加载中...

13.11 给简单脚本增加日志功能


问题

You want scripts and simple programs to write diagnostic information to log files.

解决方案

The easiest way to add logging to simple programs is to use the logging module. Forexample:

import logging

def main():

Configure the logging systemlogging.basicConfig(

filename='app.log',level=logging.ERROR

)

Variables (to make the calls that follow work)hostname = ‘www.python.org'item = ‘spam'filename = ‘data.csv'mode = ‘r'

Example logging calls (insert into your program)logging.critical(‘Host %s unknown', hostname)logging.error(“Couldn't find %r”, item)logging.warning(‘Feature is deprecated')logging.info(‘Opening file %r, mode=%r', filename, mode)logging.debug(‘Got here')

if name == ‘main':main()
The five logging calls (critical(), error(), warning(), info(), debug()) representdifferent severity levels in decreasing order. The level argument to basicConfig() isa filter. All messages issued at a level lower than this setting will be ignored.The argument to each logging operation is a message string followed by zero or morearguments. When making the final log message, the % operator is used to format themessage string using the supplied arguments.If you run this program, the contents of the file app.log will be as follows:

CRITICAL:root:Host www.python.org unknownERROR:root:Could not find ‘spam'

If you want to change the output or level of output, you can change the parameters tothe basicConfig() call. For example:

logging.basicConfig(filename='app.log',level=logging.WARNING,format='%(levelname)s:%(asctime)s:%(message)s')
As a result, the output changes to the following:

CRITICAL:2012-11-20 12:27:13,595:Host www.python.org unknownERROR:2012-11-20 12:27:13,595:Could not find ‘spam'WARNING:2012-11-20 12:27:13,595:Feature is deprecated

As shown, the logging configuration is hardcoded directly into the program. If you wantto configure it from a configuration file, change the basicConfig() call to the following:

import loggingimport logging.config

def main():# Configure the logging systemlogging.config.fileConfig(‘logconfig.ini')...
Now make a configuration file logconfig.ini that looks like this:

[loggers]keys=root

[handlers]keys=defaultHandler

[formatters]keys=defaultFormatter

[logger_root]level=INFOhandlers=defaultHandlerqualname=root

[handler_defaultHandler]class=FileHandlerformatter=defaultFormatterargs=(‘app.log', ‘a')

[formatter_defaultFormatter]format=%(levelname)s:%(name)s:%(message)s

If you want to make changes to the configuration, you can simply edit the logcon‐fig.ini file as appropriate.

讨论

Ignoring for the moment that there are about a million advanced configuration optionsfor the logging module, this solution is quite sufficient for simple programs and scripts.Simply make sure that you execute the basicConfig() call prior to making any loggingcalls, and your program will generate logging output.If you want the logging messages to route to standard error instead of a file, don’t supplyany filename information to basicConfig(). For example, simply do this:

logging.basicConfig(level=logging.INFO)

One subtle aspect of basicConfig() is that it can only be called once in your program.If you later need to change the configuration of the logging module, you need to obtainthe root logger and make changes to it directly. For example:

logging.getLogger().level = logging.DEBUG

It must be emphasized that this recipe only shows a basic use of the logging module.There are significantly more advanced customizations that can be made. An excellentresource for such customization is the “Logging Cookbook”.


还没有评论.