Monday, February 2, 2015

Python logging module basics

The Python logging module organizes loggers in a hierarchy. All loggers are descendants of the root logger. Each logger passes log messages on to its parent. So in effect, you have two ways of configuring logging.

1. Setup the configuration at a particular logger level.

2. Setup the configuration at the root level. If a particular logger doesn't have a configuration, the default(root) level configuration will be used.


To configure the root level logger, use the following snippet in your main entry script.


import logging
LOG_LEVEL = logging.DEBUG
logger = logging.getLogger() # Gets the root logger
logger.setLevel(LOG_LEVEL)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(LOG_LEVEL)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
logger.addHandler(handler)


Then in all other modules, you can add two simple lines to create a module level logger. As the module level logger doesn't have any configuration, it will use the root level logger configuration.
import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

You can configure the root logger by using the logging.basicConfig() function.

logging.getLogger(name)

Return a logger with the specified name or, if no name is specified, return a logger which is the root logger of the hierarchy. If specified, the name is typically a dot-separated hierarchical name like “a”, “a.b” or “a.b.c.d”. Choice of these names is entirely up to the developer who is using logging.