Skip to content

Instantly share code, notes, and snippets.

@coffeejoshua
Last active December 21, 2022 02:51
Show Gist options
  • Save coffeejoshua/cb3e57af6cb8f7442266fed15a5945f0 to your computer and use it in GitHub Desktop.
Save coffeejoshua/cb3e57af6cb8f7442266fed15a5945f0 to your computer and use it in GitHub Desktop.
An example logger for Python3
#!/usr/bin/env python3
# Adapted from https://docs.python.org/2/howto/logging-cookbook.html
'''
pylogging.py - Template to add logging to something in Python3
Logging level accepts strings or a numeral value:
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0 (Default, logs at warning for some reason)
'''
import logging
# You likely want to change this to an 'spam.eggs.foo' string for smaller projects.
# This value sets the minimum for the program, so if this is set to INFO for example and others
# attempt to use a lower level like DEBUG, it will still only log INFO or higher.
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# create file handler that logs at debug to file 'file.log'
fh = logging.FileHandler('file.log')
fh.setLevel(logging.DEBUG)
# create console handler for iostream. It is common to set this to WARNING.
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)
# create formatter and add it to the handlers
# Uses time.strftime(format[, t]), see
# https://docs.python.org/3/library/time.html#time.strftime
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
#logging examples.
logger.critical("logger message critical")
logger.error("logger message error")
logger.warning("logger message warning, this is also sometimes called notice")
logger.info("logger message info")
logger.debug("logger message debug")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment