blob: cfbb8384f10da5792c6473ccdef856be9a6a279d [file] [log] [blame]
Skip Montanaro649698f2002-11-14 03:57:19 +00001\section{\module{logging} ---
2 Logging facility for Python}
3
Fred Drake9a5b6a62003-07-08 15:38:40 +00004\declaremodule{standard}{logging}
Skip Montanaro649698f2002-11-14 03:57:19 +00005
6% These apply to all modules, and may be given more than once:
7
8\moduleauthor{Vinay Sajip}{vinay_sajip@red-dove.com}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00009\sectionauthor{Vinay Sajip}{vinay_sajip@red-dove.com}
Skip Montanaro649698f2002-11-14 03:57:19 +000010
Fred Drake68e6d572003-01-28 22:02:35 +000011\modulesynopsis{Logging module for Python based on \pep{282}.}
Skip Montanaro649698f2002-11-14 03:57:19 +000012
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000013\indexii{Errors}{logging}
Skip Montanaro649698f2002-11-14 03:57:19 +000014
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000015\versionadded{2.3}
16This module defines functions and classes which implement a flexible
17error logging system for applications.
Skip Montanaro649698f2002-11-14 03:57:19 +000018
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000019Logging 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.
Skip Montanaro649698f2002-11-14 03:57:19 +000026
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000027Logged 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
Fred Drakec23e0192003-01-28 22:09:16 +000032\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
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000036explicit level argument.
Skip Montanaro649698f2002-11-14 03:57:19 +000037
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000038Levels can also be associated with loggers, being set either by the
39developer or through loading a saved logging configuration. When a
40logging method is called on a logger, the logger compares its own
41level with the level associated with the method call. If the logger's
42level is higher than the method call's, no logging message is actually
43generated. This is the basic mechanism controlling the verbosity of
44logging output.
Skip Montanaro649698f2002-11-14 03:57:19 +000045
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000046Logging messages are encoded as instances of the \class{LogRecord} class.
47When a logger decides to actually log an event, an \class{LogRecord}
48instance is created from the logging message.
Skip Montanaro649698f2002-11-14 03:57:19 +000049
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000050Logging messages are subjected to a dispatch mechanism through the
51use of \dfn{handlers}, which are instances of subclasses of the
52\class{Handler} class. Handlers are responsible for ensuring that a logged
53message (in the form of a \class{LogRecord}) ends up in a particular
54location (or set of locations) which is useful for the target audience for
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +000055that message (such as end users, support desk staff, system administrators,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000056developers). Handlers are passed \class{LogRecord} instances intended for
57particular destinations. Each logger can have zero, one or more handlers
Fred Drake6b3b0462004-04-09 18:26:40 +000058associated with it (via the \method{addHandler()} method of \class{Logger}).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000059In addition to any handlers directly associated with a logger,
Fred Drakec23e0192003-01-28 22:09:16 +000060\emph{all handlers associated with all ancestors of the logger} are
61called to dispatch the message.
Skip Montanaro649698f2002-11-14 03:57:19 +000062
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000063Just as for loggers, handlers can have levels associated with them.
64A handler's level acts as a filter in the same way as a logger's level does.
Fred Drakec23e0192003-01-28 22:09:16 +000065If a handler decides to actually dispatch an event, the \method{emit()} method
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000066is used to send the message to its destination. Most user-defined subclasses
Fred Drakec23e0192003-01-28 22:09:16 +000067of \class{Handler} will need to override this \method{emit()}.
Skip Montanaro649698f2002-11-14 03:57:19 +000068
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000069In addition to the base \class{Handler} class, many useful subclasses
70are provided:
Skip Montanaro649698f2002-11-14 03:57:19 +000071
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000072\begin{enumerate}
Skip Montanaro649698f2002-11-14 03:57:19 +000073
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000074\item \class{StreamHandler} instances send error messages to
75streams (file-like objects).
Skip Montanaro649698f2002-11-14 03:57:19 +000076
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000077\item \class{FileHandler} instances send error messages to disk
78files.
79
80\item \class{RotatingFileHandler} instances send error messages to disk
81files, with support for maximum log file sizes and log file rotation.
82
83\item \class{SocketHandler} instances send error messages to
84TCP/IP sockets.
85
86\item \class{DatagramHandler} instances send error messages to UDP
87sockets.
88
89\item \class{SMTPHandler} instances send error messages to a
90designated email address.
91
92\item \class{SysLogHandler} instances send error messages to a
Fred Drake68e6d572003-01-28 22:02:35 +000093\UNIX{} syslog daemon, possibly on a remote machine.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000094
95\item \class{NTEventLogHandler} instances send error messages to a
96Windows NT/2000/XP event log.
97
98\item \class{MemoryHandler} instances send error messages to a
99buffer in memory, which is flushed whenever specific criteria are
100met.
101
102\item \class{HTTPHandler} instances send error messages to an
Fred Drake68e6d572003-01-28 22:02:35 +0000103HTTP server using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000104
105\end{enumerate}
106
107The \class{StreamHandler} and \class{FileHandler} classes are defined
108in the core logging package. The other handlers are defined in a sub-
109module, \module{logging.handlers}. (There is also another sub-module,
110\module{logging.config}, for configuration functionality.)
111
112Logged messages are formatted for presentation through instances of the
113\class{Formatter} class. They are initialized with a format string
114suitable for use with the \% operator and a dictionary.
115
116For formatting multiple messages in a batch, instances of
117\class{BufferingFormatter} can be used. In addition to the format string
118(which is applied to each message in the batch), there is provision for
119header and trailer format strings.
120
121When filtering based on logger level and/or handler level is not enough,
122instances of \class{Filter} can be added to both \class{Logger} and
Fred Drakec23e0192003-01-28 22:09:16 +0000123\class{Handler} instances (through their \method{addFilter()} method).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000124Before deciding to process a message further, both loggers and handlers
125consult all their filters for permission. If any filter returns a false
126value, the message is not processed further.
127
128The basic \class{Filter} functionality allows filtering by specific logger
129name. If this feature is used, messages sent to the named logger and its
130children are allowed through the filter, and all others dropped.
131
132In addition to the classes described above, there are a number of module-
133level functions.
134
135\begin{funcdesc}{getLogger}{\optional{name}}
136Return a logger with the specified name or, if no name is specified, return
Vinay Sajip17952b72004-08-31 10:21:51 +0000137a logger which is the root logger of the hierarchy. If specified, the name
138is typically a dot-separated hierarchical name like \var{"a"}, \var{"a.b"}
139or \var{"a.b.c.d"}. Choice of these names is entirely up to the developer
140who is using logging.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000141
142All calls to this function with a given name return the same logger instance.
143This means that logger instances never need to be passed between different
144parts of an application.
Skip Montanaro649698f2002-11-14 03:57:19 +0000145\end{funcdesc}
146
Vinay Sajipc6646c02004-09-22 12:55:16 +0000147\begin{funcdesc}{getLoggerClass}{}
148Return either the standard \class{Logger} class, or the last class passed to
149\function{setLoggerClass()}. This function may be called from within a new
150class definition, to ensure that installing a customised \class{Logger} class
151will not undo customisations already applied by other code. For example:
152
153\begin{verbatim}
154 class MyLogger(logging.getLoggerClass()):
155 # ... override behaviour here
156\end{verbatim}
157
158\end{funcdesc}
159
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000160\begin{funcdesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
161Logs a message with level \constant{DEBUG} on the root logger.
162The \var{msg} is the message format string, and the \var{args} are the
163arguments which are merged into \var{msg}. The only keyword argument in
164\var{kwargs} which is inspected is \var{exc_info} which, if it does not
165evaluate as false, causes exception information (via a call to
Fred Drakec23e0192003-01-28 22:09:16 +0000166\function{sys.exc_info()}) to be added to the logging message.
Skip Montanaro649698f2002-11-14 03:57:19 +0000167\end{funcdesc}
168
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000169\begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
170Logs a message with level \constant{INFO} on the root logger.
171The arguments are interpreted as for \function{debug()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000172\end{funcdesc}
173
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000174\begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
175Logs a message with level \constant{WARNING} on the root logger.
176The arguments are interpreted as for \function{debug()}.
177\end{funcdesc}
178
179\begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
180Logs a message with level \constant{ERROR} on the root logger.
181The arguments are interpreted as for \function{debug()}.
182\end{funcdesc}
183
184\begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
185Logs a message with level \constant{CRITICAL} on the root logger.
186The arguments are interpreted as for \function{debug()}.
187\end{funcdesc}
188
189\begin{funcdesc}{exception}{msg\optional{, *args}}
190Logs a message with level \constant{ERROR} on the root logger.
191The arguments are interpreted as for \function{debug()}. Exception info
192is added to the logging message. This function should only be called
193from an exception handler.
194\end{funcdesc}
195
196\begin{funcdesc}{disable}{lvl}
197Provides an overriding level \var{lvl} for all loggers which takes
198precedence over the logger's own level. When the need arises to
199temporarily throttle logging output down across the whole application,
200this function can be useful.
201\end{funcdesc}
202
203\begin{funcdesc}{addLevelName}{lvl, levelName}
204Associates level \var{lvl} with text \var{levelName} in an internal
205dictionary, which is used to map numeric levels to a textual
206representation, for example when a \class{Formatter} formats a message.
207This function can also be used to define your own levels. The only
208constraints are that all levels used must be registered using this
209function, levels should be positive integers and they should increase
210in increasing order of severity.
211\end{funcdesc}
212
213\begin{funcdesc}{getLevelName}{lvl}
214Returns the textual representation of logging level \var{lvl}. If the
215level is one of the predefined levels \constant{CRITICAL},
216\constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG}
217then you get the corresponding string. If you have associated levels
218with names using \function{addLevelName()} then the name you have associated
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000219with \var{lvl} is returned. If a numeric value corresponding to one of the
220defined levels is passed in, the corresponding string representation is
221returned. Otherwise, the string "Level \%s" \% lvl is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000222\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000223
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000224\begin{funcdesc}{makeLogRecord}{attrdict}
225Creates and returns a new \class{LogRecord} instance whose attributes are
226defined by \var{attrdict}. This function is useful for taking a pickled
227\class{LogRecord} attribute dictionary, sent over a socket, and reconstituting
228it as a \class{LogRecord} instance at the receiving end.
229\end{funcdesc}
230
Skip Montanaro649698f2002-11-14 03:57:19 +0000231\begin{funcdesc}{basicConfig}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000232Does basic configuration for the logging system by creating a
233\class{StreamHandler} with a default \class{Formatter} and adding it to
234the root logger. The functions \function{debug()}, \function{info()},
235\function{warning()}, \function{error()} and \function{critical()} will call
236\function{basicConfig()} automatically if no handlers are defined for the
237root logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000238\end{funcdesc}
239
Skip Montanaro649698f2002-11-14 03:57:19 +0000240\begin{funcdesc}{shutdown}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000241Informs the logging system to perform an orderly shutdown by flushing and
242closing all handlers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000243\end{funcdesc}
244
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000245\begin{funcdesc}{setLoggerClass}{klass}
246Tells the logging system to use the class \var{klass} when instantiating a
247logger. The class should define \method{__init__()} such that only a name
248argument is required, and the \method{__init__()} should call
249\method{Logger.__init__()}. This function is typically called before any
250loggers are instantiated by applications which need to use custom logger
251behavior.
252\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000253
Fred Drake68e6d572003-01-28 22:02:35 +0000254
255\begin{seealso}
256 \seepep{282}{A Logging System}
257 {The proposal which described this feature for inclusion in
258 the Python standard library.}
Fred Drake11514792004-01-08 14:59:02 +0000259 \seelink{http://www.red-dove.com/python_logging.html}
260 {Original Python \module{logging} package}
261 {This is the original source for the \module{logging}
262 package. The version of the package available from this
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000263 site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x,
264 which do not include the \module{logging} package in the standard
Fred Drake11514792004-01-08 14:59:02 +0000265 library.}
Fred Drake68e6d572003-01-28 22:02:35 +0000266\end{seealso}
267
268
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000269\subsection{Logger Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000270
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000271Loggers have the following attributes and methods. Note that Loggers are
272never instantiated directly, but always through the module-level function
273\function{logging.getLogger(name)}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000274
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000275\begin{datadesc}{propagate}
276If this evaluates to false, logging messages are not passed by this
277logger or by child loggers to higher level (ancestor) loggers. The
278constructor sets this attribute to 1.
Skip Montanaro649698f2002-11-14 03:57:19 +0000279\end{datadesc}
280
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000281\begin{methoddesc}{setLevel}{lvl}
282Sets the threshold for this logger to \var{lvl}. Logging messages
283which are less severe than \var{lvl} will be ignored. When a logger is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000284created, the level is set to \constant{NOTSET} (which causes all messages
285to be processed in the root logger, or delegation to the parent in non-root
286loggers).
Skip Montanaro649698f2002-11-14 03:57:19 +0000287\end{methoddesc}
288
289\begin{methoddesc}{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000290Indicates if a message of severity \var{lvl} would be processed by
291this logger. This method checks first the module-level level set by
292\function{logging.disable(lvl)} and then the logger's effective level as
293determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000294\end{methoddesc}
295
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000296\begin{methoddesc}{getEffectiveLevel}{}
297Indicates the effective level for this logger. If a value other than
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000298\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000299Otherwise, the hierarchy is traversed towards the root until a value
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000300other than \constant{NOTSET} is found, and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000301\end{methoddesc}
302
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000303\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
304Logs a message with level \constant{DEBUG} on this logger.
305The \var{msg} is the message format string, and the \var{args} are the
306arguments which are merged into \var{msg}. The only keyword argument in
307\var{kwargs} which is inspected is \var{exc_info} which, if it does not
308evaluate as false, causes exception information (via a call to
Fred Drakec23e0192003-01-28 22:09:16 +0000309\function{sys.exc_info()}) to be added to the logging message.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000310\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000311
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000312\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
313Logs a message with level \constant{INFO} on this logger.
314The arguments are interpreted as for \method{debug()}.
315\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000316
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000317\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
318Logs a message with level \constant{WARNING} on this logger.
319The arguments are interpreted as for \method{debug()}.
320\end{methoddesc}
321
322\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
323Logs a message with level \constant{ERROR} on this logger.
324The arguments are interpreted as for \method{debug()}.
325\end{methoddesc}
326
327\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
328Logs a message with level \constant{CRITICAL} on this logger.
329The arguments are interpreted as for \method{debug()}.
330\end{methoddesc}
331
332\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
Vinay Sajip1cf56d02004-08-04 08:36:44 +0000333Logs a message with integer level \var{lvl} on this logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000334The other arguments are interpreted as for \method{debug()}.
335\end{methoddesc}
336
337\begin{methoddesc}{exception}{msg\optional{, *args}}
338Logs a message with level \constant{ERROR} on this logger.
339The arguments are interpreted as for \method{debug()}. Exception info
340is added to the logging message. This method should only be called
341from an exception handler.
342\end{methoddesc}
343
344\begin{methoddesc}{addFilter}{filt}
345Adds the specified filter \var{filt} to this logger.
346\end{methoddesc}
347
348\begin{methoddesc}{removeFilter}{filt}
349Removes the specified filter \var{filt} from this logger.
350\end{methoddesc}
351
352\begin{methoddesc}{filter}{record}
353Applies this logger's filters to the record and returns a true value if
354the record is to be processed.
355\end{methoddesc}
356
357\begin{methoddesc}{addHandler}{hdlr}
358Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000359\end{methoddesc}
360
361\begin{methoddesc}{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000362Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000363\end{methoddesc}
364
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000365\begin{methoddesc}{findCaller}{}
366Finds the caller's source filename and line number. Returns the filename
367and line number as a 2-element tuple.
Skip Montanaro649698f2002-11-14 03:57:19 +0000368\end{methoddesc}
369
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000370\begin{methoddesc}{handle}{record}
371Handles a record by passing it to all handlers associated with this logger
372and its ancestors (until a false value of \var{propagate} is found).
373This method is used for unpickled records received from a socket, as well
374as those created locally. Logger-level filtering is applied using
375\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000376\end{methoddesc}
377
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000378\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info}
379This is a factory method which can be overridden in subclasses to create
380specialized \class{LogRecord} instances.
Skip Montanaro649698f2002-11-14 03:57:19 +0000381\end{methoddesc}
382
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000383\subsection{Basic example \label{minimal-example}}
384
385The \module{logging} package provides a lot of flexibility, and its
386configuration can appear daunting. This section demonstrates that simple
387use of the logging package is possible.
388
389The simplest example shows logging to the console:
390
391\begin{verbatim}
392import logging
393
394logging.debug('A debug message')
395logging.info('Some information')
396logging.warning('A shot across the bows')
397\end{verbatim}
398
399If you run the above script, you'll see this:
400\begin{verbatim}
401WARNING:root:A shot across the bows
402\end{verbatim}
403
404Because no particular logger was specified, the system used the root logger.
405The debug and info messages didn't appear because by default, the root
406logger is configured to only handle messages with a severity of WARNING
407or above. The message format is also a configuration default, as is the output
408destination of the messages - \code{sys.stderr}. The severity level,
409the message format and destination can be easily changed, as shown in
410the example below:
411
412\begin{verbatim}
413import logging
414
415logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000416 format='%(asctime)s %(levelname)s %(message)s',
417 filename='/tmp/myapp.log',
418 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000419logging.debug('A debug message')
420logging.info('Some information')
421logging.warning('A shot across the bows')
422\end{verbatim}
423
424The \method{basicConfig()} method is used to change the configuration
425defaults, which results in output (written to \code{/tmp/myapp.log})
426which should look something like the following:
427
428\begin{verbatim}
4292004-07-02 13:00:08,743 DEBUG A debug message
4302004-07-02 13:00:08,743 INFO Some information
4312004-07-02 13:00:08,743 WARNING A shot across the bows
432\end{verbatim}
433
434This time, all messages with a severity of DEBUG or above were handled,
435and the format of the messages was also changed, and output went to the
436specified file rather than the console.
437
438Formatting uses standard Python string formatting - see section
439\ref{typesseq-strings}. The format string takes the following
440common specifiers. For a complete list of specifiers, consult the
441\class{Formatter} documentation.
442
443\begin{tableii}{l|l}{code}{Format}{Description}
444\lineii{\%(name)s} {Name of the logger (logging channel).}
445\lineii{\%(levelname)s}{Text logging level for the message
446 (\code{'DEBUG'}, \code{'INFO'},
447 \code{'WARNING'}, \code{'ERROR'},
448 \code{'CRITICAL'}).}
449\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
450 was created. By default this is of the form
451 ``2003-07-08 16:49:45,896'' (the numbers after the
452 comma are millisecond portion of the time).}
453\lineii{\%(message)s} {The logged message.}
454\end{tableii}
455
456To change the date/time format, you can pass an additional keyword parameter,
457\var{datefmt}, as in the following:
458
459\begin{verbatim}
460import logging
461
462logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000463 format='%(asctime)s %(levelname)-8s %(message)s',
464 datefmt='%a, %d %b %Y %H:%M:%S',
465 filename='/temp/myapp.log',
466 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000467logging.debug('A debug message')
468logging.info('Some information')
469logging.warning('A shot across the bows')
470\end{verbatim}
471
472which would result in output like
473
474\begin{verbatim}
475Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
476Fri, 02 Jul 2004 13:06:18 INFO Some information
477Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
478\end{verbatim}
479
480The date format string follows the requirements of \function{strftime()} -
481see the documentation for the \refmodule{time} module.
482
483If, instead of sending logging output to the console or a file, you'd rather
484use a file-like object which you have created separately, you can pass it
485to \function{basicConfig()} using the \var{stream} keyword argument. Note
486that if both \var{stream} and \var{filename} keyword arguments are passed,
487the \var{stream} argument is ignored.
488
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000489Of course, you can put variable information in your output. To do this,
490simply have the message be a format string and pass in additional arguments
491containing the variable information, as in the following example:
492
493\begin{verbatim}
494import logging
495
496logging.basicConfig(level=logging.DEBUG,
497 format='%(asctime)s %(levelname)-8s %(message)s',
498 datefmt='%a, %d %b %Y %H:%M:%S',
499 filename='/temp/myapp.log',
500 filemode='w')
501logging.error('Pack my box with %d dozen %s', 12, 'liquor jugs')
502\end{verbatim}
503
504which would result in
505
506\begin{verbatim}
507Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 12 dozen liquor jugs
508\end{verbatim}
509
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000510\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000511
Fred Drake68e6d572003-01-28 22:02:35 +0000512Handlers have the following attributes and methods. Note that
513\class{Handler} is never instantiated directly; this class acts as a
514base for more useful subclasses. However, the \method{__init__()}
515method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000516
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000517\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000518Initializes the \class{Handler} instance by setting its level, setting
519the list of filters to the empty list and creating a lock (using
Raymond Hettingerc75c3e02003-09-01 22:50:52 +0000520\method{createLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000521\end{methoddesc}
522
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000523\begin{methoddesc}{createLock}{}
524Initializes a thread lock which can be used to serialize access to
525underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000526\end{methoddesc}
527
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000528\begin{methoddesc}{acquire}{}
529Acquires the thread lock created with \method{createLock()}.
530\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000531
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000532\begin{methoddesc}{release}{}
533Releases the thread lock acquired with \method{acquire()}.
534\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000535
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000536\begin{methoddesc}{setLevel}{lvl}
537Sets the threshold for this handler to \var{lvl}. Logging messages which are
538less severe than \var{lvl} will be ignored. When a handler is created, the
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000539level is set to \constant{NOTSET} (which causes all messages to be processed).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000540\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000541
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000542\begin{methoddesc}{setFormatter}{form}
543Sets the \class{Formatter} for this handler to \var{form}.
544\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000545
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000546\begin{methoddesc}{addFilter}{filt}
547Adds the specified filter \var{filt} to this handler.
548\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000549
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000550\begin{methoddesc}{removeFilter}{filt}
551Removes the specified filter \var{filt} from this handler.
552\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000553
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000554\begin{methoddesc}{filter}{record}
555Applies this handler's filters to the record and returns a true value if
556the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000557\end{methoddesc}
558
559\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000560Ensure all logging output has been flushed. This version does
561nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000562\end{methoddesc}
563
Skip Montanaro649698f2002-11-14 03:57:19 +0000564\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000565Tidy up any resources used by the handler. This version does
566nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000567\end{methoddesc}
568
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000569\begin{methoddesc}{handle}{record}
570Conditionally emits the specified logging record, depending on
571filters which may have been added to the handler. Wraps the actual
572emission of the record with acquisition/release of the I/O thread
573lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000574\end{methoddesc}
575
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000576\begin{methoddesc}{handleError}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000577This method should be called from handlers when an exception is
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000578encountered during an \method{emit()} call. By default it does nothing,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000579which means that exceptions get silently ignored. This is what is
580mostly wanted for a logging system - most users will not care
581about errors in the logging system, they are more interested in
582application errors. You could, however, replace this with a custom
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000583handler if you wish. The specified record is the one which was being
584processed when the exception occurred.
Skip Montanaro649698f2002-11-14 03:57:19 +0000585\end{methoddesc}
586
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000587\begin{methoddesc}{format}{record}
588Do formatting for a record - if a formatter is set, use it.
589Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000590\end{methoddesc}
591
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000592\begin{methoddesc}{emit}{record}
593Do whatever it takes to actually log the specified logging record.
594This version is intended to be implemented by subclasses and so
595raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000596\end{methoddesc}
597
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000598\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000599
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000600The \class{StreamHandler} class sends logging output to streams such as
601\var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more
602precisely, any object which supports \method{write()} and \method{flush()}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000603methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000604
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000605\begin{classdesc}{StreamHandler}{\optional{strm}}
606Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
607specified, the instance will use it for logging output; otherwise,
608\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000609\end{classdesc}
610
611\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000612If a formatter is specified, it is used to format the record.
613The record is then written to the stream with a trailing newline.
614If exception information is present, it is formatted using
615\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000616\end{methoddesc}
617
618\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000619Flushes the stream by calling its \method{flush()} method. Note that
620the \method{close()} method is inherited from \class{Handler} and
621so does nothing, so an explicit \method{flush()} call may be needed
622at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000623\end{methoddesc}
624
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000625\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000626
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000627The \class{FileHandler} class sends logging output to a disk file.
Fred Drake68e6d572003-01-28 22:02:35 +0000628It inherits the output functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000629
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000630\begin{classdesc}{FileHandler}{filename\optional{, mode}}
631Returns a new instance of the \class{FileHandler} class. The specified
632file is opened and used as the stream for logging. If \var{mode} is
Fred Drake9a5b6a62003-07-08 15:38:40 +0000633not specified, \constant{'a'} is used. By default, the file grows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000634indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000635\end{classdesc}
636
637\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000638Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000639\end{methoddesc}
640
641\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000642Outputs the record to the file.
643\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000644
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000645\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000646
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000647The \class{RotatingFileHandler} class supports rotation of disk log files.
648
Fred Drake9a5b6a62003-07-08 15:38:40 +0000649\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{,
650 maxBytes\optional{, backupCount}}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000651Returns a new instance of the \class{RotatingFileHandler} class. The
652specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +0000653\var{mode} is not specified, \code{'a'} is used. By default, the
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000654file grows indefinitely.
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000655
656You can use the \var{maxBytes} and
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000657\var{backupCount} values to allow the file to \dfn{rollover} at a
658predetermined size. When the size is about to be exceeded, the file is
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000659closed and a new file is silently opened for output. Rollover occurs
660whenever the current log file is nearly \var{maxBytes} in length; if
661\var{maxBytes} is zero, rollover never occurs. If \var{backupCount}
662is non-zero, the system will save old log files by appending the
663extensions ".1", ".2" etc., to the filename. For example, with
664a \var{backupCount} of 5 and a base file name of
665\file{app.log}, you would get \file{app.log},
666\file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being
667written to is always \file{app.log}. When this file is filled, it is
668closed and renamed to \file{app.log.1}, and if files \file{app.log.1},
669\file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2},
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000670\file{app.log.3} etc. respectively.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000671\end{classdesc}
672
673\begin{methoddesc}{doRollover}{}
674Does a rollover, as described above.
675\end{methoddesc}
676
677\begin{methoddesc}{emit}{record}
678Outputs the record to the file, catering for rollover as described
679in \method{setRollover()}.
680\end{methoddesc}
681
682\subsubsection{SocketHandler}
683
684The \class{SocketHandler} class sends logging output to a network
685socket. The base class uses a TCP socket.
686
687\begin{classdesc}{SocketHandler}{host, port}
688Returns a new instance of the \class{SocketHandler} class intended to
689communicate with a remote machine whose address is given by \var{host}
690and \var{port}.
691\end{classdesc}
692
693\begin{methoddesc}{close}{}
694Closes the socket.
695\end{methoddesc}
696
697\begin{methoddesc}{handleError}{}
698\end{methoddesc}
699
700\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000701Pickles the record's attribute dictionary and writes it to the socket in
702binary format. If there is an error with the socket, silently drops the
703packet. If the connection was previously lost, re-establishes the connection.
Fred Drake6b3b0462004-04-09 18:26:40 +0000704To unpickle the record at the receiving end into a \class{LogRecord}, use the
705\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000706\end{methoddesc}
707
708\begin{methoddesc}{handleError}{}
709Handles an error which has occurred during \method{emit()}. The
710most likely cause is a lost connection. Closes the socket so that
711we can retry on the next event.
712\end{methoddesc}
713
714\begin{methoddesc}{makeSocket}{}
715This is a factory method which allows subclasses to define the precise
716type of socket they want. The default implementation creates a TCP
717socket (\constant{socket.SOCK_STREAM}).
718\end{methoddesc}
719
720\begin{methoddesc}{makePickle}{record}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000721Pickles the record's attribute dictionary in binary format with a length
722prefix, and returns it ready for transmission across the socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000723\end{methoddesc}
724
725\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000726Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000727for partial sends which can happen when the network is busy.
728\end{methoddesc}
729
730\subsubsection{DatagramHandler}
731
732The \class{DatagramHandler} class inherits from \class{SocketHandler}
733to support sending logging messages over UDP sockets.
734
735\begin{classdesc}{DatagramHandler}{host, port}
736Returns a new instance of the \class{DatagramHandler} class intended to
737communicate with a remote machine whose address is given by \var{host}
738and \var{port}.
739\end{classdesc}
740
741\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000742Pickles the record's attribute dictionary and writes it to the socket in
743binary format. If there is an error with the socket, silently drops the
744packet.
Fred Drake6b3b0462004-04-09 18:26:40 +0000745To unpickle the record at the receiving end into a \class{LogRecord}, use the
746\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000747\end{methoddesc}
748
749\begin{methoddesc}{makeSocket}{}
750The factory method of \class{SocketHandler} is here overridden to create
751a UDP socket (\constant{socket.SOCK_DGRAM}).
752\end{methoddesc}
753
754\begin{methoddesc}{send}{s}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000755Send a pickled string to a socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000756\end{methoddesc}
757
758\subsubsection{SysLogHandler}
759
760The \class{SysLogHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000761remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000762
763\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
764Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +0000765communicate with a remote \UNIX{} machine whose address is given by
766\var{address} in the form of a \code{(\var{host}, \var{port})}
767tuple. If \var{address} is not specified, \code{('localhost', 514)} is
768used. The address is used to open a UDP socket. If \var{facility} is
769not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000770\end{classdesc}
771
772\begin{methoddesc}{close}{}
773Closes the socket to the remote host.
774\end{methoddesc}
775
776\begin{methoddesc}{emit}{record}
777The record is formatted, and then sent to the syslog server. If
778exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +0000779\end{methoddesc}
780
781\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000782Encodes the facility and priority into an integer. You can pass in strings
783or integers - if strings are passed, internal mapping dictionaries are used
784to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000785\end{methoddesc}
786
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000787\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000788
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000789The \class{NTEventLogHandler} class supports sending logging messages
790to a local Windows NT, Windows 2000 or Windows XP event log. Before
791you can use it, you need Mark Hammond's Win32 extensions for Python
792installed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000793
Fred Drake9a5b6a62003-07-08 15:38:40 +0000794\begin{classdesc}{NTEventLogHandler}{appname\optional{,
795 dllname\optional{, logtype}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000796Returns a new instance of the \class{NTEventLogHandler} class. The
797\var{appname} is used to define the application name as it appears in the
798event log. An appropriate registry entry is created using this name.
799The \var{dllname} should give the fully qualified pathname of a .dll or .exe
800which contains message definitions to hold in the log (if not specified,
Fred Drake9a5b6a62003-07-08 15:38:40 +0000801\code{'win32service.pyd'} is used - this is installed with the Win32
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000802extensions and contains some basic placeholder message definitions.
803Note that use of these placeholders will make your event logs big, as the
804entire message source is held in the log. If you want slimmer logs, you have
805to pass in the name of your own .dll or .exe which contains the message
806definitions you want to use in the event log). The \var{logtype} is one of
Fred Drake9a5b6a62003-07-08 15:38:40 +0000807\code{'Application'}, \code{'System'} or \code{'Security'}, and
808defaults to \code{'Application'}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000809\end{classdesc}
810
811\begin{methoddesc}{close}{}
812At this point, you can remove the application name from the registry as a
813source of event log entries. However, if you do this, you will not be able
814to see the events as you intended in the Event Log Viewer - it needs to be
815able to access the registry to get the .dll name. The current version does
816not do this (in fact it doesn't do anything).
817\end{methoddesc}
818
819\begin{methoddesc}{emit}{record}
820Determines the message ID, event category and event type, and then logs the
821message in the NT event log.
822\end{methoddesc}
823
824\begin{methoddesc}{getEventCategory}{record}
825Returns the event category for the record. Override this if you
826want to specify your own categories. This version returns 0.
827\end{methoddesc}
828
829\begin{methoddesc}{getEventType}{record}
830Returns the event type for the record. Override this if you want
831to specify your own types. This version does a mapping using the
832handler's typemap attribute, which is set up in \method{__init__()}
833to a dictionary which contains mappings for \constant{DEBUG},
834\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
835\constant{CRITICAL}. If you are using your own levels, you will either need
836to override this method or place a suitable dictionary in the
837handler's \var{typemap} attribute.
838\end{methoddesc}
839
840\begin{methoddesc}{getMessageID}{record}
841Returns the message ID for the record. If you are using your
842own messages, you could do this by having the \var{msg} passed to the
843logger being an ID rather than a format string. Then, in here,
844you could use a dictionary lookup to get the message ID. This
845version returns 1, which is the base message ID in
Fred Drake9a5b6a62003-07-08 15:38:40 +0000846\file{win32service.pyd}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000847\end{methoddesc}
848
849\subsubsection{SMTPHandler}
850
851The \class{SMTPHandler} class supports sending logging messages to an email
852address via SMTP.
853
854\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
855Returns a new instance of the \class{SMTPHandler} class. The
856instance is initialized with the from and to addresses and subject
857line of the email. The \var{toaddrs} should be a list of strings without
858domain names (That's what the \var{mailhost} is for). To specify a
859non-standard SMTP port, use the (host, port) tuple format for the
860\var{mailhost} argument. If you use a string, the standard SMTP port
861is used.
862\end{classdesc}
863
864\begin{methoddesc}{emit}{record}
865Formats the record and sends it to the specified addressees.
866\end{methoddesc}
867
868\begin{methoddesc}{getSubject}{record}
869If you want to specify a subject line which is record-dependent,
870override this method.
871\end{methoddesc}
872
873\subsubsection{MemoryHandler}
874
875The \class{MemoryHandler} supports buffering of logging records in memory,
876periodically flushing them to a \dfn{target} handler. Flushing occurs
877whenever the buffer is full, or when an event of a certain severity or
878greater is seen.
879
880\class{MemoryHandler} is a subclass of the more general
881\class{BufferingHandler}, which is an abstract class. This buffers logging
882records in memory. Whenever each record is added to the buffer, a
883check is made by calling \method{shouldFlush()} to see if the buffer
884should be flushed. If it should, then \method{flush()} is expected to
885do the needful.
886
887\begin{classdesc}{BufferingHandler}{capacity}
888Initializes the handler with a buffer of the specified capacity.
889\end{classdesc}
890
891\begin{methoddesc}{emit}{record}
892Appends the record to the buffer. If \method{shouldFlush()} returns true,
893calls \method{flush()} to process the buffer.
894\end{methoddesc}
895
896\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000897You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000898just zaps the buffer to empty.
899\end{methoddesc}
900
901\begin{methoddesc}{shouldFlush}{record}
902Returns true if the buffer is up to capacity. This method can be
903overridden to implement custom flushing strategies.
904\end{methoddesc}
905
906\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000907\optional{, target}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000908Returns a new instance of the \class{MemoryHandler} class. The
909instance is initialized with a buffer size of \var{capacity}. If
910\var{flushLevel} is not specified, \constant{ERROR} is used. If no
911\var{target} is specified, the target will need to be set using
912\method{setTarget()} before this handler does anything useful.
913\end{classdesc}
914
915\begin{methoddesc}{close}{}
916Calls \method{flush()}, sets the target to \constant{None} and
917clears the buffer.
918\end{methoddesc}
919
920\begin{methoddesc}{flush}{}
921For a \class{MemoryHandler}, flushing means just sending the buffered
922records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000923different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000924\end{methoddesc}
925
926\begin{methoddesc}{setTarget}{target}
927Sets the target handler for this handler.
928\end{methoddesc}
929
930\begin{methoddesc}{shouldFlush}{record}
931Checks for buffer full or a record at the \var{flushLevel} or higher.
932\end{methoddesc}
933
934\subsubsection{HTTPHandler}
935
936The \class{HTTPHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000937Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000938
939\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
940Returns a new instance of the \class{HTTPHandler} class. The
941instance is initialized with a host address, url and HTTP method.
Fred Drake68e6d572003-01-28 22:02:35 +0000942If no \var{method} is specified, \samp{GET} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000943\end{classdesc}
944
945\begin{methoddesc}{emit}{record}
946Sends the record to the Web server as an URL-encoded dictionary.
947\end{methoddesc}
948
949\subsection{Formatter Objects}
950
951\class{Formatter}s have the following attributes and methods. They are
952responsible for converting a \class{LogRecord} to (usually) a string
953which can be interpreted by either a human or an external system. The
954base
955\class{Formatter} allows a formatting string to be specified. If none is
Fred Drake8efc74d2004-04-15 06:18:48 +0000956supplied, the default value of \code{'\%(message)s'} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000957
958A Formatter can be initialized with a format string which makes use of
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000959knowledge of the \class{LogRecord} attributes - such as the default value
960mentioned above making use of the fact that the user's message and
Fred Drake6b3b0462004-04-09 18:26:40 +0000961arguments are pre-formatted into a \class{LogRecord}'s \var{message}
Anthony Baxtera6b7d342003-07-08 08:40:20 +0000962attribute. This format string contains standard python \%-style
963mapping keys. See section \ref{typesseq-strings}, ``String Formatting
964Operations,'' for more information on string formatting.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000965
Fred Drake6b3b0462004-04-09 18:26:40 +0000966Currently, the useful mapping keys in a \class{LogRecord} are:
Anthony Baxtera6b7d342003-07-08 08:40:20 +0000967
Fred Drake9a5b6a62003-07-08 15:38:40 +0000968\begin{tableii}{l|l}{code}{Format}{Description}
969\lineii{\%(name)s} {Name of the logger (logging channel).}
970\lineii{\%(levelno)s} {Numeric logging level for the message
971 (\constant{DEBUG}, \constant{INFO},
972 \constant{WARNING}, \constant{ERROR},
973 \constant{CRITICAL}).}
974\lineii{\%(levelname)s}{Text logging level for the message
975 (\code{'DEBUG'}, \code{'INFO'},
976 \code{'WARNING'}, \code{'ERROR'},
977 \code{'CRITICAL'}).}
978\lineii{\%(pathname)s} {Full pathname of the source file where the logging
979 call was issued (if available).}
980\lineii{\%(filename)s} {Filename portion of pathname.}
981\lineii{\%(module)s} {Module (name portion of filename).}
982\lineii{\%(lineno)d} {Source line number where the logging call was issued
983 (if available).}
Fred Drake6b3b0462004-04-09 18:26:40 +0000984\lineii{\%(created)f} {Time when the \class{LogRecord} was created (as
Fred Drake9a5b6a62003-07-08 15:38:40 +0000985 returned by \function{time.time()}).}
Fred Drake6b3b0462004-04-09 18:26:40 +0000986\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
987 was created. By default this is of the form
Fred Drake9a5b6a62003-07-08 15:38:40 +0000988 ``2003-07-08 16:49:45,896'' (the numbers after the
989 comma are millisecond portion of the time).}
990\lineii{\%(msecs)d} {Millisecond portion of the time when the
991 \class{LogRecord} was created.}
992\lineii{\%(thread)d} {Thread ID (if available).}
993\lineii{\%(process)d} {Process ID (if available).}
994\lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}
Anthony Baxtera6b7d342003-07-08 08:40:20 +0000995\end{tableii}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000996
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000997\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
998Returns a new instance of the \class{Formatter} class. The
999instance is initialized with a format string for the message as a whole,
1000as well as a format string for the date/time portion of a message. If
Neal Norwitzdd3afa72003-07-08 16:26:34 +00001001no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001002is specified, the ISO8601 date format is used.
1003\end{classdesc}
1004
1005\begin{methoddesc}{format}{record}
1006The record's attribute dictionary is used as the operand to a
1007string formatting operation. Returns the resulting string.
1008Before formatting the dictionary, a couple of preparatory steps
1009are carried out. The \var{message} attribute of the record is computed
1010using \var{msg} \% \var{args}. If the formatting string contains
Fred Drake9a5b6a62003-07-08 15:38:40 +00001011\code{'(asctime)'}, \method{formatTime()} is called to format the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001012event time. If there is exception information, it is formatted using
1013\method{formatException()} and appended to the message.
1014\end{methoddesc}
1015
1016\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
1017This method should be called from \method{format()} by a formatter which
1018wants to make use of a formatted time. This method can be overridden
1019in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001020basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +00001021it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001022record. Otherwise, the ISO8601 format is used. The resulting
1023string is returned.
1024\end{methoddesc}
1025
1026\begin{methoddesc}{formatException}{exc_info}
1027Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +00001028as returned by \function{sys.exc_info()}) as a string. This default
1029implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001030The resulting string is returned.
1031\end{methoddesc}
1032
1033\subsection{Filter Objects}
1034
1035\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
1036more sophisticated filtering than is provided by levels. The base filter
1037class only allows events which are below a certain point in the logger
1038hierarchy. For example, a filter initialized with "A.B" will allow events
1039logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
1040"B.A.B" etc. If initialized with the empty string, all events are passed.
1041
1042\begin{classdesc}{Filter}{\optional{name}}
1043Returns an instance of the \class{Filter} class. If \var{name} is specified,
1044it names a logger which, together with its children, will have its events
1045allowed through the filter. If no name is specified, allows every event.
1046\end{classdesc}
1047
1048\begin{methoddesc}{filter}{record}
1049Is the specified record to be logged? Returns zero for no, nonzero for
1050yes. If deemed appropriate, the record may be modified in-place by this
1051method.
1052\end{methoddesc}
1053
1054\subsection{LogRecord Objects}
1055
Fred Drake6b3b0462004-04-09 18:26:40 +00001056\class{LogRecord} instances are created every time something is logged. They
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001057contain all the information pertinent to the event being logged. The
1058main information passed in is in msg and args, which are combined
1059using msg \% args to create the message field of the record. The record
1060also includes information such as when the record was created, the
1061source line where the logging call was made, and any exception
1062information to be logged.
1063
Fred Drake6b3b0462004-04-09 18:26:40 +00001064\class{LogRecord} has no methods; it's just a repository for
1065information about the logging event. The only reason it's a class
1066rather than a dictionary is to facilitate extension.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001067
1068\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001069 exc_info}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001070Returns an instance of \class{LogRecord} initialized with interesting
1071information. The \var{name} is the logger name; \var{lvl} is the
1072numeric level; \var{pathname} is the absolute pathname of the source
1073file in which the logging call was made; \var{lineno} is the line
1074number in that file where the logging call is found; \var{msg} is the
1075user-supplied message (a format string); \var{args} is the tuple
1076which, together with \var{msg}, makes up the user message; and
1077\var{exc_info} is the exception tuple obtained by calling
1078\function{sys.exc_info() }(or \constant{None}, if no exception information
1079is available).
1080\end{classdesc}
1081
1082\subsection{Thread Safety}
1083
1084The logging module is intended to be thread-safe without any special work
1085needing to be done by its clients. It achieves this though using threading
1086locks; there is one lock to serialize access to the module's shared data,
1087and each handler also creates a lock to serialize access to its underlying
1088I/O.
1089
1090\subsection{Configuration}
1091
1092
Fred Drake94ffbb72004-04-08 19:44:31 +00001093\subsubsection{Configuration functions%
1094 \label{logging-config-api}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001095
Fred Drake9a5b6a62003-07-08 15:38:40 +00001096The following functions allow the logging module to be
1097configured. Before they can be used, you must import
1098\module{logging.config}. Their use is optional --- you can configure
1099the logging module entirely by making calls to the main API (defined
1100in \module{logging} itself) and defining handlers which are declared
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001101either in \module{logging} or \module{logging.handlers}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001102
1103\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
1104Reads the logging configuration from a ConfigParser-format file named
1105\var{fname}. This function can be called several times from an application,
1106allowing an end user the ability to select from various pre-canned
1107configurations (if the developer provides a mechanism to present the
1108choices and load the chosen configuration). Defaults to be passed to
1109ConfigParser can be specified in the \var{defaults} argument.
1110\end{funcdesc}
1111
1112\begin{funcdesc}{listen}{\optional{port}}
1113Starts up a socket server on the specified port, and listens for new
1114configurations. If no port is specified, the module's default
1115\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
1116will be sent as a file suitable for processing by \function{fileConfig()}.
1117Returns a \class{Thread} instance on which you can call \method{start()}
1118to start the server, and which you can \method{join()} when appropriate.
1119To stop the server, call \function{stopListening()}.
1120\end{funcdesc}
1121
1122\begin{funcdesc}{stopListening}{}
1123Stops the listening server which was created with a call to
1124\function{listen()}. This is typically called before calling \method{join()}
1125on the return value from \function{listen()}.
1126\end{funcdesc}
1127
Fred Drake94ffbb72004-04-08 19:44:31 +00001128\subsubsection{Configuration file format%
1129 \label{logging-config-fileformat}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001130
Fred Drake6b3b0462004-04-09 18:26:40 +00001131The configuration file format understood by \function{fileConfig()} is
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001132based on ConfigParser functionality. The file must contain sections
1133called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
1134which identify by name the entities of each type which are defined in
1135the file. For each such entity, there is a separate section which
1136identified how that entity is configured. Thus, for a logger named
1137\code{log01} in the \code{[loggers]} section, the relevant
1138configuration details are held in a section
1139\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
1140the \code{[handlers]} section will have its configuration held in a
1141section called \code{[handler_hand01]}, while a formatter called
1142\code{form01} in the \code{[formatters]} section will have its
1143configuration specified in a section called
1144\code{[formatter_form01]}. The root logger configuration must be
1145specified in a section called \code{[logger_root]}.
1146
1147Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001148
1149\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001150[loggers]
1151keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +00001152
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001153[handlers]
1154keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1155
1156[formatters]
1157keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +00001158\end{verbatim}
1159
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001160The root logger must specify a level and a list of handlers. An
1161example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001162
1163\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001164[logger_root]
1165level=NOTSET
1166handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +00001167\end{verbatim}
1168
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001169The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1170ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1171\code{NOTSET} means that all messages will be logged. Level values are
1172\function{eval()}uated in the context of the \code{logging} package's
1173namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +00001174
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001175The \code{handlers} entry is a comma-separated list of handler names,
1176which must appear in the \code{[handlers]} section. These names must
1177appear in the \code{[handlers]} section and have corresponding
1178sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +00001179
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001180For loggers other than the root logger, some additional information is
1181required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +00001182
1183\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001184[logger_parser]
1185level=DEBUG
1186handlers=hand01
1187propagate=1
1188qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001189\end{verbatim}
1190
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001191The \code{level} and \code{handlers} entries are interpreted as for
1192the root logger, except that if a non-root logger's level is specified
1193as \code{NOTSET}, the system consults loggers higher up the hierarchy
1194to determine the effective level of the logger. The \code{propagate}
1195entry is set to 1 to indicate that messages must propagate to handlers
1196higher up the logger hierarchy from this logger, or 0 to indicate that
1197messages are \strong{not} propagated to handlers up the hierarchy. The
1198\code{qualname} entry is the hierarchical channel name of the logger,
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001199that is to say the name used by the application to get the logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001200
1201Sections which specify handler configuration are exemplified by the
1202following.
1203
Skip Montanaro649698f2002-11-14 03:57:19 +00001204\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001205[handler_hand01]
1206class=StreamHandler
1207level=NOTSET
1208formatter=form01
1209args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001210\end{verbatim}
1211
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001212The \code{class} entry indicates the handler's class (as determined by
1213\function{eval()} in the \code{logging} package's namespace). The
1214\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1215to mean "log everything".
1216
1217The \code{formatter} entry indicates the key name of the formatter for
1218this handler. If blank, a default formatter
1219(\code{logging._defaultFormatter}) is used. If a name is specified, it
1220must appear in the \code{[formatters]} section and have a
1221corresponding section in the configuration file.
1222
1223The \code{args} entry, when \function{eval()}uated in the context of
1224the \code{logging} package's namespace, is the list of arguments to
1225the constructor for the handler class. Refer to the constructors for
1226the relevant handlers, or to the examples below, to see how typical
1227entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001228
1229\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001230[handler_hand02]
1231class=FileHandler
1232level=DEBUG
1233formatter=form02
1234args=('python.log', 'w')
1235
1236[handler_hand03]
1237class=handlers.SocketHandler
1238level=INFO
1239formatter=form03
1240args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1241
1242[handler_hand04]
1243class=handlers.DatagramHandler
1244level=WARN
1245formatter=form04
1246args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1247
1248[handler_hand05]
1249class=handlers.SysLogHandler
1250level=ERROR
1251formatter=form05
1252args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1253
1254[handler_hand06]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001255class=handlers.NTEventLogHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001256level=CRITICAL
1257formatter=form06
1258args=('Python Application', '', 'Application')
1259
1260[handler_hand07]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001261class=handlers.SMTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001262level=WARN
1263formatter=form07
1264args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1265
1266[handler_hand08]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001267class=handlers.MemoryHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001268level=NOTSET
1269formatter=form08
1270target=
1271args=(10, ERROR)
1272
1273[handler_hand09]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001274class=handlers.HTTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001275level=NOTSET
1276formatter=form09
1277args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001278\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001279
1280Sections which specify formatter configuration are typified by the following.
1281
1282\begin{verbatim}
1283[formatter_form01]
1284format=F1 %(asctime)s %(levelname)s %(message)s
1285datefmt=
1286\end{verbatim}
1287
1288The \code{format} entry is the overall format string, and the
1289\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1290string. If empty, the package substitutes ISO8601 format date/times, which
1291is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1292The ISO8601 format also specifies milliseconds, which are appended to the
1293result of using the above format string, with a comma separator. An example
1294time in ISO8601 format is \code{2003-01-23 00:29:50,411}.