Tuesday 22 December 2015

Python: logging hello world example


Unlike other languages, python logging is very simple, just import logging package, define logger object and call logging methods to log messages.
import logging

logger = logging.getLogger()
logging.basicConfig(level=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.
DEBUG:root:Debug message
INFO:root:Information Message
WARNING:root:Warning Message
ERROR:root:Error Message
CRITICAL:root:Critical Message

Observe the output, each log message includes the level and the description of the event provided in the logging call. The root of the hierarchy of loggers is called the root logger. The root logger’s name is printed as ‘root’ in the logged output.

I don’t specify any format for log messages. The default format is ‘severity:logger name:message’. You can change this default formatting by passing format argument to logging.basicConfig() method. Later posts explain how to format log messages

logger = logging.getLogger()
‘getLogger()’ method returns a reference to a logger instance with the specified name if it is provided. You can pass a name to getLogger method, it is optional. The names are period-separated hierarchical structures like com.foo, com.foo.bar etc., I will explain about this name hierarchy later.

logging.basicConfig(level=logging.DEBUG)
By using this method, we can set the basic configuration for a logger. Above statement sets the logging level to DEBUG. Default logging level is Warning.

‘basicConfig’ method support following arguments.
Argument
Description
filename
Specifies the file name to store log messages
filemode
Specifies the mode of the file, by default opens in append mode.
format
Used to format log messages.
datefmt
Use the specified date/time format.
style
If format is specified, use this style for the format string.
level
Set the root logger level to the specified level.
stream
Use the specified stream to initialize the StreamHandler. You shouldn’t use filename and stream together. If both are present, a ValueError is raised.
handler
Handlers send the log records to the appropriate destination







Previous                                                 Next                                                 Home

No comments:

Post a Comment