Skip to content

Instantly share code, notes, and snippets.

@krystofl
Last active March 26, 2020 20:52
Show Gist options
  • Save krystofl/3be114668a8f60fcdfc6f9520f1d57d8 to your computer and use it in GitHub Desktop.
Save krystofl/3be114668a8f60fcdfc6f9520f1d57d8 to your computer and use it in GitHub Desktop.
Python Logging Demo
{
"version": 1,
"loggers": {
"": {
"level" : "DEBUG",
"handlers": ["console_handler"]
}
},
"handlers": {
"console_handler": {
"level" : "DEBUG",
"formatter": "logfmt",
"class" : "logging.StreamHandler"
}
},
"formatters": {
"logfmt": {
"format" : "dt=%(asctime)s lvl=%(levelname)s msg=\"%(message)s\"",
"datefmt": "%Y-%m-%d_%H:%M:%S"
}
}
}
#!/usr/bin/python3
'''
Demonstrate how logging in python works
https://docs.python.org/3.8/library/logging.html
'''
import logging
import logging.config
import json # for loading config from file
if __name__ == '__main__':
CONFIG_FROM_FILE = True
if CONFIG_FROM_FILE:
# load the config from a file
# fileConfig() is getting deprecated, so use the newer dictConfig()
# https://docs.python.org/3/library/logging.config.html#logging.config.dictConfig
with open('logger_config.json', 'r') as f:
cd = json.load(f)
logging.config.dictConfig(cd)
# create the logger
logger = logging.getLogger('my-logger-name')
else: # config not from file - do it from here
logger = logging.getLogger('my-logger-name')
# set output to terminal only
# each output stream gets its own handler
handler = logging.StreamHandler()
# set the logging level
# logging levels: https://docs.python.org/3.8/library/logging.html#logging-levels
# CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET
handler.setLevel(logging.DEBUG)
# set the log format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
# output messages at different levels
logger.debug("this is a DEBUG message")
logger.info("this is an info message")
logger.warning("this is a warning message")
logger.error("this is an error message")
logger.critical("this is a CRITICAL message")
logger.log(logging.INFO, "this is another way to make an INFO message")
# a special case of ERROR - adds exception info to the logging message
try:
raise Exception("someone set us up the bomb")
except Exception as e:
logger.exception("this is an EXCEPTION message")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment