Skip to content

Instantly share code, notes, and snippets.

@miebach
Last active December 16, 2015 00:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miebach/5349852 to your computer and use it in GitHub Desktop.
Save miebach/5349852 to your computer and use it in GitHub Desktop.
Python logging example
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Python logging demo from https://gist.github.com/miebach/5349852
import logging
# see http://www.shutupandship.com/2012/02/how-python-logging-module-works.html
def init_file_logger(fname="log.txt",threshhold_level="info",logger_instance=""):
# Initialize a new logger instance and optionally return it.
# You can later always get the instance by calling logging.getLogger(logger_instance)
# Levels are CRITICAL <- ERROR <- WARNING <- INFO <- DEBUG
h = logging.FileHandler(fname)
l = logging.getLogger(logger_instance)
l.handlers=[]
l.addHandler(h)
if threshhold_level == "debug":
l.setLevel(logging.DEBUG)
elif threshhold_level == "info":
l.setLevel(logging.INFO)
elif threshhold_level == "warning":
l.setLevel(logging.WARNING)
elif threshhold_level == "error":
l.setLevel(logging.ERROR)
elif threshhold_level == "critical":
l.setLevel(logging.CRITICAL)
return l
## 1) Application initialisation and simple demo:
# Create a root file logger (logger_instance='')
root_log = init_file_logger() # get a root logger instance with INFO level using file "log.txt"
# the root logger will also log all messages from the other loggers
# create and use 2 different file loggers:
logger1 = init_file_logger('log1.txt',logger_instance="LOG1") # get a logger instance with INFO level using file "log1.txt"
logger1.info("msg 1 for log1.txt (also goes to root logger)")
logger2a = init_file_logger('log2.txt',"warning",logger_instance="LOG2")
logger2a.debug("msg 2 is dropped") # "debug" level is below "warning"
logger2a.critical("msg 3 for log2.txt (also goes to root logger)")
## 2) This could be in a differnt module that runs later:
# All loggers are application global and can be used from any module.
import logging
# the second time we access LOG2, we don't initialize it again.
logger2b = logging.getLogger("LOG2") # logger2b is the same than logger2a
logger2b.critical("msg 4 for log2.txt again (also goes to root logger)")
# The instances are organized in a tree, identified by a dotted instance name.
# Messages to a specific instance also go to all parents and also to the root logger:
logger1sub = init_file_logger('log1sub.txt',logger_instance="LOG1.SUB")
logger1sub.info("msg 5 for log1sub.txt - also goes to log1.txt (and also to the root logger)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment