Thursday 24 December 2015

Python: Naming loggers

You can give any name to the logger. Multiple calls to getLogger() with the same name will return a reference to the same logger object.


For example,
import logging

logger = logging.getLogger("My Logger")
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')

def logMessages():
    logger.debug("Debug message")
    logger.info("Information Message")
    logger.warn("Warning Message")
    logger.error("Error Message")
    logger.critical("Critical Message")

if (__name__ == "__main__"):
    logMessages()


Run above program, you will get following output.
2015-10-22 23:29:07,698 My Logger    DEBUG    Debug message
2015-10-22 23:29:07,698 My Logger    INFO     Information Message
2015-10-22 23:29:07,698 My Logger    WARNING  Warning Message
2015-10-22 23:29:07,698 My Logger    ERROR    Error Message
2015-10-22 23:29:07,698 My Logger    CRITICAL Critical Message


Observe the output, you logger name ‘My Logger’ is printed in console.

Usually module name is used as logger. Following statement is the common way to specify module name.

logger= logging.getLogger( __name__ )

logging_tutorial.py
import logging

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')

def logMessages():
    logger.debug("Debug message")
    logger.info("Information Message")
    logger.warn("Warning Message")
    logger.error("Error Message")
    logger.critical("Critical Message")


loggingEx.py
import logging_tutorial

logging_tutorial.logMessages()


Run above program, you will get following messages.
2015-10-22 23:40:02,337 logging_tutorial DEBUG    Debug message
2015-10-22 23:40:02,337 logging_tutorial INFO     Information Message
2015-10-22 23:40:02,337 logging_tutorial WARNING  Warning Message
2015-10-22 23:40:02,337 logging_tutorial ERROR    Error Message
2015-10-22 23:40:02,337 logging_tutorial CRITICAL Critical Message


Observe the output, module name ‘logging_tutorial’ is printed in console.



Previous                                                 Next                                                 Home

No comments:

Post a Comment