Thursday 15 January 2015

Logging in python

I wanted to implement a python logging module which I can call from multiple python modules with my own logger settings. I was going through Python documentation on logging and I can only say, it is amazing!! You get swamped by the features offered!

Ultimately, here is how I decided to use the logging:

log.py:
-----------
#! /usr/bin/env python
import logging

def setup_logging(name):

    """ set up logging
    """

    logging.basicConfig(level=logging.DEBUG)  # (level=logging.INFO)
    #logger = logging.getLogger(__name__)
    logger = logging.getLogger(name)
  
   # set up file handler
    handler = logging.FileHandler('main.log')
    handler.setLevel(logging.DEBUG)

    # logging format
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)

    # add the handlers to the logger
    logger.addHandler(handler)
    return logger

main.py:
--------------
#! /usr/bin/env python
import log
logger = log.setup_logging('root')
logger.debug('main message')

No comments:

Post a Comment