Python: Logging

This is part of my Python & Django Series which can be found here including information on how to download all the source code.

The logging module provides the ability to add conditional logging into any code.

Levels

Logging is associated with a level of seriousness which starts at debug information and ends up at a critical system.

Level Description
Debug Debug information
Info Information
Warning Warning
Error Error
Critical Critical

When we log information we provide the level along with the message.

Code:

import logging

logging.debug('Debug Info')
logging.info('Info')
logging.warning('Warning')
logging.error('Error')
logging.critical('Critical Error')

We configure the active level with the level parameter of the basicconfig function. Only entities which are equal to or of a higher seriousness are reported. By default the level is set to WARNING.

Code:

logging.basicConfig(level=logging.WARNING)   # Set report level

Output:

WARNING:root:Warning
ERROR:root:Error
CRITICAL:root:Critical Error

If we changed the level to debug we would output the following.

Output:

DEBUG:root:Debug Info
INFO:root:Info
WARNING:root:Warning
ERROR:root:Error
CRITICAL:root:Critical Error

Logging To A File

By default the messages are logged to a terminal. We can log to a file with the filename parameter.

Code:

logging.basicConfig(filename='log.txt',level=logging.DEBUG)

By default messages are appended to the log file between application runs. We can overwrite the file each time by setting the filemode parameter to ‘w’.

Code:

logging.basicConfig(filename='log.txt',level=logging.DEBUG, filemode="w")

Format

We can define the format of the messages in a number of ways.

First lets add the time to the output message.

Code:

logging.basicConfig(format='%(asctime)s %(message)s')

Output:

2015-06-10 19:19:03,578 Warning
2015-06-10 19:19:03,579 Error
2015-06-10 19:19:03,579 Critical Error

We can also add new templates into the format and pass the data as key value pairs into the logging message.

Below we add in the templates ip and user into the format string, these are then populated by the parameter named extra which should be a dictionary.

Code:

logging.basicConfig(format='%(asctime)-15s %(ip)s %(user)-8s %(message)s')
logging.critical('Critical %s', 'Error', extra = {'ip': '192.168.0.1', 'user': 'luke'})

Output:

2015-06-10 19:55:01,698 192.168.0.1 luke Critical Error

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s