Friday, 1 January 2016

Python: formatters

Formatters are used to format log records. ‘logging’ module provides Formatter class to initialize formatter.

logging.Formatter.__init__(fmt=None, datefmt=None, style='%')
Argument
Description
fmt
Specify the format of log record.
For example,
fmt='[%(levelname)s] %(message)s'
datefmt
If there is no date format string, the default date format is: '%Y-%m-%d %H:%M:%S'
style
The style is one of %, ‘{‘ or ‘$’. If one of these is not specified, then ‘%’ will be used.

If the style is ‘%’, the message format string uses %(<dictionary key>)s styled string substitution.

If the style is ‘{‘, the message format string is assumed to be compatible with str.format().

If the style is ‘$’ then the message format string should conform to what is expected by string.Template.substitute().


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

import logging
import logging.handlers
import time

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

LOG_FILENAME="temp.log"
#Define handler to write to standard output
handler = logging.FileHandler(LOG_FILENAME)

formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)

#Adding handler to logger
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

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 in console.
2015-10-24 09:26:07,783 __main__     DEBUG    Debug message
2015-10-24 09:26:07,783 __main__     INFO     Information Message
2015-10-24 09:26:07,783 __main__     WARNING  Warning Message
2015-10-24 09:26:07,783 __main__     ERROR    Error Message
2015-10-24 09:26:07,784 __main__     CRITICAL Critical Message


You will get following output in temp.log file.
2015-10-24 09:28:08,914 - DEBUG - Debug message
2015-10-24 09:28:08,914 - INFO - Information Message
2015-10-24 09:28:08,914 - WARNING - Warning Message
2015-10-24 09:28:08,914 - ERROR - Error Message
2015-10-24 09:28:08,914 - CRITICAL - Critical Message









Previous                                                 Next                                                 Home

No comments:

Post a Comment