Thursday 24 December 2015

Python: logging: format logging messages


By setting ‘format’ argument to logging.basicConfig() method, we can format the log messages.

import logging

logger = logging.getLogger()
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s %(funcName)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 22:55:19,096 root         DEBUG    Debug message logMessages
2015-10-22 22:55:19,096 root         INFO     Information Message logMessages
2015-10-22 22:55:19,096 root         WARNING  Warning Message logMessages
2015-10-22 22:55:19,097 root         ERROR    Error Message logMessages
2015-10-22 22:55:19,097 root         CRITICAL Critical Message logMessages

Following are different format attributes supported by python.
Format
Description
%(asctime)s
Displays the time of log record creation in human readable format. The format is of the form '2015-10-22 22:55:19,096'. The numbers after the comma (,) represents milli seconds.
%(created)f
Represents the time when the LogRecord was created.
%(filename)s
File name portion of the pathname.
%(funcName)s
Name of the function is logged
%(levelname)s
Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
%(levelno)s
Numeric logging level for the message.
%(lineno)d
Line number, from where the logging call was issued.
%(module)s
Module name
%(msecs)d
Millisecond portion of the time when the LogRecord was created.
%(message)s
The logged message, computed as msg % args.
%(name)s
Name of the logger used to log the call.
%(pathname)s
Full pathname of the source file where the logging call was issued
%(process)d
Process Id
%(processName)s
Process Name
%(relativeCreated)d
Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
%(thread)d
Thread ID.
%(threadName)s
Thread name





Previous                                                 Next                                                 Home

No comments:

Post a Comment