© svl861, 123RF.com

© svl861, 123RF.com

The logging module in Python

Log Normal

Article from ADMIN 08/2012
By
Logging frameworks are a good idea, even for DIY scripts, because they allow programmers to redirect program messages to logfiles. Python developers can turn to the logging module described here.

How many times have you added a print statement to your programs and scripts to see exactly why something is not working as expected? A separate function to let you output these messages or hide them at the flip of a switch would be a more elegant approach. However, both methods are unnecessary with Python, which has a powerful logging module to greatly facilitate development. For example, in web projects, you typically do not have a standard output channel, so the logging module can redirect program output to syslog.

The module was written by Vinay Sajip, who describes the concept in Python standard document PEP 282 [1] and has documented the implementation on his own website [2]. The developer put much thought into his work and was inspired by Java's log4j, among other things. In Python 2.3, the logging module [3] was finally added to the standard library, so assuming you have Python in place, you have nothing to install. To use the module, import it at the start of a script, like this:

import logging

The module provides static functions like debug, info, and warning that let you output information at different logging levels. The principle is perhaps best known from Unix/Linux daemons, such as Apache and the corresponding syslog daemon. Debug is the highest level and includes all the lower levels, such as Notice and Error.

After selecting the Debug logging level, the user gets to see every single piece of information that is output. The Warning log level doesn't include debug messages but still includes all error messages. The Python module doesn't implement all of the Unix syslog levels; rather, it takes a more pragmatic approach of just using five levels, as shown in

...
Use Express-Checkout link below to read the full article (PDF).

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy ADMIN Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

comments powered by Disqus
Subscribe to our ADMIN Newsletters
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs



Support Our Work

ADMIN content is made possible with support from readers like you. Please consider contributing when you've found an article to be beneficial.

Learn More”>
	</a>

<hr>		    
			</div>
		    		</div>

		<div class=