Logging HOWTO: Guido Van Rossum Fred L. Drake, JR., Editor
Logging HOWTO: Guido Van Rossum Fred L. Drake, JR., Editor
Release 2.7.6
Contents
1 Basic Logging Tutorial 1.1 When to use logging . . . . . . . . . . . . 1.2 A simple example . . . . . . . . . . . . . . 1.3 Logging to a le . . . . . . . . . . . . . . . 1.4 Logging from multiple modules . . . . . . 1.5 Logging variable data . . . . . . . . . . . . 1.6 Changing the format of displayed messages 1.7 Displaying the date/time in messages . . . . 1.8 Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii ii ii iii iv iv v v v
Advanced Logging Tutorial 2.1 Logging Flow . . . . . . . . . . . . . . . . . 2.2 Loggers . . . . . . . . . . . . . . . . . . . . 2.3 Handlers . . . . . . . . . . . . . . . . . . . . 2.4 Formatters . . . . . . . . . . . . . . . . . . . 2.5 Conguring Logging . . . . . . . . . . . . . 2.6 What happens if no conguration is provided 2.7 Conguring Logging for a Library . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
Logging Levels xiii 3.1 Custom Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii Useful Handlers Exceptions raised during logging Using arbitrary objects as messages xiv xv xv xv
4 5 6
7 Optimization Indexxvii
Report an error regarding a particular runtime event Report suppression of an error without raising an exception (e.g. error handler in a long-running server process)
The logging functions are named after the level or severity of the events they are used to track. The standard levels and their applicability are described below (in increasing order of severity): Level DEBUG INFO WARNING ERROR CRITICAL When its used Detailed information, typically of interest only when diagnosing problems. Conrmation that things are working as expected. An indication that something unexpected happened, or indicative of some problem in the near future (e.g. disk space low). The software is still working as expected. Due to a more serious problem, the software has not been able to perform some function. A serious error, indicating that the program itself may be unable to continue running.
The default level is WARNING, which means that only events of this level and above will be tracked, unless the logging package is congured to do otherwise. Events that are tracked can be handled in different ways. The simplest way of handling tracked events is to print them to the console. Another common way is to write them to a disk le.
WARNING:root:Watch out! printed out on the console. The INFO message doesnt appear because the default level is WARNING. The printed message includes the indication of the level and the description of the event provided in the logging call, i.e. Watch out!. Dont worry about the root part for now: it will be explained later. The actual output can be formatted quite exibly if you need that; formatting options will also be explained later.
1.3 Logging to a le
A very common situation is that of recording logging events in a le, so lets look at that next. Be sure to try the following in a newly-started Python interpreter, and dont just continue from the session described above: import logging logging.basicConfig(filename=example.log,level=logging.DEBUG) logging.debug(This message should go to the log file) logging.info(So should this) logging.warning(And this, too) And now if we open the le and look at what we have, we should nd the log messages: DEBUG:root:This message should go to the log file INFO:root:So should this WARNING:root:And this, too This example also shows how you can set the logging level which acts as the threshold for tracking. In this case, because we set the threshold to DEBUG, all of the messages were printed. If you want to set the logging level from a command-line option such as: --log=INFO and you have the value of the parameter passed for --log in some variable loglevel, you can use: getattr(logging, loglevel.upper()) to get the value which youll pass to basicConfig() via the level argument. You may want to error check any user input value, perhaps as in the following example: # assuming loglevel is bound to the string value obtained from the # command line argument. Convert to upper case to allow the user to # specify --log=DEBUG or --log=debug numeric_level = getattr(logging, loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError(Invalid log level: %s % loglevel) logging.basicConfig(level=numeric_level, ...) The call to basicConfig() should come before any calls to debug(), info() etc. As its intended as a one-off simple conguration facility, only the rst call will actually do anything: subsequent calls are effectively no-ops. If you run the above script several times, the messages from successive runs are appended to the le example.log. If you want each run to start afresh, not remembering the messages from earlier runs, you can specify the lemode argument, by changing the call in the above example to: logging.basicConfig(filename=example.log, filemode=w, level=logging.DEBUG) The output will be the same as before, but the log le is no longer appended to, so the messages from earlier runs are lost.
logging.debug(This message should appear on the console) logging.info(So should this) logging.warning(And this, too) which would print: DEBUG:This message should appear on the console INFO:So should this WARNING:And this, too Notice that the root which appeared in earlier examples has disappeared. For a full set of things that can appear in format strings, you can refer to the documentation for logrecord-attributes, but for simple usage, you just need the levelname (severity), message (event description, including variable data) and perhaps to display when the event occurred. This is described in the next section.
Loggers expose the interface that application code directly uses. Handlers send the log records (created by loggers) to the appropriate destination. Filters provide a ner grained facility for determining which log records to output. Formatters specify the layout of log records in the nal output. Log event information is passed between loggers, handlers, lters and formatters in a LogRecord instance. Logging is performed by calling methods on instances of the Logger class (hereafter called loggers). Each instance has a name, and they are conceptually arranged in a namespace hierarchy using dots (periods) as separators. For example, a logger named scan is the parent of loggers scan.text, scan.html and scan.pdf. Logger names can be anything you want, and indicate the area of an application in which a logged message originates. A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows: logger = logging.getLogger(__name__) This means that logger names track the package/module hierarchy, and its intuitively obvious where events are logged just from the logger name. The root of the hierarchy of loggers is called the root logger. Thats the logger used by the functions debug(), info(), warning(), error() and critical(), which just call the same-named method of the root logger. The functions and the methods have the same signatures. The root loggers name is printed as root in the logged output. It is, of course, possible to log messages to different destinations. Support is included in the package for writing log messages to les, HTTP GET/POST locations, email via SMTP, generic sockets, or OS-specic logging mechanisms such as syslog or the Windows NT event log. Destinations are served by handler classes. You can create your own log destination class if you have special requirements not met by any of the built-in handler classes. By default, no destination is set for any logging messages. You can specify a destination (such as console or le) by using basicConfig() as in the tutorial examples. If you call the functions debug(), info(), warning(), error() and critical(), they will check to see if no destination is set; and if one is not set, they will set a destination of the console (sys.stderr) and a default format for the displayed message before delegating to the root logger to do the actual message output. The default format set by basicConfig() for messages is: severity:logger name:message You can change this by passing a format string to basicConfig() with the format keyword argument. For all options regarding how a format string is constructed, see formatter-objects.
2.2 Loggers
Logger objects have a threefold job. First, they expose several methods to application code so that applications can log messages at runtime. Second, logger objects determine which log messages to act upon based upon severity (the default ltering facility) or lter objects. Third, logger objects pass along relevant log messages to all interested log handlers. The most widely used methods on logger objects fall into two categories: conguration and message sending. These are the most common conguration methods: Logger.setLevel() species the lowest-severity log message a logger will handle, where debug is the lowest built-in severity level and critical is the highest built-in severity. For example, if the severity level is INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages and will ignore DEBUG messages. Logger.addHandler() and Logger.removeHandler() add and remove handler objects from the logger object. Handlers are covered in more detail in Handlers. Logger.addFilter() and Logger.removeFilter() add and remove lter objects from the logger object. Filters are covered in more detail in lter. You dont need to always call these methods on every logger you create. See the last two paragraphs in this section.
With the logger object congured, the following methods create log messages: Logger.debug(), Logger.info(), Logger.warning(), Logger.error(), and Logger.critical() all create log records with a message and a level that corresponds to their respective method names. The message is actually a format string, which may contain the standard string substitution syntax of %s, %d, %f, and so on. The rest of their arguments is a list of objects that correspond with the substitution elds in the message. With regard to **kwargs, the logging methods care only about a keyword of exc_info and use it to determine whether to log exception information. Logger.exception() creates a log message similar to Logger.error(). The difference is that Logger.exception() dumps a stack trace along with it. Call this method only from an exception handler. Logger.log() takes a log level as an explicit argument. This is a little more verbose for logging messages than using the log level convenience methods listed above, but this is how to log at custom log levels. getLogger() returns a reference to a logger instance with the specied name if it is provided, or root if not. The names are period-separated hierarchical structures. Multiple calls to getLogger() with the same name will return a reference to the same logger object. Loggers that are further down in the hierarchical list are children of loggers higher up in the list. For example, given a logger with a name of foo, loggers with names of foo.bar, foo.bar.baz, and foo.bam are all descendants of foo. Loggers have a concept of effective level. If a level is not explicitly set on a logger, the level of its parent is used instead as its effective level. If the parent has no explicit level set, its parent is examined, and so on - all ancestors are searched until an explicitly set level is found. The root logger always has an explicit level set (WARNING by default). When deciding whether to process an event, the effective level of the logger is used to determine whether the event is passed to the loggers handlers. Child loggers propagate messages up to the handlers associated with their ancestor loggers. Because of this, it is unnecessary to dene and congure handlers for all the loggers an application uses. It is sufcient to congure handlers for a top-level logger and create child loggers as needed. (You can, however, turn off propagation by setting the propagate attribute of a logger to False.)
2.3 Handlers
Handler objects are responsible for dispatching the appropriate log messages (based on the log messages severity) to the handlers specied destination. Logger objects can add zero or more handler objects to themselves with an addHandler() method. As an example scenario, an application may want to send all log messages to a log le, all log messages of error or higher to stdout, and all messages of critical to an email address. This scenario requires three individual handlers where each handler is responsible for sending messages of a specic severity to a specic location. The standard library includes quite a few handler types (see Useful Handlers); the tutorials use mainly StreamHandler and FileHandler in its examples. There are very few methods in a handler for application developers to concern themselves with. The only handler methods that seem relevant for application developers who are using the built-in handler objects (that is, not creating custom handlers) are the following conguration methods: The setLevel() method, just as in logger objects, species the lowest severity that will be dispatched to the appropriate destination. Why are there two setLevel() methods? The level set in the logger determines which severity of messages it will pass to its handlers. The level set in each handler determines which messages that handler will send on. setFormatter() selects a Formatter object for this handler to use. addFilter() and removeFilter() respectively congure and decongure lter objects on handlers.
Application code should not directly instantiate and use instances of Handler. Instead, the Handler class is a base class that denes the interface that all handlers should have and establishes some default behavior that child classes can use (or override).
2.4 Formatters
Formatter objects congure the nal order, structure, and contents of the log message. Unlike the base logging.Handler class, application code may instantiate formatter classes, although you could likely subclass the formatter if your application needs special behavior. The constructor takes two optional arguments a message format string and a date format string. logging.Formatter.__init__(fmt=None, datefmt=None) If there is no message format string, the default is to use the raw message. If there is no date format string, the default date format is: %Y-%m-%d %H:%M:%S with the milliseconds tacked on at the end. The message format string uses %(<dictionary key>)s styled string substitution; the possible keys are documented in logrecord-attributes. The following message format string will log the time in a human-readable format, the severity of the message, and the contents of the message, in that order: %(asctime)s - %(levelname)s - %(message)s Formatters use a user-congurable function to convert the creation time of a record to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the converter attribute of the instance to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the converter attribute in the Formatter class (to time.gmtime for GMT display).
formatter = logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s) # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) # application code logger.debug(debug message) logger.info(info message) logger.warn(warn message) logger.error(error message) logger.critical(critical message) Running this module from the command line produces the following output: $ python simple_logging_module.py 2005-03-19 15:10:26,618 - simple_example 2005-03-19 15:10:26,620 - simple_example 2005-03-19 15:10:26,695 - simple_example 2005-03-19 15:10:26,697 - simple_example 2005-03-19 15:10:26,773 - simple_example DEBUG - debug message INFO - info message WARNING - warn message ERROR - error message CRITICAL - critical message
The following Python module creates a logger, handler, and formatter nearly identical to those in the example listed above, with the only difference being the names of the objects: import logging import logging.config logging.config.fileConfig(logging.conf) # create logger logger = logging.getLogger(simpleExample) # application code logger.debug(debug message) logger.info(info message) logger.warn(warn message) logger.error(error message) logger.critical(critical message) Here is the logging.conf le: [loggers] keys=root,simpleExample [handlers] keys=consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler
[logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt= The output is nearly identical to that of the non-cong-le-based example: $ python simple_logging_config.py 2005-03-19 15:38:55,977 - simpleExample 2005-03-19 15:38:55,979 - simpleExample 2005-03-19 15:38:56,054 - simpleExample 2005-03-19 15:38:56,055 - simpleExample 2005-03-19 15:38:56,130 - simpleExample DEBUG - debug message INFO - info message WARNING - warn message ERROR - error message CRITICAL - critical message
You can see that the cong le approach has a few advantages over the Python code approach, mainly separation of conguration and code and the ability of noncoders to easily modify the logging properties. Warning: The fileConfig() function takes a default parameter, disable_existing_loggers, which defaults to True for reasons of backward compatibility. This may or may not be what you want, since it will cause any loggers existing before the fileConfig() call to be disabled unless they (or an ancestor) are explicitly named in the conguration. Please refer to the reference documentation for more information, and specify False for this parameter if you wish. The dictionary passed to dictConfig() can also specify a Boolean value with key disable_existing_loggers, which if not specied explicitly in the dictionary also defaults to being interpreted as True. This leads to the logger-disabling behaviour described above, which may not be what you want - in which case, provide the key explicitly with a value of False. Note that the class names referenced in cong les need to be either relative to the logging module, or absolute values which can be resolved using normal import mechanisms. Thus, you could use either WatchedFileHandler (relative to the logging module) or mypackage.mymodule.MyHandler (for a class dened in package mypackage and module mymodule, where mypackage is available on the Python import path). In Python 2.7, a new means of conguring logging has been introduced, using dictionaries to hold conguration information. This provides a superset of the functionality of the cong-le-based approach outlined above, and is the recommended conguration method for new applications and deployments. Because a Python dictionary is used to hold conguration information, and since you can populate that dictionary using different means, you have more options for conguration. For example, you can use a conguration le in JSON format, or, if you have access to YAML processing functionality, a le in YAML format, to populate the conguration dictionary. Or, of course, you can construct the dictionary in Python code, receive it in pickled form over a socket, or use whatever approach makes sense for your application. Heres an example of the same conguration as above, in YAML format for the new dictionary-based approach: version: 1 formatters: simple:
format: %(asctime)s - %(name)s - %(levelname)s - %(message)s handlers: console: class: logging.StreamHandler level: DEBUG formatter: simple stream: ext://sys.stdout loggers: simpleExample: level: DEBUG handlers: [console] propagate: no root: level: DEBUG handlers: [console] For more information about logging using a dictionary, see logging-cong-api.
Note: It is strongly advised that you do not add any handlers other than NullHandler to your librarys loggers. This is because the conguration of handlers is the prerogative of the application developer who uses your library. The application developer knows their target audience and what handlers are most appropriate for their application: if you add handlers under the hood, you might well interfere with their ability to carry out unit tests and deliver logs which suit their requirements.
3 Logging Levels
The numeric values of logging levels are given in the following table. These are primarily of interest if you want to dene your own levels, and need them to have specic values relative to the predened levels. If you dene a level with the same numeric value, it overwrites the predened value; the predened name is lost. Level CRITICAL ERROR WARNING INFO DEBUG NOTSET Numeric value 50 40 30 20 10 0
Levels can also be associated with loggers, being set either by the developer or through loading a saved logging conguration. When a logging method is called on a logger, the logger compares its own level with the level associated with the method call. If the loggers level is higher than the method calls, no logging message is actually generated. This is the basic mechanism controlling the verbosity of logging output. Logging messages are encoded as instances of the LogRecord class. When a logger decides to actually log an event, a LogRecord instance is created from the logging message. Logging messages are subjected to a dispatch mechanism through the use of handlers, which are instances of subclasses of the Handler class. Handlers are responsible for ensuring that a logged message (in the form of a LogRecord) ends up in a particular location (or set of locations) which is useful for the target audience for that message (such as end users, support desk staff, system administrators, developers). Handlers are passed LogRecord instances intended for particular destinations. Each logger can have zero, one or more handlers associated with it (via the addHandler() method of Logger). In addition to any handlers directly associated with a logger, all handlers associated with all ancestors of the logger are called to dispatch the message (unless the propagate ag for a logger is set to a false value, at which point the passing to ancestor handlers stops). Just as for loggers, handlers can have levels associated with them. A handlers level acts as a lter in the same way as a loggers level does. If a handler decides to actually dispatch an event, the emit() method is used to send the message to its destination. Most user-dened subclasses of Handler will need to override this emit().
4 Useful Handlers
In addition to the base Handler class, many useful subclasses are provided: 1. StreamHandler instances send messages to streams (le-like objects). 2. FileHandler instances send messages to disk les. 3. BaseRotatingHandler is the base class for handlers that rotate log les at a certain point. It is not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler. 4. RotatingFileHandler instances send messages to disk les, with support for maximum log le sizes and log le rotation. 5. TimedRotatingFileHandler instances send messages to disk les, rotating the log le at certain timed intervals. 6. SocketHandler instances send messages to TCP/IP sockets. 7. DatagramHandler instances send messages to UDP sockets. 8. SMTPHandler instances send messages to a designated email address. 9. SysLogHandler instances send messages to a Unix syslog daemon, possibly on a remote machine. 10. NTEventLogHandler instances send messages to a Windows NT/2000/XP event log. 11. MemoryHandler instances send messages to a buffer in memory, which is ushed whenever specic criteria are met. 12. HTTPHandler instances send messages to an HTTP server using either GET or POST semantics. 13. WatchedFileHandler instances watch the le they are logging to. If the le changes, it is closed and reopened using the le name. This handler is only useful on Unix-like systems; Windows does not support the underlying mechanism used. 14. NullHandler instances do nothing with error messages. They are used by library developers who want to use logging, but want to avoid the No handlers could be found for logger XXX message which can be displayed if the library user has not congured logging. See Conguring Logging for a Library for more information. New in version 2.7: The NullHandler class. The NullHandler, StreamHandler and FileHandler classes are dened in the core logging package. The other handlers are dened in a sub- module, logging.handlers. (There is also another sub-module, logging.config, for conguration functionality.) Logged messages are formatted for presentation through instances of the Formatter class. They are initialized with a format string suitable for use with the % operator and a dictionary. For formatting multiple messages in a batch, instances of BufferingFormatter can be used. In addition to the format string (which is applied to each message in the batch), there is provision for header and trailer format strings. When ltering based on logger level and/or handler level is not enough, instances of Filter can be added to both Logger and Handler instances (through their addFilter() method). Before deciding to process a message further, both loggers and handlers consult all their lters for permission. If any lter returns a false value, the message is not processed further. The basic Filter functionality allows ltering by specic logger name. If this feature is used, messages sent to the named logger and its children are allowed through the lter, and all others dropped.
7 Optimization
Formatting of message arguments is deferred until it cannot be avoided. However, computing the arguments passed to the logging method can also be expensive, and you may want to avoid doing it if the logger will just throw away your event. To decide what to do, you can call the isEnabledFor() method which takes a level argument and returns true if the event would be created by the Logger for that level of call. You can write code like this: if logger.isEnabledFor(logging.DEBUG): logger.debug(Message with %s, %s, expensive_func1(), expensive_func2()) so that if the loggers threshold is set above DEBUG, the calls to expensive_func1() and expensive_func2() are never made. There are other optimizations which can be made for specic applications which need more precise control over what logging information is collected. Heres a list of things you can do to avoid processing during logging which you dont need: What you dont want to collect Information about where calls were made from. Threading information. Process information. How to avoid collecting it Set logging._srcfile to None. Set logging.logThreads to 0. Set logging.logProcesses to 0.
Also note that the core logging module only includes the basic handlers. If you dont import logging.handlers and logging.config, they wont take up any memory. See Also: Module logging API reference for the logging module.
Module logging.config Conguration API for the logging module. Module logging.handlers Useful handlers included with the logging module. A logging cookbook
Index Symbols
__init__() (logging.logging.Formatter method), ix
xvii