source: vendor/python/2.5/Doc/lib/liblogging.tex

Last change on this file was 3225, checked in by bird, 18 years ago

Python 2.5

File size: 68.6 KB
Line 
1\section{\module{logging} ---
2 Logging facility for Python}
3
4\declaremodule{standard}{logging}
5
6% These apply to all modules, and may be given more than once:
7
8\moduleauthor{Vinay Sajip}{vinay_sajip@red-dove.com}
9\sectionauthor{Vinay Sajip}{vinay_sajip@red-dove.com}
10
11\modulesynopsis{Logging module for Python based on \pep{282}.}
12
13\indexii{Errors}{logging}
14
15\versionadded{2.3}
16This module defines functions and classes which implement a flexible
17error logging system for applications.
18
19Logging is performed by calling methods on instances of the
20\class{Logger} class (hereafter called \dfn{loggers}). Each instance has a
21name, and they are conceptually arranged in a name space hierarchy
22using dots (periods) as separators. For example, a logger named
23"scan" is the parent of loggers "scan.text", "scan.html" and "scan.pdf".
24Logger names can be anything you want, and indicate the area of an
25application in which a logged message originates.
26
27Logged messages also have levels of importance associated with them.
28The default levels provided are \constant{DEBUG}, \constant{INFO},
29\constant{WARNING}, \constant{ERROR} and \constant{CRITICAL}. As a
30convenience, you indicate the importance of a logged message by calling
31an appropriate method of \class{Logger}. The methods are
32\method{debug()}, \method{info()}, \method{warning()}, \method{error()} and
33\method{critical()}, which mirror the default levels. You are not
34constrained to use these levels: you can specify your own and use a
35more general \class{Logger} method, \method{log()}, which takes an
36explicit level argument.
37
38The numeric values of logging levels are given in the following table. These
39are primarily of interest if you want to define your own levels, and need
40them to have specific values relative to the predefined levels. If you
41define a level with the same numeric value, it overwrites the predefined
42value; the predefined name is lost.
43
44\begin{tableii}{l|l}{code}{Level}{Numeric value}
45 \lineii{CRITICAL}{50}
46 \lineii{ERROR}{40}
47 \lineii{WARNING}{30}
48 \lineii{INFO}{20}
49 \lineii{DEBUG}{10}
50 \lineii{NOTSET}{0}
51\end{tableii}
52
53Levels can also be associated with loggers, being set either by the
54developer or through loading a saved logging configuration. When a
55logging method is called on a logger, the logger compares its own
56level with the level associated with the method call. If the logger's
57level is higher than the method call's, no logging message is actually
58generated. This is the basic mechanism controlling the verbosity of
59logging output.
60
61Logging messages are encoded as instances of the \class{LogRecord} class.
62When a logger decides to actually log an event, a \class{LogRecord}
63instance is created from the logging message.
64
65Logging messages are subjected to a dispatch mechanism through the
66use of \dfn{handlers}, which are instances of subclasses of the
67\class{Handler} class. Handlers are responsible for ensuring that a logged
68message (in the form of a \class{LogRecord}) ends up in a particular
69location (or set of locations) which is useful for the target audience for
70that message (such as end users, support desk staff, system administrators,
71developers). Handlers are passed \class{LogRecord} instances intended for
72particular destinations. Each logger can have zero, one or more handlers
73associated with it (via the \method{addHandler()} method of \class{Logger}).
74In addition to any handlers directly associated with a logger,
75\emph{all handlers associated with all ancestors of the logger} are
76called to dispatch the message.
77
78Just as for loggers, handlers can have levels associated with them.
79A handler's level acts as a filter in the same way as a logger's level does.
80If a handler decides to actually dispatch an event, the \method{emit()} method
81is used to send the message to its destination. Most user-defined subclasses
82of \class{Handler} will need to override this \method{emit()}.
83
84In addition to the base \class{Handler} class, many useful subclasses
85are provided:
86
87\begin{enumerate}
88
89\item \class{StreamHandler} instances send error messages to
90streams (file-like objects).
91
92\item \class{FileHandler} instances send error messages to disk
93files.
94
95\item \class{BaseRotatingHandler} is the base class for handlers that
96rotate log files at a certain point. It is not meant to be instantiated
97directly. Instead, use \class{RotatingFileHandler} or
98\class{TimedRotatingFileHandler}.
99
100\item \class{RotatingFileHandler} instances send error messages to disk
101files, with support for maximum log file sizes and log file rotation.
102
103\item \class{TimedRotatingFileHandler} instances send error messages to
104disk files rotating the log file at certain timed intervals.
105
106\item \class{SocketHandler} instances send error messages to
107TCP/IP sockets.
108
109\item \class{DatagramHandler} instances send error messages to UDP
110sockets.
111
112\item \class{SMTPHandler} instances send error messages to a
113designated email address.
114
115\item \class{SysLogHandler} instances send error messages to a
116\UNIX{} syslog daemon, possibly on a remote machine.
117
118\item \class{NTEventLogHandler} instances send error messages to a
119Windows NT/2000/XP event log.
120
121\item \class{MemoryHandler} instances send error messages to a
122buffer in memory, which is flushed whenever specific criteria are
123met.
124
125\item \class{HTTPHandler} instances send error messages to an
126HTTP server using either \samp{GET} or \samp{POST} semantics.
127
128\end{enumerate}
129
130The \class{StreamHandler} and \class{FileHandler} classes are defined
131in the core logging package. The other handlers are defined in a sub-
132module, \module{logging.handlers}. (There is also another sub-module,
133\module{logging.config}, for configuration functionality.)
134
135Logged messages are formatted for presentation through instances of the
136\class{Formatter} class. They are initialized with a format string
137suitable for use with the \% operator and a dictionary.
138
139For formatting multiple messages in a batch, instances of
140\class{BufferingFormatter} can be used. In addition to the format string
141(which is applied to each message in the batch), there is provision for
142header and trailer format strings.
143
144When filtering based on logger level and/or handler level is not enough,
145instances of \class{Filter} can be added to both \class{Logger} and
146\class{Handler} instances (through their \method{addFilter()} method).
147Before deciding to process a message further, both loggers and handlers
148consult all their filters for permission. If any filter returns a false
149value, the message is not processed further.
150
151The basic \class{Filter} functionality allows filtering by specific logger
152name. If this feature is used, messages sent to the named logger and its
153children are allowed through the filter, and all others dropped.
154
155In addition to the classes described above, there are a number of module-
156level functions.
157
158\begin{funcdesc}{getLogger}{\optional{name}}
159Return a logger with the specified name or, if no name is specified, return
160a logger which is the root logger of the hierarchy. If specified, the name
161is typically a dot-separated hierarchical name like \var{"a"}, \var{"a.b"}
162or \var{"a.b.c.d"}. Choice of these names is entirely up to the developer
163who is using logging.
164
165All calls to this function with a given name return the same logger instance.
166This means that logger instances never need to be passed between different
167parts of an application.
168\end{funcdesc}
169
170\begin{funcdesc}{getLoggerClass}{}
171Return either the standard \class{Logger} class, or the last class passed to
172\function{setLoggerClass()}. This function may be called from within a new
173class definition, to ensure that installing a customised \class{Logger} class
174will not undo customisations already applied by other code. For example:
175
176\begin{verbatim}
177 class MyLogger(logging.getLoggerClass()):
178 # ... override behaviour here
179\end{verbatim}
180
181\end{funcdesc}
182
183\begin{funcdesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
184Logs a message with level \constant{DEBUG} on the root logger.
185The \var{msg} is the message format string, and the \var{args} are the
186arguments which are merged into \var{msg} using the string formatting
187operator. (Note that this means that you can use keywords in the
188format string, together with a single dictionary argument.)
189
190There are two keyword arguments in \var{kwargs} which are inspected:
191\var{exc_info} which, if it does not evaluate as false, causes exception
192information to be added to the logging message. If an exception tuple (in the
193format returned by \function{sys.exc_info()}) is provided, it is used;
194otherwise, \function{sys.exc_info()} is called to get the exception
195information.
196
197The other optional keyword argument is \var{extra} which can be used to pass
198a dictionary which is used to populate the __dict__ of the LogRecord created
199for the logging event with user-defined attributes. These custom attributes
200can then be used as you like. For example, they could be incorporated into
201logged messages. For example:
202
203\begin{verbatim}
204 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
205 logging.basicConfig(format=FORMAT)
206 dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
207 logging.warning("Protocol problem: %s", "connection reset", extra=d)
208\end{verbatim}
209
210would print something like
211\begin{verbatim}
2122006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
213\end{verbatim}
214
215The keys in the dictionary passed in \var{extra} should not clash with the keys
216used by the logging system. (See the \class{Formatter} documentation for more
217information on which keys are used by the logging system.)
218
219If you choose to use these attributes in logged messages, you need to exercise
220some care. In the above example, for instance, the \class{Formatter} has been
221set up with a format string which expects 'clientip' and 'user' in the
222attribute dictionary of the LogRecord. If these are missing, the message will
223not be logged because a string formatting exception will occur. So in this
224case, you always need to pass the \var{extra} dictionary with these keys.
225
226While this might be annoying, this feature is intended for use in specialized
227circumstances, such as multi-threaded servers where the same code executes
228in many contexts, and interesting conditions which arise are dependent on this
229context (such as remote client IP address and authenticated user name, in the
230above example). In such circumstances, it is likely that specialized
231\class{Formatter}s would be used with particular \class{Handler}s.
232
233\versionchanged[\var{extra} was added]{2.5}
234
235\end{funcdesc}
236
237\begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
238Logs a message with level \constant{INFO} on the root logger.
239The arguments are interpreted as for \function{debug()}.
240\end{funcdesc}
241
242\begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
243Logs a message with level \constant{WARNING} on the root logger.
244The arguments are interpreted as for \function{debug()}.
245\end{funcdesc}
246
247\begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
248Logs a message with level \constant{ERROR} on the root logger.
249The arguments are interpreted as for \function{debug()}.
250\end{funcdesc}
251
252\begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
253Logs a message with level \constant{CRITICAL} on the root logger.
254The arguments are interpreted as for \function{debug()}.
255\end{funcdesc}
256
257\begin{funcdesc}{exception}{msg\optional{, *args}}
258Logs a message with level \constant{ERROR} on the root logger.
259The arguments are interpreted as for \function{debug()}. Exception info
260is added to the logging message. This function should only be called
261from an exception handler.
262\end{funcdesc}
263
264\begin{funcdesc}{log}{level, msg\optional{, *args\optional{, **kwargs}}}
265Logs a message with level \var{level} on the root logger.
266The other arguments are interpreted as for \function{debug()}.
267\end{funcdesc}
268
269\begin{funcdesc}{disable}{lvl}
270Provides an overriding level \var{lvl} for all loggers which takes
271precedence over the logger's own level. When the need arises to
272temporarily throttle logging output down across the whole application,
273this function can be useful.
274\end{funcdesc}
275
276\begin{funcdesc}{addLevelName}{lvl, levelName}
277Associates level \var{lvl} with text \var{levelName} in an internal
278dictionary, which is used to map numeric levels to a textual
279representation, for example when a \class{Formatter} formats a message.
280This function can also be used to define your own levels. The only
281constraints are that all levels used must be registered using this
282function, levels should be positive integers and they should increase
283in increasing order of severity.
284\end{funcdesc}
285
286\begin{funcdesc}{getLevelName}{lvl}
287Returns the textual representation of logging level \var{lvl}. If the
288level is one of the predefined levels \constant{CRITICAL},
289\constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG}
290then you get the corresponding string. If you have associated levels
291with names using \function{addLevelName()} then the name you have associated
292with \var{lvl} is returned. If a numeric value corresponding to one of the
293defined levels is passed in, the corresponding string representation is
294returned. Otherwise, the string "Level \%s" \% lvl is returned.
295\end{funcdesc}
296
297\begin{funcdesc}{makeLogRecord}{attrdict}
298Creates and returns a new \class{LogRecord} instance whose attributes are
299defined by \var{attrdict}. This function is useful for taking a pickled
300\class{LogRecord} attribute dictionary, sent over a socket, and reconstituting
301it as a \class{LogRecord} instance at the receiving end.
302\end{funcdesc}
303
304\begin{funcdesc}{basicConfig}{\optional{**kwargs}}
305Does basic configuration for the logging system by creating a
306\class{StreamHandler} with a default \class{Formatter} and adding it to
307the root logger. The functions \function{debug()}, \function{info()},
308\function{warning()}, \function{error()} and \function{critical()} will call
309\function{basicConfig()} automatically if no handlers are defined for the
310root logger.
311
312\versionchanged[Formerly, \function{basicConfig} did not take any keyword
313arguments]{2.4}
314
315The following keyword arguments are supported.
316
317\begin{tableii}{l|l}{code}{Format}{Description}
318\lineii{filename}{Specifies that a FileHandler be created, using the
319specified filename, rather than a StreamHandler.}
320\lineii{filemode}{Specifies the mode to open the file, if filename is
321specified (if filemode is unspecified, it defaults to 'a').}
322\lineii{format}{Use the specified format string for the handler.}
323\lineii{datefmt}{Use the specified date/time format.}
324\lineii{level}{Set the root logger level to the specified level.}
325\lineii{stream}{Use the specified stream to initialize the StreamHandler.
326Note that this argument is incompatible with 'filename' - if both
327are present, 'stream' is ignored.}
328\end{tableii}
329
330\end{funcdesc}
331
332\begin{funcdesc}{shutdown}{}
333Informs the logging system to perform an orderly shutdown by flushing and
334closing all handlers.
335\end{funcdesc}
336
337\begin{funcdesc}{setLoggerClass}{klass}
338Tells the logging system to use the class \var{klass} when instantiating a
339logger. The class should define \method{__init__()} such that only a name
340argument is required, and the \method{__init__()} should call
341\method{Logger.__init__()}. This function is typically called before any
342loggers are instantiated by applications which need to use custom logger
343behavior.
344\end{funcdesc}
345
346
347\begin{seealso}
348 \seepep{282}{A Logging System}
349 {The proposal which described this feature for inclusion in
350 the Python standard library.}
351 \seelink{http://www.red-dove.com/python_logging.html}
352 {Original Python \module{logging} package}
353 {This is the original source for the \module{logging}
354 package. The version of the package available from this
355 site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x,
356 which do not include the \module{logging} package in the standard
357 library.}
358\end{seealso}
359
360
361\subsection{Logger Objects}
362
363Loggers have the following attributes and methods. Note that Loggers are
364never instantiated directly, but always through the module-level function
365\function{logging.getLogger(name)}.
366
367\begin{datadesc}{propagate}
368If this evaluates to false, logging messages are not passed by this
369logger or by child loggers to higher level (ancestor) loggers. The
370constructor sets this attribute to 1.
371\end{datadesc}
372
373\begin{methoddesc}{setLevel}{lvl}
374Sets the threshold for this logger to \var{lvl}. Logging messages
375which are less severe than \var{lvl} will be ignored. When a logger is
376created, the level is set to \constant{NOTSET} (which causes all messages
377to be processed when the logger is the root logger, or delegation to the
378parent when the logger is a non-root logger). Note that the root logger
379is created with level \constant{WARNING}.
380
381The term "delegation to the parent" means that if a logger has a level
382of NOTSET, its chain of ancestor loggers is traversed until either an
383ancestor with a level other than NOTSET is found, or the root is
384reached.
385
386If an ancestor is found with a level other than NOTSET, then that
387ancestor's level is treated as the effective level of the logger where
388the ancestor search began, and is used to determine how a logging
389event is handled.
390
391If the root is reached, and it has a level of NOTSET, then all
392messages will be processed. Otherwise, the root's level will be used
393as the effective level.
394\end{methoddesc}
395
396\begin{methoddesc}{isEnabledFor}{lvl}
397Indicates if a message of severity \var{lvl} would be processed by
398this logger. This method checks first the module-level level set by
399\function{logging.disable(lvl)} and then the logger's effective level as
400determined by \method{getEffectiveLevel()}.
401\end{methoddesc}
402
403\begin{methoddesc}{getEffectiveLevel}{}
404Indicates the effective level for this logger. If a value other than
405\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
406Otherwise, the hierarchy is traversed towards the root until a value
407other than \constant{NOTSET} is found, and that value is returned.
408\end{methoddesc}
409
410\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
411Logs a message with level \constant{DEBUG} on this logger.
412The \var{msg} is the message format string, and the \var{args} are the
413arguments which are merged into \var{msg} using the string formatting
414operator. (Note that this means that you can use keywords in the
415format string, together with a single dictionary argument.)
416
417There are two keyword arguments in \var{kwargs} which are inspected:
418\var{exc_info} which, if it does not evaluate as false, causes exception
419information to be added to the logging message. If an exception tuple (in the
420format returned by \function{sys.exc_info()}) is provided, it is used;
421otherwise, \function{sys.exc_info()} is called to get the exception
422information.
423
424The other optional keyword argument is \var{extra} which can be used to pass
425a dictionary which is used to populate the __dict__ of the LogRecord created
426for the logging event with user-defined attributes. These custom attributes
427can then be used as you like. For example, they could be incorporated into
428logged messages. For example:
429
430\begin{verbatim}
431 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
432 logging.basicConfig(format=FORMAT)
433 dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
434 logger = logging.getLogger("tcpserver")
435 logger.warning("Protocol problem: %s", "connection reset", extra=d)
436\end{verbatim}
437
438would print something like
439\begin{verbatim}
4402006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
441\end{verbatim}
442
443The keys in the dictionary passed in \var{extra} should not clash with the keys
444used by the logging system. (See the \class{Formatter} documentation for more
445information on which keys are used by the logging system.)
446
447If you choose to use these attributes in logged messages, you need to exercise
448some care. In the above example, for instance, the \class{Formatter} has been
449set up with a format string which expects 'clientip' and 'user' in the
450attribute dictionary of the LogRecord. If these are missing, the message will
451not be logged because a string formatting exception will occur. So in this
452case, you always need to pass the \var{extra} dictionary with these keys.
453
454While this might be annoying, this feature is intended for use in specialized
455circumstances, such as multi-threaded servers where the same code executes
456in many contexts, and interesting conditions which arise are dependent on this
457context (such as remote client IP address and authenticated user name, in the
458above example). In such circumstances, it is likely that specialized
459\class{Formatter}s would be used with particular \class{Handler}s.
460
461\versionchanged[\var{extra} was added]{2.5}
462
463\end{methoddesc}
464
465\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
466Logs a message with level \constant{INFO} on this logger.
467The arguments are interpreted as for \method{debug()}.
468\end{methoddesc}
469
470\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
471Logs a message with level \constant{WARNING} on this logger.
472The arguments are interpreted as for \method{debug()}.
473\end{methoddesc}
474
475\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
476Logs a message with level \constant{ERROR} on this logger.
477The arguments are interpreted as for \method{debug()}.
478\end{methoddesc}
479
480\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
481Logs a message with level \constant{CRITICAL} on this logger.
482The arguments are interpreted as for \method{debug()}.
483\end{methoddesc}
484
485\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
486Logs a message with integer level \var{lvl} on this logger.
487The other arguments are interpreted as for \method{debug()}.
488\end{methoddesc}
489
490\begin{methoddesc}{exception}{msg\optional{, *args}}
491Logs a message with level \constant{ERROR} on this logger.
492The arguments are interpreted as for \method{debug()}. Exception info
493is added to the logging message. This method should only be called
494from an exception handler.
495\end{methoddesc}
496
497\begin{methoddesc}{addFilter}{filt}
498Adds the specified filter \var{filt} to this logger.
499\end{methoddesc}
500
501\begin{methoddesc}{removeFilter}{filt}
502Removes the specified filter \var{filt} from this logger.
503\end{methoddesc}
504
505\begin{methoddesc}{filter}{record}
506Applies this logger's filters to the record and returns a true value if
507the record is to be processed.
508\end{methoddesc}
509
510\begin{methoddesc}{addHandler}{hdlr}
511Adds the specified handler \var{hdlr} to this logger.
512\end{methoddesc}
513
514\begin{methoddesc}{removeHandler}{hdlr}
515Removes the specified handler \var{hdlr} from this logger.
516\end{methoddesc}
517
518\begin{methoddesc}{findCaller}{}
519Finds the caller's source filename and line number. Returns the filename
520and line number as a 2-element tuple.
521\end{methoddesc}
522
523\begin{methoddesc}{handle}{record}
524Handles a record by passing it to all handlers associated with this logger
525and its ancestors (until a false value of \var{propagate} is found).
526This method is used for unpickled records received from a socket, as well
527as those created locally. Logger-level filtering is applied using
528\method{filter()}.
529\end{methoddesc}
530
531\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info,
532 func, extra}
533This is a factory method which can be overridden in subclasses to create
534specialized \class{LogRecord} instances.
535\versionchanged[\var{func} and \var{extra} were added]{2.5}
536\end{methoddesc}
537
538\subsection{Basic example \label{minimal-example}}
539
540\versionchanged[formerly \function{basicConfig} did not take any keyword
541arguments]{2.4}
542
543The \module{logging} package provides a lot of flexibility, and its
544configuration can appear daunting. This section demonstrates that simple
545use of the logging package is possible.
546
547The simplest example shows logging to the console:
548
549\begin{verbatim}
550import logging
551
552logging.debug('A debug message')
553logging.info('Some information')
554logging.warning('A shot across the bows')
555\end{verbatim}
556
557If you run the above script, you'll see this:
558\begin{verbatim}
559WARNING:root:A shot across the bows
560\end{verbatim}
561
562Because no particular logger was specified, the system used the root logger.
563The debug and info messages didn't appear because by default, the root
564logger is configured to only handle messages with a severity of WARNING
565or above. The message format is also a configuration default, as is the output
566destination of the messages - \code{sys.stderr}. The severity level,
567the message format and destination can be easily changed, as shown in
568the example below:
569
570\begin{verbatim}
571import logging
572
573logging.basicConfig(level=logging.DEBUG,
574 format='%(asctime)s %(levelname)s %(message)s',
575 filename='/tmp/myapp.log',
576 filemode='w')
577logging.debug('A debug message')
578logging.info('Some information')
579logging.warning('A shot across the bows')
580\end{verbatim}
581
582The \method{basicConfig()} method is used to change the configuration
583defaults, which results in output (written to \code{/tmp/myapp.log})
584which should look something like the following:
585
586\begin{verbatim}
5872004-07-02 13:00:08,743 DEBUG A debug message
5882004-07-02 13:00:08,743 INFO Some information
5892004-07-02 13:00:08,743 WARNING A shot across the bows
590\end{verbatim}
591
592This time, all messages with a severity of DEBUG or above were handled,
593and the format of the messages was also changed, and output went to the
594specified file rather than the console.
595
596Formatting uses standard Python string formatting - see section
597\ref{typesseq-strings}. The format string takes the following
598common specifiers. For a complete list of specifiers, consult the
599\class{Formatter} documentation.
600
601\begin{tableii}{l|l}{code}{Format}{Description}
602\lineii{\%(name)s} {Name of the logger (logging channel).}
603\lineii{\%(levelname)s}{Text logging level for the message
604 (\code{'DEBUG'}, \code{'INFO'},
605 \code{'WARNING'}, \code{'ERROR'},
606 \code{'CRITICAL'}).}
607\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
608 was created. By default this is of the form
609 ``2003-07-08 16:49:45,896'' (the numbers after the
610 comma are millisecond portion of the time).}
611\lineii{\%(message)s} {The logged message.}
612\end{tableii}
613
614To change the date/time format, you can pass an additional keyword parameter,
615\var{datefmt}, as in the following:
616
617\begin{verbatim}
618import logging
619
620logging.basicConfig(level=logging.DEBUG,
621 format='%(asctime)s %(levelname)-8s %(message)s',
622 datefmt='%a, %d %b %Y %H:%M:%S',
623 filename='/temp/myapp.log',
624 filemode='w')
625logging.debug('A debug message')
626logging.info('Some information')
627logging.warning('A shot across the bows')
628\end{verbatim}
629
630which would result in output like
631
632\begin{verbatim}
633Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
634Fri, 02 Jul 2004 13:06:18 INFO Some information
635Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
636\end{verbatim}
637
638The date format string follows the requirements of \function{strftime()} -
639see the documentation for the \refmodule{time} module.
640
641If, instead of sending logging output to the console or a file, you'd rather
642use a file-like object which you have created separately, you can pass it
643to \function{basicConfig()} using the \var{stream} keyword argument. Note
644that if both \var{stream} and \var{filename} keyword arguments are passed,
645the \var{stream} argument is ignored.
646
647Of course, you can put variable information in your output. To do this,
648simply have the message be a format string and pass in additional arguments
649containing the variable information, as in the following example:
650
651\begin{verbatim}
652import logging
653
654logging.basicConfig(level=logging.DEBUG,
655 format='%(asctime)s %(levelname)-8s %(message)s',
656 datefmt='%a, %d %b %Y %H:%M:%S',
657 filename='/temp/myapp.log',
658 filemode='w')
659logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
660\end{verbatim}
661
662which would result in
663
664\begin{verbatim}
665Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
666\end{verbatim}
667
668\subsection{Logging to multiple destinations \label{multiple-destinations}}
669
670Let's say you want to log to console and file with different message formats
671and in differing circumstances. Say you want to log messages with levels
672of DEBUG and higher to file, and those messages at level INFO and higher to
673the console. Let's also assume that the file should contain timestamps, but
674the console messages should not. Here's how you can achieve this:
675
676\begin{verbatim}
677import logging
678
679# set up logging to file - see previous section for more details
680logging.basicConfig(level=logging.DEBUG,
681 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
682 datefmt='%m-%d %H:%M',
683 filename='/temp/myapp.log',
684 filemode='w')
685# define a Handler which writes INFO messages or higher to the sys.stderr
686console = logging.StreamHandler()
687console.setLevel(logging.INFO)
688# set a format which is simpler for console use
689formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
690# tell the handler to use this format
691console.setFormatter(formatter)
692# add the handler to the root logger
693logging.getLogger('').addHandler(console)
694
695# Now, we can log to the root logger, or any other logger. First the root...
696logging.info('Jackdaws love my big sphinx of quartz.')
697
698# Now, define a couple of other loggers which might represent areas in your
699# application:
700
701logger1 = logging.getLogger('myapp.area1')
702logger2 = logging.getLogger('myapp.area2')
703
704logger1.debug('Quick zephyrs blow, vexing daft Jim.')
705logger1.info('How quickly daft jumping zebras vex.')
706logger2.warning('Jail zesty vixen who grabbed pay from quack.')
707logger2.error('The five boxing wizards jump quickly.')
708\end{verbatim}
709
710When you run this, on the console you will see
711
712\begin{verbatim}
713root : INFO Jackdaws love my big sphinx of quartz.
714myapp.area1 : INFO How quickly daft jumping zebras vex.
715myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
716myapp.area2 : ERROR The five boxing wizards jump quickly.
717\end{verbatim}
718
719and in the file you will see something like
720
721\begin{verbatim}
72210-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
72310-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
72410-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
72510-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
72610-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
727\end{verbatim}
728
729As you can see, the DEBUG message only shows up in the file. The other
730messages are sent to both destinations.
731
732This example uses console and file handlers, but you can use any number and
733combination of handlers you choose.
734
735\subsection{Sending and receiving logging events across a network
736\label{network-logging}}
737
738Let's say you want to send logging events across a network, and handle them
739at the receiving end. A simple way of doing this is attaching a
740\class{SocketHandler} instance to the root logger at the sending end:
741
742\begin{verbatim}
743import logging, logging.handlers
744
745rootLogger = logging.getLogger('')
746rootLogger.setLevel(logging.DEBUG)
747socketHandler = logging.handlers.SocketHandler('localhost',
748 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
749# don't bother with a formatter, since a socket handler sends the event as
750# an unformatted pickle
751rootLogger.addHandler(socketHandler)
752
753# Now, we can log to the root logger, or any other logger. First the root...
754logging.info('Jackdaws love my big sphinx of quartz.')
755
756# Now, define a couple of other loggers which might represent areas in your
757# application:
758
759logger1 = logging.getLogger('myapp.area1')
760logger2 = logging.getLogger('myapp.area2')
761
762logger1.debug('Quick zephyrs blow, vexing daft Jim.')
763logger1.info('How quickly daft jumping zebras vex.')
764logger2.warning('Jail zesty vixen who grabbed pay from quack.')
765logger2.error('The five boxing wizards jump quickly.')
766\end{verbatim}
767
768At the receiving end, you can set up a receiver using the
769\module{SocketServer} module. Here is a basic working example:
770
771\begin{verbatim}
772import cPickle
773import logging
774import logging.handlers
775import SocketServer
776import struct
777
778
779class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
780 """Handler for a streaming logging request.
781
782 This basically logs the record using whatever logging policy is
783 configured locally.
784 """
785
786 def handle(self):
787 """
788 Handle multiple requests - each expected to be a 4-byte length,
789 followed by the LogRecord in pickle format. Logs the record
790 according to whatever policy is configured locally.
791 """
792 while 1:
793 chunk = self.connection.recv(4)
794 if len(chunk) < 4:
795 break
796 slen = struct.unpack(">L", chunk)[0]
797 chunk = self.connection.recv(slen)
798 while len(chunk) < slen:
799 chunk = chunk + self.connection.recv(slen - len(chunk))
800 obj = self.unPickle(chunk)
801 record = logging.makeLogRecord(obj)
802 self.handleLogRecord(record)
803
804 def unPickle(self, data):
805 return cPickle.loads(data)
806
807 def handleLogRecord(self, record):
808 # if a name is specified, we use the named logger rather than the one
809 # implied by the record.
810 if self.server.logname is not None:
811 name = self.server.logname
812 else:
813 name = record.name
814 logger = logging.getLogger(name)
815 # N.B. EVERY record gets logged. This is because Logger.handle
816 # is normally called AFTER logger-level filtering. If you want
817 # to do filtering, do it at the client end to save wasting
818 # cycles and network bandwidth!
819 logger.handle(record)
820
821class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
822 """simple TCP socket-based logging receiver suitable for testing.
823 """
824
825 allow_reuse_address = 1
826
827 def __init__(self, host='localhost',
828 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
829 handler=LogRecordStreamHandler):
830 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
831 self.abort = 0
832 self.timeout = 1
833 self.logname = None
834
835 def serve_until_stopped(self):
836 import select
837 abort = 0
838 while not abort:
839 rd, wr, ex = select.select([self.socket.fileno()],
840 [], [],
841 self.timeout)
842 if rd:
843 self.handle_request()
844 abort = self.abort
845
846def main():
847 logging.basicConfig(
848 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
849 tcpserver = LogRecordSocketReceiver()
850 print "About to start TCP server..."
851 tcpserver.serve_until_stopped()
852
853if __name__ == "__main__":
854 main()
855\end{verbatim}
856
857First run the server, and then the client. On the client side, nothing is
858printed on the console; on the server side, you should see something like:
859
860\begin{verbatim}
861About to start TCP server...
862 59 root INFO Jackdaws love my big sphinx of quartz.
863 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
864 69 myapp.area1 INFO How quickly daft jumping zebras vex.
865 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
866 69 myapp.area2 ERROR The five boxing wizards jump quickly.
867\end{verbatim}
868
869\subsection{Handler Objects}
870
871Handlers have the following attributes and methods. Note that
872\class{Handler} is never instantiated directly; this class acts as a
873base for more useful subclasses. However, the \method{__init__()}
874method in subclasses needs to call \method{Handler.__init__()}.
875
876\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
877Initializes the \class{Handler} instance by setting its level, setting
878the list of filters to the empty list and creating a lock (using
879\method{createLock()}) for serializing access to an I/O mechanism.
880\end{methoddesc}
881
882\begin{methoddesc}{createLock}{}
883Initializes a thread lock which can be used to serialize access to
884underlying I/O functionality which may not be threadsafe.
885\end{methoddesc}
886
887\begin{methoddesc}{acquire}{}
888Acquires the thread lock created with \method{createLock()}.
889\end{methoddesc}
890
891\begin{methoddesc}{release}{}
892Releases the thread lock acquired with \method{acquire()}.
893\end{methoddesc}
894
895\begin{methoddesc}{setLevel}{lvl}
896Sets the threshold for this handler to \var{lvl}. Logging messages which are
897less severe than \var{lvl} will be ignored. When a handler is created, the
898level is set to \constant{NOTSET} (which causes all messages to be processed).
899\end{methoddesc}
900
901\begin{methoddesc}{setFormatter}{form}
902Sets the \class{Formatter} for this handler to \var{form}.
903\end{methoddesc}
904
905\begin{methoddesc}{addFilter}{filt}
906Adds the specified filter \var{filt} to this handler.
907\end{methoddesc}
908
909\begin{methoddesc}{removeFilter}{filt}
910Removes the specified filter \var{filt} from this handler.
911\end{methoddesc}
912
913\begin{methoddesc}{filter}{record}
914Applies this handler's filters to the record and returns a true value if
915the record is to be processed.
916\end{methoddesc}
917
918\begin{methoddesc}{flush}{}
919Ensure all logging output has been flushed. This version does
920nothing and is intended to be implemented by subclasses.
921\end{methoddesc}
922
923\begin{methoddesc}{close}{}
924Tidy up any resources used by the handler. This version does
925nothing and is intended to be implemented by subclasses.
926\end{methoddesc}
927
928\begin{methoddesc}{handle}{record}
929Conditionally emits the specified logging record, depending on
930filters which may have been added to the handler. Wraps the actual
931emission of the record with acquisition/release of the I/O thread
932lock.
933\end{methoddesc}
934
935\begin{methoddesc}{handleError}{record}
936This method should be called from handlers when an exception is
937encountered during an \method{emit()} call. By default it does nothing,
938which means that exceptions get silently ignored. This is what is
939mostly wanted for a logging system - most users will not care
940about errors in the logging system, they are more interested in
941application errors. You could, however, replace this with a custom
942handler if you wish. The specified record is the one which was being
943processed when the exception occurred.
944\end{methoddesc}
945
946\begin{methoddesc}{format}{record}
947Do formatting for a record - if a formatter is set, use it.
948Otherwise, use the default formatter for the module.
949\end{methoddesc}
950
951\begin{methoddesc}{emit}{record}
952Do whatever it takes to actually log the specified logging record.
953This version is intended to be implemented by subclasses and so
954raises a \exception{NotImplementedError}.
955\end{methoddesc}
956
957\subsubsection{StreamHandler}
958
959The \class{StreamHandler} class, located in the core \module{logging}
960package, sends logging output to streams such as \var{sys.stdout},
961\var{sys.stderr} or any file-like object (or, more precisely, any
962object which supports \method{write()} and \method{flush()} methods).
963
964\begin{classdesc}{StreamHandler}{\optional{strm}}
965Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
966specified, the instance will use it for logging output; otherwise,
967\var{sys.stderr} will be used.
968\end{classdesc}
969
970\begin{methoddesc}{emit}{record}
971If a formatter is specified, it is used to format the record.
972The record is then written to the stream with a trailing newline.
973If exception information is present, it is formatted using
974\function{traceback.print_exception()} and appended to the stream.
975\end{methoddesc}
976
977\begin{methoddesc}{flush}{}
978Flushes the stream by calling its \method{flush()} method. Note that
979the \method{close()} method is inherited from \class{Handler} and
980so does nothing, so an explicit \method{flush()} call may be needed
981at times.
982\end{methoddesc}
983
984\subsubsection{FileHandler}
985
986The \class{FileHandler} class, located in the core \module{logging}
987package, sends logging output to a disk file. It inherits the output
988functionality from \class{StreamHandler}.
989
990\begin{classdesc}{FileHandler}{filename\optional{, mode}}
991Returns a new instance of the \class{FileHandler} class. The specified
992file is opened and used as the stream for logging. If \var{mode} is
993not specified, \constant{'a'} is used. By default, the file grows
994indefinitely.
995\end{classdesc}
996
997\begin{methoddesc}{close}{}
998Closes the file.
999\end{methoddesc}
1000
1001\begin{methoddesc}{emit}{record}
1002Outputs the record to the file.
1003\end{methoddesc}
1004
1005\subsubsection{RotatingFileHandler}
1006
1007The \class{RotatingFileHandler} class, located in the \module{logging.handlers}
1008module, supports rotation of disk log files.
1009
1010\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{,
1011 maxBytes\optional{, backupCount}}}}
1012Returns a new instance of the \class{RotatingFileHandler} class. The
1013specified file is opened and used as the stream for logging. If
1014\var{mode} is not specified, \code{'a'} is used. By default, the
1015file grows indefinitely.
1016
1017You can use the \var{maxBytes} and
1018\var{backupCount} values to allow the file to \dfn{rollover} at a
1019predetermined size. When the size is about to be exceeded, the file is
1020closed and a new file is silently opened for output. Rollover occurs
1021whenever the current log file is nearly \var{maxBytes} in length; if
1022\var{maxBytes} is zero, rollover never occurs. If \var{backupCount}
1023is non-zero, the system will save old log files by appending the
1024extensions ".1", ".2" etc., to the filename. For example, with
1025a \var{backupCount} of 5 and a base file name of
1026\file{app.log}, you would get \file{app.log},
1027\file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being
1028written to is always \file{app.log}. When this file is filled, it is
1029closed and renamed to \file{app.log.1}, and if files \file{app.log.1},
1030\file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2},
1031\file{app.log.3} etc. respectively.
1032\end{classdesc}
1033
1034\begin{methoddesc}{doRollover}{}
1035Does a rollover, as described above.
1036\end{methoddesc}
1037
1038\begin{methoddesc}{emit}{record}
1039Outputs the record to the file, catering for rollover as described previously.
1040\end{methoddesc}
1041
1042\subsubsection{TimedRotatingFileHandler}
1043
1044The \class{TimedRotatingFileHandler} class, located in the
1045\module{logging.handlers} module, supports rotation of disk log files
1046at certain timed intervals.
1047
1048\begin{classdesc}{TimedRotatingFileHandler}{filename
1049 \optional{,when
1050 \optional{,interval
1051 \optional{,backupCount}}}}
1052
1053Returns a new instance of the \class{TimedRotatingFileHandler} class. The
1054specified file is opened and used as the stream for logging. On rotating
1055it also sets the filename suffix. Rotating happens based on the product
1056of \var{when} and \var{interval}.
1057
1058You can use the \var{when} to specify the type of \var{interval}. The
1059list of possible values is, note that they are not case sensitive:
1060
1061\begin{tableii}{l|l}{}{Value}{Type of interval}
1062 \lineii{S}{Seconds}
1063 \lineii{M}{Minutes}
1064 \lineii{H}{Hours}
1065 \lineii{D}{Days}
1066 \lineii{W}{Week day (0=Monday)}
1067 \lineii{midnight}{Roll over at midnight}
1068\end{tableii}
1069
1070If \var{backupCount} is non-zero, the system will save old log files by
1071appending extensions to the filename. The extensions are date-and-time
1072based, using the strftime format \code{\%Y-\%m-\%d_\%H-\%M-\%S} or a leading
1073portion thereof, depending on the rollover interval. At most \var{backupCount}
1074files will be kept, and if more would be created when rollover occurs, the
1075oldest one is deleted.
1076\end{classdesc}
1077
1078\begin{methoddesc}{doRollover}{}
1079Does a rollover, as described above.
1080\end{methoddesc}
1081
1082\begin{methoddesc}{emit}{record}
1083Outputs the record to the file, catering for rollover as described
1084above.
1085\end{methoddesc}
1086
1087\subsubsection{SocketHandler}
1088
1089The \class{SocketHandler} class, located in the
1090\module{logging.handlers} module, sends logging output to a network
1091socket. The base class uses a TCP socket.
1092
1093\begin{classdesc}{SocketHandler}{host, port}
1094Returns a new instance of the \class{SocketHandler} class intended to
1095communicate with a remote machine whose address is given by \var{host}
1096and \var{port}.
1097\end{classdesc}
1098
1099\begin{methoddesc}{close}{}
1100Closes the socket.
1101\end{methoddesc}
1102
1103\begin{methoddesc}{handleError}{}
1104\end{methoddesc}
1105
1106\begin{methoddesc}{emit}{}
1107Pickles the record's attribute dictionary and writes it to the socket in
1108binary format. If there is an error with the socket, silently drops the
1109packet. If the connection was previously lost, re-establishes the connection.
1110To unpickle the record at the receiving end into a \class{LogRecord}, use the
1111\function{makeLogRecord()} function.
1112\end{methoddesc}
1113
1114\begin{methoddesc}{handleError}{}
1115Handles an error which has occurred during \method{emit()}. The
1116most likely cause is a lost connection. Closes the socket so that
1117we can retry on the next event.
1118\end{methoddesc}
1119
1120\begin{methoddesc}{makeSocket}{}
1121This is a factory method which allows subclasses to define the precise
1122type of socket they want. The default implementation creates a TCP
1123socket (\constant{socket.SOCK_STREAM}).
1124\end{methoddesc}
1125
1126\begin{methoddesc}{makePickle}{record}
1127Pickles the record's attribute dictionary in binary format with a length
1128prefix, and returns it ready for transmission across the socket.
1129\end{methoddesc}
1130
1131\begin{methoddesc}{send}{packet}
1132Send a pickled string \var{packet} to the socket. This function allows
1133for partial sends which can happen when the network is busy.
1134\end{methoddesc}
1135
1136\subsubsection{DatagramHandler}
1137
1138The \class{DatagramHandler} class, located in the
1139\module{logging.handlers} module, inherits from \class{SocketHandler}
1140to support sending logging messages over UDP sockets.
1141
1142\begin{classdesc}{DatagramHandler}{host, port}
1143Returns a new instance of the \class{DatagramHandler} class intended to
1144communicate with a remote machine whose address is given by \var{host}
1145and \var{port}.
1146\end{classdesc}
1147
1148\begin{methoddesc}{emit}{}
1149Pickles the record's attribute dictionary and writes it to the socket in
1150binary format. If there is an error with the socket, silently drops the
1151packet.
1152To unpickle the record at the receiving end into a \class{LogRecord}, use the
1153\function{makeLogRecord()} function.
1154\end{methoddesc}
1155
1156\begin{methoddesc}{makeSocket}{}
1157The factory method of \class{SocketHandler} is here overridden to create
1158a UDP socket (\constant{socket.SOCK_DGRAM}).
1159\end{methoddesc}
1160
1161\begin{methoddesc}{send}{s}
1162Send a pickled string to a socket.
1163\end{methoddesc}
1164
1165\subsubsection{SysLogHandler}
1166
1167The \class{SysLogHandler} class, located in the
1168\module{logging.handlers} module, supports sending logging messages to
1169a remote or local \UNIX{} syslog.
1170
1171\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
1172Returns a new instance of the \class{SysLogHandler} class intended to
1173communicate with a remote \UNIX{} machine whose address is given by
1174\var{address} in the form of a \code{(\var{host}, \var{port})}
1175tuple. If \var{address} is not specified, \code{('localhost', 514)} is
1176used. The address is used to open a UDP socket. If \var{facility} is
1177not specified, \constant{LOG_USER} is used.
1178\end{classdesc}
1179
1180\begin{methoddesc}{close}{}
1181Closes the socket to the remote host.
1182\end{methoddesc}
1183
1184\begin{methoddesc}{emit}{record}
1185The record is formatted, and then sent to the syslog server. If
1186exception information is present, it is \emph{not} sent to the server.
1187\end{methoddesc}
1188
1189\begin{methoddesc}{encodePriority}{facility, priority}
1190Encodes the facility and priority into an integer. You can pass in strings
1191or integers - if strings are passed, internal mapping dictionaries are used
1192to convert them to integers.
1193\end{methoddesc}
1194
1195\subsubsection{NTEventLogHandler}
1196
1197The \class{NTEventLogHandler} class, located in the
1198\module{logging.handlers} module, supports sending logging messages to
1199a local Windows NT, Windows 2000 or Windows XP event log. Before you
1200can use it, you need Mark Hammond's Win32 extensions for Python
1201installed.
1202
1203\begin{classdesc}{NTEventLogHandler}{appname\optional{,
1204 dllname\optional{, logtype}}}
1205Returns a new instance of the \class{NTEventLogHandler} class. The
1206\var{appname} is used to define the application name as it appears in the
1207event log. An appropriate registry entry is created using this name.
1208The \var{dllname} should give the fully qualified pathname of a .dll or .exe
1209which contains message definitions to hold in the log (if not specified,
1210\code{'win32service.pyd'} is used - this is installed with the Win32
1211extensions and contains some basic placeholder message definitions.
1212Note that use of these placeholders will make your event logs big, as the
1213entire message source is held in the log. If you want slimmer logs, you have
1214to pass in the name of your own .dll or .exe which contains the message
1215definitions you want to use in the event log). The \var{logtype} is one of
1216\code{'Application'}, \code{'System'} or \code{'Security'}, and
1217defaults to \code{'Application'}.
1218\end{classdesc}
1219
1220\begin{methoddesc}{close}{}
1221At this point, you can remove the application name from the registry as a
1222source of event log entries. However, if you do this, you will not be able
1223to see the events as you intended in the Event Log Viewer - it needs to be
1224able to access the registry to get the .dll name. The current version does
1225not do this (in fact it doesn't do anything).
1226\end{methoddesc}
1227
1228\begin{methoddesc}{emit}{record}
1229Determines the message ID, event category and event type, and then logs the
1230message in the NT event log.
1231\end{methoddesc}
1232
1233\begin{methoddesc}{getEventCategory}{record}
1234Returns the event category for the record. Override this if you
1235want to specify your own categories. This version returns 0.
1236\end{methoddesc}
1237
1238\begin{methoddesc}{getEventType}{record}
1239Returns the event type for the record. Override this if you want
1240to specify your own types. This version does a mapping using the
1241handler's typemap attribute, which is set up in \method{__init__()}
1242to a dictionary which contains mappings for \constant{DEBUG},
1243\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
1244\constant{CRITICAL}. If you are using your own levels, you will either need
1245to override this method or place a suitable dictionary in the
1246handler's \var{typemap} attribute.
1247\end{methoddesc}
1248
1249\begin{methoddesc}{getMessageID}{record}
1250Returns the message ID for the record. If you are using your
1251own messages, you could do this by having the \var{msg} passed to the
1252logger being an ID rather than a format string. Then, in here,
1253you could use a dictionary lookup to get the message ID. This
1254version returns 1, which is the base message ID in
1255\file{win32service.pyd}.
1256\end{methoddesc}
1257
1258\subsubsection{SMTPHandler}
1259
1260The \class{SMTPHandler} class, located in the
1261\module{logging.handlers} module, supports sending logging messages to
1262an email address via SMTP.
1263
1264\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
1265Returns a new instance of the \class{SMTPHandler} class. The
1266instance is initialized with the from and to addresses and subject
1267line of the email. The \var{toaddrs} should be a list of strings. To specify a
1268non-standard SMTP port, use the (host, port) tuple format for the
1269\var{mailhost} argument. If you use a string, the standard SMTP port
1270is used.
1271\end{classdesc}
1272
1273\begin{methoddesc}{emit}{record}
1274Formats the record and sends it to the specified addressees.
1275\end{methoddesc}
1276
1277\begin{methoddesc}{getSubject}{record}
1278If you want to specify a subject line which is record-dependent,
1279override this method.
1280\end{methoddesc}
1281
1282\subsubsection{MemoryHandler}
1283
1284The \class{MemoryHandler} class, located in the
1285\module{logging.handlers} module, supports buffering of logging
1286records in memory, periodically flushing them to a \dfn{target}
1287handler. Flushing occurs whenever the buffer is full, or when an event
1288of a certain severity or greater is seen.
1289
1290\class{MemoryHandler} is a subclass of the more general
1291\class{BufferingHandler}, which is an abstract class. This buffers logging
1292records in memory. Whenever each record is added to the buffer, a
1293check is made by calling \method{shouldFlush()} to see if the buffer
1294should be flushed. If it should, then \method{flush()} is expected to
1295do the needful.
1296
1297\begin{classdesc}{BufferingHandler}{capacity}
1298Initializes the handler with a buffer of the specified capacity.
1299\end{classdesc}
1300
1301\begin{methoddesc}{emit}{record}
1302Appends the record to the buffer. If \method{shouldFlush()} returns true,
1303calls \method{flush()} to process the buffer.
1304\end{methoddesc}
1305
1306\begin{methoddesc}{flush}{}
1307You can override this to implement custom flushing behavior. This version
1308just zaps the buffer to empty.
1309\end{methoddesc}
1310
1311\begin{methoddesc}{shouldFlush}{record}
1312Returns true if the buffer is up to capacity. This method can be
1313overridden to implement custom flushing strategies.
1314\end{methoddesc}
1315
1316\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
1317\optional{, target}}}
1318Returns a new instance of the \class{MemoryHandler} class. The
1319instance is initialized with a buffer size of \var{capacity}. If
1320\var{flushLevel} is not specified, \constant{ERROR} is used. If no
1321\var{target} is specified, the target will need to be set using
1322\method{setTarget()} before this handler does anything useful.
1323\end{classdesc}
1324
1325\begin{methoddesc}{close}{}
1326Calls \method{flush()}, sets the target to \constant{None} and
1327clears the buffer.
1328\end{methoddesc}
1329
1330\begin{methoddesc}{flush}{}
1331For a \class{MemoryHandler}, flushing means just sending the buffered
1332records to the target, if there is one. Override if you want
1333different behavior.
1334\end{methoddesc}
1335
1336\begin{methoddesc}{setTarget}{target}
1337Sets the target handler for this handler.
1338\end{methoddesc}
1339
1340\begin{methoddesc}{shouldFlush}{record}
1341Checks for buffer full or a record at the \var{flushLevel} or higher.
1342\end{methoddesc}
1343
1344\subsubsection{HTTPHandler}
1345
1346The \class{HTTPHandler} class, located in the
1347\module{logging.handlers} module, supports sending logging messages to
1348a Web server, using either \samp{GET} or \samp{POST} semantics.
1349
1350\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
1351Returns a new instance of the \class{HTTPHandler} class. The
1352instance is initialized with a host address, url and HTTP method.
1353The \var{host} can be of the form \code{host:port}, should you need to
1354use a specific port number. If no \var{method} is specified, \samp{GET}
1355is used.
1356\end{classdesc}
1357
1358\begin{methoddesc}{emit}{record}
1359Sends the record to the Web server as an URL-encoded dictionary.
1360\end{methoddesc}
1361
1362\subsection{Formatter Objects}
1363
1364\class{Formatter}s have the following attributes and methods. They are
1365responsible for converting a \class{LogRecord} to (usually) a string
1366which can be interpreted by either a human or an external system. The
1367base
1368\class{Formatter} allows a formatting string to be specified. If none is
1369supplied, the default value of \code{'\%(message)s'} is used.
1370
1371A Formatter can be initialized with a format string which makes use of
1372knowledge of the \class{LogRecord} attributes - such as the default value
1373mentioned above making use of the fact that the user's message and
1374arguments are pre-formatted into a \class{LogRecord}'s \var{message}
1375attribute. This format string contains standard python \%-style
1376mapping keys. See section \ref{typesseq-strings}, ``String Formatting
1377Operations,'' for more information on string formatting.
1378
1379Currently, the useful mapping keys in a \class{LogRecord} are:
1380
1381\begin{tableii}{l|l}{code}{Format}{Description}
1382\lineii{\%(name)s} {Name of the logger (logging channel).}
1383\lineii{\%(levelno)s} {Numeric logging level for the message
1384 (\constant{DEBUG}, \constant{INFO},
1385 \constant{WARNING}, \constant{ERROR},
1386 \constant{CRITICAL}).}
1387\lineii{\%(levelname)s}{Text logging level for the message
1388 (\code{'DEBUG'}, \code{'INFO'},
1389 \code{'WARNING'}, \code{'ERROR'},
1390 \code{'CRITICAL'}).}
1391\lineii{\%(pathname)s} {Full pathname of the source file where the logging
1392 call was issued (if available).}
1393\lineii{\%(filename)s} {Filename portion of pathname.}
1394\lineii{\%(module)s} {Module (name portion of filename).}
1395\lineii{\%(funcName)s} {Name of function containing the logging call.}
1396\lineii{\%(lineno)d} {Source line number where the logging call was issued
1397 (if available).}
1398\lineii{\%(created)f} {Time when the \class{LogRecord} was created (as
1399 returned by \function{time.time()}).}
1400\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
1401 was created. By default this is of the form
1402 ``2003-07-08 16:49:45,896'' (the numbers after the
1403 comma are millisecond portion of the time).}
1404\lineii{\%(msecs)d} {Millisecond portion of the time when the
1405 \class{LogRecord} was created.}
1406\lineii{\%(thread)d} {Thread ID (if available).}
1407\lineii{\%(threadName)s} {Thread name (if available).}
1408\lineii{\%(process)d} {Process ID (if available).}
1409\lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}
1410\end{tableii}
1411
1412\versionchanged[\var{funcName} was added]{2.5}
1413
1414\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
1415Returns a new instance of the \class{Formatter} class. The
1416instance is initialized with a format string for the message as a whole,
1417as well as a format string for the date/time portion of a message. If
1418no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}
1419is specified, the ISO8601 date format is used.
1420\end{classdesc}
1421
1422\begin{methoddesc}{format}{record}
1423The record's attribute dictionary is used as the operand to a
1424string formatting operation. Returns the resulting string.
1425Before formatting the dictionary, a couple of preparatory steps
1426are carried out. The \var{message} attribute of the record is computed
1427using \var{msg} \% \var{args}. If the formatting string contains
1428\code{'(asctime)'}, \method{formatTime()} is called to format the
1429event time. If there is exception information, it is formatted using
1430\method{formatException()} and appended to the message.
1431\end{methoddesc}
1432
1433\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
1434This method should be called from \method{format()} by a formatter which
1435wants to make use of a formatted time. This method can be overridden
1436in formatters to provide for any specific requirement, but the
1437basic behavior is as follows: if \var{datefmt} (a string) is specified,
1438it is used with \function{time.strftime()} to format the creation time of the
1439record. Otherwise, the ISO8601 format is used. The resulting
1440string is returned.
1441\end{methoddesc}
1442
1443\begin{methoddesc}{formatException}{exc_info}
1444Formats the specified exception information (a standard exception tuple
1445as returned by \function{sys.exc_info()}) as a string. This default
1446implementation just uses \function{traceback.print_exception()}.
1447The resulting string is returned.
1448\end{methoddesc}
1449
1450\subsection{Filter Objects}
1451
1452\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
1453more sophisticated filtering than is provided by levels. The base filter
1454class only allows events which are below a certain point in the logger
1455hierarchy. For example, a filter initialized with "A.B" will allow events
1456logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
1457"B.A.B" etc. If initialized with the empty string, all events are passed.
1458
1459\begin{classdesc}{Filter}{\optional{name}}
1460Returns an instance of the \class{Filter} class. If \var{name} is specified,
1461it names a logger which, together with its children, will have its events
1462allowed through the filter. If no name is specified, allows every event.
1463\end{classdesc}
1464
1465\begin{methoddesc}{filter}{record}
1466Is the specified record to be logged? Returns zero for no, nonzero for
1467yes. If deemed appropriate, the record may be modified in-place by this
1468method.
1469\end{methoddesc}
1470
1471\subsection{LogRecord Objects}
1472
1473\class{LogRecord} instances are created every time something is logged. They
1474contain all the information pertinent to the event being logged. The
1475main information passed in is in msg and args, which are combined
1476using msg \% args to create the message field of the record. The record
1477also includes information such as when the record was created, the
1478source line where the logging call was made, and any exception
1479information to be logged.
1480
1481\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
1482 exc_info}
1483Returns an instance of \class{LogRecord} initialized with interesting
1484information. The \var{name} is the logger name; \var{lvl} is the
1485numeric level; \var{pathname} is the absolute pathname of the source
1486file in which the logging call was made; \var{lineno} is the line
1487number in that file where the logging call is found; \var{msg} is the
1488user-supplied message (a format string); \var{args} is the tuple
1489which, together with \var{msg}, makes up the user message; and
1490\var{exc_info} is the exception tuple obtained by calling
1491\function{sys.exc_info() }(or \constant{None}, if no exception information
1492is available).
1493\end{classdesc}
1494
1495\begin{methoddesc}{getMessage}{}
1496Returns the message for this \class{LogRecord} instance after merging any
1497user-supplied arguments with the message.
1498\end{methoddesc}
1499
1500\subsection{Thread Safety}
1501
1502The logging module is intended to be thread-safe without any special work
1503needing to be done by its clients. It achieves this though using threading
1504locks; there is one lock to serialize access to the module's shared data,
1505and each handler also creates a lock to serialize access to its underlying
1506I/O.
1507
1508\subsection{Configuration}
1509
1510
1511\subsubsection{Configuration functions%
1512 \label{logging-config-api}}
1513
1514The following functions configure the logging module. They are located in the
1515\module{logging.config} module. Their use is optional --- you can configure
1516the logging module using these functions or by making calls to the
1517main API (defined in \module{logging} itself) and defining handlers
1518which are declared either in \module{logging} or
1519\module{logging.handlers}.
1520
1521\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
1522Reads the logging configuration from a ConfigParser-format file named
1523\var{fname}. This function can be called several times from an application,
1524allowing an end user the ability to select from various pre-canned
1525configurations (if the developer provides a mechanism to present the
1526choices and load the chosen configuration). Defaults to be passed to
1527ConfigParser can be specified in the \var{defaults} argument.
1528\end{funcdesc}
1529
1530\begin{funcdesc}{listen}{\optional{port}}
1531Starts up a socket server on the specified port, and listens for new
1532configurations. If no port is specified, the module's default
1533\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
1534will be sent as a file suitable for processing by \function{fileConfig()}.
1535Returns a \class{Thread} instance on which you can call \method{start()}
1536to start the server, and which you can \method{join()} when appropriate.
1537To stop the server, call \function{stopListening()}. To send a configuration
1538to the socket, read in the configuration file and send it to the socket
1539as a string of bytes preceded by a four-byte length packed in binary using
1540struct.\code{pack('>L', n)}.
1541\end{funcdesc}
1542
1543\begin{funcdesc}{stopListening}{}
1544Stops the listening server which was created with a call to
1545\function{listen()}. This is typically called before calling \method{join()}
1546on the return value from \function{listen()}.
1547\end{funcdesc}
1548
1549\subsubsection{Configuration file format%
1550 \label{logging-config-fileformat}}
1551
1552The configuration file format understood by \function{fileConfig()} is
1553based on ConfigParser functionality. The file must contain sections
1554called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
1555which identify by name the entities of each type which are defined in
1556the file. For each such entity, there is a separate section which
1557identified how that entity is configured. Thus, for a logger named
1558\code{log01} in the \code{[loggers]} section, the relevant
1559configuration details are held in a section
1560\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
1561the \code{[handlers]} section will have its configuration held in a
1562section called \code{[handler_hand01]}, while a formatter called
1563\code{form01} in the \code{[formatters]} section will have its
1564configuration specified in a section called
1565\code{[formatter_form01]}. The root logger configuration must be
1566specified in a section called \code{[logger_root]}.
1567
1568Examples of these sections in the file are given below.
1569
1570\begin{verbatim}
1571[loggers]
1572keys=root,log02,log03,log04,log05,log06,log07
1573
1574[handlers]
1575keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1576
1577[formatters]
1578keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
1579\end{verbatim}
1580
1581The root logger must specify a level and a list of handlers. An
1582example of a root logger section is given below.
1583
1584\begin{verbatim}
1585[logger_root]
1586level=NOTSET
1587handlers=hand01
1588\end{verbatim}
1589
1590The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1591ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1592\code{NOTSET} means that all messages will be logged. Level values are
1593\function{eval()}uated in the context of the \code{logging} package's
1594namespace.
1595
1596The \code{handlers} entry is a comma-separated list of handler names,
1597which must appear in the \code{[handlers]} section. These names must
1598appear in the \code{[handlers]} section and have corresponding
1599sections in the configuration file.
1600
1601For loggers other than the root logger, some additional information is
1602required. This is illustrated by the following example.
1603
1604\begin{verbatim}
1605[logger_parser]
1606level=DEBUG
1607handlers=hand01
1608propagate=1
1609qualname=compiler.parser
1610\end{verbatim}
1611
1612The \code{level} and \code{handlers} entries are interpreted as for
1613the root logger, except that if a non-root logger's level is specified
1614as \code{NOTSET}, the system consults loggers higher up the hierarchy
1615to determine the effective level of the logger. The \code{propagate}
1616entry is set to 1 to indicate that messages must propagate to handlers
1617higher up the logger hierarchy from this logger, or 0 to indicate that
1618messages are \strong{not} propagated to handlers up the hierarchy. The
1619\code{qualname} entry is the hierarchical channel name of the logger,
1620that is to say the name used by the application to get the logger.
1621
1622Sections which specify handler configuration are exemplified by the
1623following.
1624
1625\begin{verbatim}
1626[handler_hand01]
1627class=StreamHandler
1628level=NOTSET
1629formatter=form01
1630args=(sys.stdout,)
1631\end{verbatim}
1632
1633The \code{class} entry indicates the handler's class (as determined by
1634\function{eval()} in the \code{logging} package's namespace). The
1635\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1636to mean "log everything".
1637
1638The \code{formatter} entry indicates the key name of the formatter for
1639this handler. If blank, a default formatter
1640(\code{logging._defaultFormatter}) is used. If a name is specified, it
1641must appear in the \code{[formatters]} section and have a
1642corresponding section in the configuration file.
1643
1644The \code{args} entry, when \function{eval()}uated in the context of
1645the \code{logging} package's namespace, is the list of arguments to
1646the constructor for the handler class. Refer to the constructors for
1647the relevant handlers, or to the examples below, to see how typical
1648entries are constructed.
1649
1650\begin{verbatim}
1651[handler_hand02]
1652class=FileHandler
1653level=DEBUG
1654formatter=form02
1655args=('python.log', 'w')
1656
1657[handler_hand03]
1658class=handlers.SocketHandler
1659level=INFO
1660formatter=form03
1661args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1662
1663[handler_hand04]
1664class=handlers.DatagramHandler
1665level=WARN
1666formatter=form04
1667args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1668
1669[handler_hand05]
1670class=handlers.SysLogHandler
1671level=ERROR
1672formatter=form05
1673args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1674
1675[handler_hand06]
1676class=handlers.NTEventLogHandler
1677level=CRITICAL
1678formatter=form06
1679args=('Python Application', '', 'Application')
1680
1681[handler_hand07]
1682class=handlers.SMTPHandler
1683level=WARN
1684formatter=form07
1685args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1686
1687[handler_hand08]
1688class=handlers.MemoryHandler
1689level=NOTSET
1690formatter=form08
1691target=
1692args=(10, ERROR)
1693
1694[handler_hand09]
1695class=handlers.HTTPHandler
1696level=NOTSET
1697formatter=form09
1698args=('localhost:9022', '/log', 'GET')
1699\end{verbatim}
1700
1701Sections which specify formatter configuration are typified by the following.
1702
1703\begin{verbatim}
1704[formatter_form01]
1705format=F1 %(asctime)s %(levelname)s %(message)s
1706datefmt=
1707class=logging.Formatter
1708\end{verbatim}
1709
1710The \code{format} entry is the overall format string, and the
1711\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1712string. If empty, the package substitutes ISO8601 format date/times, which
1713is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1714The ISO8601 format also specifies milliseconds, which are appended to the
1715result of using the above format string, with a comma separator. An example
1716time in ISO8601 format is \code{2003-01-23 00:29:50,411}.
1717
1718The \code{class} entry is optional. It indicates the name of the
1719formatter's class (as a dotted module and class name.) This option is
1720useful for instantiating a \class{Formatter} subclass. Subclasses of
1721\class{Formatter} can present exception tracebacks in an expanded or
1722condensed format.
Note: See TracBrowser for help on using the repository browser.