Python 3 logging setup

Doing a few things here:

  1. Showing log output in the console
  2. Writing log output to a file
  3. Set logger level

import logging
LOG_FILE = "your_log_file.log"
logger = logging.getLogger(__name__)
# Set up console handler for logging
ch = logging.StreamHandler()
# Set up file handler for logging
fh = logging.FileHandler(LOG_FILE)
# Make the log messages look nice
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Apply the formatter to console and file loggers
ch.setFormatter(formatter)
fh.setFormatter(formatter)
logger.addHandler(ch)
logger.addHandler(fh)
# Catch all log messages of INFO or higher(debug, critical, etc)
logger.setLevel(logging.INFO)
# Also set the level of the logger itself
# https://mail.python.org/pipermail/python-list/2010-March/572131.html
from logging.getLogger().setLevel(logging.INFO)

Then log messages like so:
logger.info("This is working now")
logger.debug("A behind-the-scenes message")
logger.warn("This post is getting too long")

Leave a Reply

Your email address will not be published. Required fields are marked *