Logging in Python

Example of configuring logging in Python:

import logging

# Create logger and set the level (and higher) we are logging
logger = logging.getLogger("MyProgram")
logger.setLevel(logging.INFO)
# Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL
# INFO = log messages of level INFO and higher

# Set the output format to use
formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s: %(message)s")

# Enable logging to console
console_logging = logging.StreamHandler()
console_logging.setFormatter(formatter)
logger.addHandler(console_logging)

# Enable logging to a file
file_logging = logging.FileHandler("logtest.log")
file_logging.setFormatter(formatter)
logger.addHandler(file_logging)

# Now test the logging:
logger.info("First message to be logged")

# This does not log anything yet:
logger.debug("Low-level status information here")

# Adjust the logging level and retry debug logging:
logger.setLevel(logging.DEBUG)
logger.debug("Low-level status information finally here")

Output:

$ python3 logtest.py
2019-04-14 20:05:31,493 MyProgram INFO: First message to be logged
2019-04-14 20:05:31,493 MyProgram DEBUG: Low-level status information finally here
$ cat logtest.log
2019-04-14 20:05:31,493 MyProgram INFO: First message to be logged
2019-04-14 20:05:31,493 MyProgram DEBUG: Low-level status information finally here

More information: https://docs.python.org/3/library/logging.html

Updated: April 15, 2019 — 14:12

Leave a Reply