Friday, July 11, 2014

simple way to add logging to your python project

#import the relevant module 
import logging
#you can give you specific name or use the module name
logger = logging.getLogger(__name__)
#if you see duplicate logs .. this should solve the problem for you
#duplicate logs are because there is some other logger catching your logs too
logger.propagate = False
# again multiple handlers can lead to duplicate logs .. so  check before adding new handler

if not logger.handlers:
    #suit yourself and specify whatever format you want easily
    frmt = logging.Formatter('%(asctime)s  %(name)s  %(levelname)s  %(message)s')
    #console
    hdlr = logging.StreamHandler()
    hdlr.setFormatter(frmt)
    logger.addHandler(hdlr)
    #you decide what level of info you want info/dbg/criticla/warn
    logger.setLevel(logging.DEBUG)






now you are ready to publish logs .. sample :-

def test_a(logger):
    logger.debug("debug")
    logger.info("info")
    logger.warning("warning")
    logger.error("error")





for more info refer


https://docs.python.org/2/library/logging.html

No comments:

Post a Comment