Monday, September 14, 2015

Better logging with logging

I've been using Python for more than 2 years now. It's sad that I never came across the amazing logging library. I was relying on the plain old print and used .format to its full potential.

Now that I know about logging, I can't think of using anything else.

There are various approaches to initialize the logging module. I prefer the one with the config file. That way it's easier to configure the format etc.

This is a sample python code using the logging library
import logging
import logging.config

logging.config.fileConfig('loggerconfig.ini')
logger = logging.getLogger('server')

def testmodule():
    logger.info("This is a test info message")
    logger.critical("This is a test critical message")

testmodule()
Output of this sample code:
[10-11-15 23:55:12]  INFO     test                      This is a test info message (testmodule:8)
[10-11-15 23:55:12]  CRITICAL test                      This is a test critical message (testmodule:9)
This is the sample loggerconfig.ini file used to achieve the above output
[loggers]
keys=root,server

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_server]
level=DEBUG
handlers=consoleHandler
qualname=server
propagate=0

;Available debug levels
;CRITICAL 50 ERROR 40 WARNING 30 INFO 20 DEBUG 10 NOTSET 0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=[%(asctime)s]  %(levelname)-8s %(module)-25s %(message)s (%(funcName)s:%(lineno)d)
datefmt=%m-%d-%y %H:%M:%S

format and datefmt are the most important fields in the config file which you need to edit to get the desired output. List of all the attributes are documented here

No comments:

Post a Comment