blob: ecb3791dfb8f97129382619ba0c8c55062d99324 [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
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000147\begin{funcdesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
148Logs a message with level \constant{DEBUG} on the root logger.
149The \var{msg} is the message format string, and the \var{args} are the
150arguments which are merged into \var{msg}. The only keyword argument in
151\var{kwargs} which is inspected is \var{exc_info} which, if it does not
152evaluate as false, causes exception information (via a call to
Fred Drakec23e0192003-01-28 22:09:16 +0000153\function{sys.exc_info()}) to be added to the logging message.
Skip Montanaro649698f2002-11-14 03:57:19 +0000154\end{funcdesc}
155
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000156\begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
157Logs a message with level \constant{INFO} on the root logger.
158The arguments are interpreted as for \function{debug()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000159\end{funcdesc}
160
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000161\begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
162Logs a message with level \constant{WARNING} on the root logger.
163The arguments are interpreted as for \function{debug()}.
164\end{funcdesc}
165
166\begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
167Logs a message with level \constant{ERROR} on the root logger.
168The arguments are interpreted as for \function{debug()}.
169\end{funcdesc}
170
171\begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
172Logs a message with level \constant{CRITICAL} on the root logger.
173The arguments are interpreted as for \function{debug()}.
174\end{funcdesc}
175
176\begin{funcdesc}{exception}{msg\optional{, *args}}
177Logs a message with level \constant{ERROR} on the root logger.
178The arguments are interpreted as for \function{debug()}. Exception info
179is added to the logging message. This function should only be called
180from an exception handler.
181\end{funcdesc}
182
183\begin{funcdesc}{disable}{lvl}
184Provides an overriding level \var{lvl} for all loggers which takes
185precedence over the logger's own level. When the need arises to
186temporarily throttle logging output down across the whole application,
187this function can be useful.
188\end{funcdesc}
189
190\begin{funcdesc}{addLevelName}{lvl, levelName}
191Associates level \var{lvl} with text \var{levelName} in an internal
192dictionary, which is used to map numeric levels to a textual
193representation, for example when a \class{Formatter} formats a message.
194This function can also be used to define your own levels. The only
195constraints are that all levels used must be registered using this
196function, levels should be positive integers and they should increase
197in increasing order of severity.
198\end{funcdesc}
199
200\begin{funcdesc}{getLevelName}{lvl}
201Returns the textual representation of logging level \var{lvl}. If the
202level is one of the predefined levels \constant{CRITICAL},
203\constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG}
204then you get the corresponding string. If you have associated levels
205with names using \function{addLevelName()} then the name you have associated
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000206with \var{lvl} is returned. If a numeric value corresponding to one of the
207defined levels is passed in, the corresponding string representation is
208returned. Otherwise, the string "Level \%s" \% lvl is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000209\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000210
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000211\begin{funcdesc}{makeLogRecord}{attrdict}
212Creates and returns a new \class{LogRecord} instance whose attributes are
213defined by \var{attrdict}. This function is useful for taking a pickled
214\class{LogRecord} attribute dictionary, sent over a socket, and reconstituting
215it as a \class{LogRecord} instance at the receiving end.
216\end{funcdesc}
217
Skip Montanaro649698f2002-11-14 03:57:19 +0000218\begin{funcdesc}{basicConfig}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000219Does basic configuration for the logging system by creating a
220\class{StreamHandler} with a default \class{Formatter} and adding it to
221the root logger. The functions \function{debug()}, \function{info()},
222\function{warning()}, \function{error()} and \function{critical()} will call
223\function{basicConfig()} automatically if no handlers are defined for the
224root logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000225\end{funcdesc}
226
Skip Montanaro649698f2002-11-14 03:57:19 +0000227\begin{funcdesc}{shutdown}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000228Informs the logging system to perform an orderly shutdown by flushing and
229closing all handlers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000230\end{funcdesc}
231
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000232\begin{funcdesc}{setLoggerClass}{klass}
233Tells the logging system to use the class \var{klass} when instantiating a
234logger. The class should define \method{__init__()} such that only a name
235argument is required, and the \method{__init__()} should call
236\method{Logger.__init__()}. This function is typically called before any
237loggers are instantiated by applications which need to use custom logger
238behavior.
239\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000240
Fred Drake68e6d572003-01-28 22:02:35 +0000241
242\begin{seealso}
243 \seepep{282}{A Logging System}
244 {The proposal which described this feature for inclusion in
245 the Python standard library.}
Fred Drake11514792004-01-08 14:59:02 +0000246 \seelink{http://www.red-dove.com/python_logging.html}
247 {Original Python \module{logging} package}
248 {This is the original source for the \module{logging}
249 package. The version of the package available from this
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000250 site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x,
251 which do not include the \module{logging} package in the standard
Fred Drake11514792004-01-08 14:59:02 +0000252 library.}
Fred Drake68e6d572003-01-28 22:02:35 +0000253\end{seealso}
254
255
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000256\subsection{Logger Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000257
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000258Loggers have the following attributes and methods. Note that Loggers are
259never instantiated directly, but always through the module-level function
260\function{logging.getLogger(name)}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000261
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000262\begin{datadesc}{propagate}
263If this evaluates to false, logging messages are not passed by this
264logger or by child loggers to higher level (ancestor) loggers. The
265constructor sets this attribute to 1.
Skip Montanaro649698f2002-11-14 03:57:19 +0000266\end{datadesc}
267
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000268\begin{methoddesc}{setLevel}{lvl}
269Sets the threshold for this logger to \var{lvl}. Logging messages
270which are less severe than \var{lvl} will be ignored. When a logger is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000271created, the level is set to \constant{NOTSET} (which causes all messages
272to be processed in the root logger, or delegation to the parent in non-root
273loggers).
Skip Montanaro649698f2002-11-14 03:57:19 +0000274\end{methoddesc}
275
276\begin{methoddesc}{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000277Indicates if a message of severity \var{lvl} would be processed by
278this logger. This method checks first the module-level level set by
279\function{logging.disable(lvl)} and then the logger's effective level as
280determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000281\end{methoddesc}
282
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000283\begin{methoddesc}{getEffectiveLevel}{}
284Indicates the effective level for this logger. If a value other than
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000285\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000286Otherwise, the hierarchy is traversed towards the root until a value
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000287other than \constant{NOTSET} is found, and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000288\end{methoddesc}
289
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000290\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
291Logs a message with level \constant{DEBUG} on this logger.
292The \var{msg} is the message format string, and the \var{args} are the
293arguments which are merged into \var{msg}. The only keyword argument in
294\var{kwargs} which is inspected is \var{exc_info} which, if it does not
295evaluate as false, causes exception information (via a call to
Fred Drakec23e0192003-01-28 22:09:16 +0000296\function{sys.exc_info()}) to be added to the logging message.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000297\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000298
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000299\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
300Logs a message with level \constant{INFO} on this logger.
301The arguments are interpreted as for \method{debug()}.
302\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000303
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000304\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
305Logs a message with level \constant{WARNING} on this logger.
306The arguments are interpreted as for \method{debug()}.
307\end{methoddesc}
308
309\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
310Logs a message with level \constant{ERROR} on this logger.
311The arguments are interpreted as for \method{debug()}.
312\end{methoddesc}
313
314\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
315Logs a message with level \constant{CRITICAL} on this logger.
316The arguments are interpreted as for \method{debug()}.
317\end{methoddesc}
318
319\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
Vinay Sajip1cf56d02004-08-04 08:36:44 +0000320Logs a message with integer level \var{lvl} on this logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000321The other arguments are interpreted as for \method{debug()}.
322\end{methoddesc}
323
324\begin{methoddesc}{exception}{msg\optional{, *args}}
325Logs a message with level \constant{ERROR} on this logger.
326The arguments are interpreted as for \method{debug()}. Exception info
327is added to the logging message. This method should only be called
328from an exception handler.
329\end{methoddesc}
330
331\begin{methoddesc}{addFilter}{filt}
332Adds the specified filter \var{filt} to this logger.
333\end{methoddesc}
334
335\begin{methoddesc}{removeFilter}{filt}
336Removes the specified filter \var{filt} from this logger.
337\end{methoddesc}
338
339\begin{methoddesc}{filter}{record}
340Applies this logger's filters to the record and returns a true value if
341the record is to be processed.
342\end{methoddesc}
343
344\begin{methoddesc}{addHandler}{hdlr}
345Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000346\end{methoddesc}
347
348\begin{methoddesc}{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000349Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000350\end{methoddesc}
351
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000352\begin{methoddesc}{findCaller}{}
353Finds the caller's source filename and line number. Returns the filename
354and line number as a 2-element tuple.
Skip Montanaro649698f2002-11-14 03:57:19 +0000355\end{methoddesc}
356
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000357\begin{methoddesc}{handle}{record}
358Handles a record by passing it to all handlers associated with this logger
359and its ancestors (until a false value of \var{propagate} is found).
360This method is used for unpickled records received from a socket, as well
361as those created locally. Logger-level filtering is applied using
362\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000363\end{methoddesc}
364
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000365\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info}
366This is a factory method which can be overridden in subclasses to create
367specialized \class{LogRecord} instances.
Skip Montanaro649698f2002-11-14 03:57:19 +0000368\end{methoddesc}
369
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000370\subsection{Basic example \label{minimal-example}}
371
372The \module{logging} package provides a lot of flexibility, and its
373configuration can appear daunting. This section demonstrates that simple
374use of the logging package is possible.
375
376The simplest example shows logging to the console:
377
378\begin{verbatim}
379import logging
380
381logging.debug('A debug message')
382logging.info('Some information')
383logging.warning('A shot across the bows')
384\end{verbatim}
385
386If you run the above script, you'll see this:
387\begin{verbatim}
388WARNING:root:A shot across the bows
389\end{verbatim}
390
391Because no particular logger was specified, the system used the root logger.
392The debug and info messages didn't appear because by default, the root
393logger is configured to only handle messages with a severity of WARNING
394or above. The message format is also a configuration default, as is the output
395destination of the messages - \code{sys.stderr}. The severity level,
396the message format and destination can be easily changed, as shown in
397the example below:
398
399\begin{verbatim}
400import logging
401
402logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000403 format='%(asctime)s %(levelname)s %(message)s',
404 filename='/tmp/myapp.log',
405 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000406logging.debug('A debug message')
407logging.info('Some information')
408logging.warning('A shot across the bows')
409\end{verbatim}
410
411The \method{basicConfig()} method is used to change the configuration
412defaults, which results in output (written to \code{/tmp/myapp.log})
413which should look something like the following:
414
415\begin{verbatim}
4162004-07-02 13:00:08,743 DEBUG A debug message
4172004-07-02 13:00:08,743 INFO Some information
4182004-07-02 13:00:08,743 WARNING A shot across the bows
419\end{verbatim}
420
421This time, all messages with a severity of DEBUG or above were handled,
422and the format of the messages was also changed, and output went to the
423specified file rather than the console.
424
425Formatting uses standard Python string formatting - see section
426\ref{typesseq-strings}. The format string takes the following
427common specifiers. For a complete list of specifiers, consult the
428\class{Formatter} documentation.
429
430\begin{tableii}{l|l}{code}{Format}{Description}
431\lineii{\%(name)s} {Name of the logger (logging channel).}
432\lineii{\%(levelname)s}{Text logging level for the message
433 (\code{'DEBUG'}, \code{'INFO'},
434 \code{'WARNING'}, \code{'ERROR'},
435 \code{'CRITICAL'}).}
436\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
437 was created. By default this is of the form
438 ``2003-07-08 16:49:45,896'' (the numbers after the
439 comma are millisecond portion of the time).}
440\lineii{\%(message)s} {The logged message.}
441\end{tableii}
442
443To change the date/time format, you can pass an additional keyword parameter,
444\var{datefmt}, as in the following:
445
446\begin{verbatim}
447import logging
448
449logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000450 format='%(asctime)s %(levelname)-8s %(message)s',
451 datefmt='%a, %d %b %Y %H:%M:%S',
452 filename='/temp/myapp.log',
453 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000454logging.debug('A debug message')
455logging.info('Some information')
456logging.warning('A shot across the bows')
457\end{verbatim}
458
459which would result in output like
460
461\begin{verbatim}
462Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
463Fri, 02 Jul 2004 13:06:18 INFO Some information
464Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
465\end{verbatim}
466
467The date format string follows the requirements of \function{strftime()} -
468see the documentation for the \refmodule{time} module.
469
470If, instead of sending logging output to the console or a file, you'd rather
471use a file-like object which you have created separately, you can pass it
472to \function{basicConfig()} using the \var{stream} keyword argument. Note
473that if both \var{stream} and \var{filename} keyword arguments are passed,
474the \var{stream} argument is ignored.
475
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000476Of course, you can put variable information in your output. To do this,
477simply have the message be a format string and pass in additional arguments
478containing the variable information, as in the following example:
479
480\begin{verbatim}
481import logging
482
483logging.basicConfig(level=logging.DEBUG,
484 format='%(asctime)s %(levelname)-8s %(message)s',
485 datefmt='%a, %d %b %Y %H:%M:%S',
486 filename='/temp/myapp.log',
487 filemode='w')
488logging.error('Pack my box with %d dozen %s', 12, 'liquor jugs')
489\end{verbatim}
490
491which would result in
492
493\begin{verbatim}
494Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 12 dozen liquor jugs
495\end{verbatim}
496
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000497\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000498
Fred Drake68e6d572003-01-28 22:02:35 +0000499Handlers have the following attributes and methods. Note that
500\class{Handler} is never instantiated directly; this class acts as a
501base for more useful subclasses. However, the \method{__init__()}
502method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000503
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000504\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000505Initializes the \class{Handler} instance by setting its level, setting
506the list of filters to the empty list and creating a lock (using
Raymond Hettingerc75c3e02003-09-01 22:50:52 +0000507\method{createLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000508\end{methoddesc}
509
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000510\begin{methoddesc}{createLock}{}
511Initializes a thread lock which can be used to serialize access to
512underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000513\end{methoddesc}
514
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000515\begin{methoddesc}{acquire}{}
516Acquires the thread lock created with \method{createLock()}.
517\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000518
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000519\begin{methoddesc}{release}{}
520Releases the thread lock acquired with \method{acquire()}.
521\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000522
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000523\begin{methoddesc}{setLevel}{lvl}
524Sets the threshold for this handler to \var{lvl}. Logging messages which are
525less severe than \var{lvl} will be ignored. When a handler is created, the
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000526level is set to \constant{NOTSET} (which causes all messages to be processed).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000527\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000528
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000529\begin{methoddesc}{setFormatter}{form}
530Sets the \class{Formatter} for this handler to \var{form}.
531\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000532
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000533\begin{methoddesc}{addFilter}{filt}
534Adds the specified filter \var{filt} to this handler.
535\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000536
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000537\begin{methoddesc}{removeFilter}{filt}
538Removes the specified filter \var{filt} from this handler.
539\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000540
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000541\begin{methoddesc}{filter}{record}
542Applies this handler's filters to the record and returns a true value if
543the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000544\end{methoddesc}
545
546\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000547Ensure all logging output has been flushed. This version does
548nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000549\end{methoddesc}
550
Skip Montanaro649698f2002-11-14 03:57:19 +0000551\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000552Tidy up any resources used by the handler. This version does
553nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000554\end{methoddesc}
555
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000556\begin{methoddesc}{handle}{record}
557Conditionally emits the specified logging record, depending on
558filters which may have been added to the handler. Wraps the actual
559emission of the record with acquisition/release of the I/O thread
560lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000561\end{methoddesc}
562
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000563\begin{methoddesc}{handleError}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000564This method should be called from handlers when an exception is
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000565encountered during an \method{emit()} call. By default it does nothing,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000566which means that exceptions get silently ignored. This is what is
567mostly wanted for a logging system - most users will not care
568about errors in the logging system, they are more interested in
569application errors. You could, however, replace this with a custom
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000570handler if you wish. The specified record is the one which was being
571processed when the exception occurred.
Skip Montanaro649698f2002-11-14 03:57:19 +0000572\end{methoddesc}
573
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000574\begin{methoddesc}{format}{record}
575Do formatting for a record - if a formatter is set, use it.
576Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000577\end{methoddesc}
578
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000579\begin{methoddesc}{emit}{record}
580Do whatever it takes to actually log the specified logging record.
581This version is intended to be implemented by subclasses and so
582raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000583\end{methoddesc}
584
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000585\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000586
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000587The \class{StreamHandler} class sends logging output to streams such as
588\var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more
589precisely, any object which supports \method{write()} and \method{flush()}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000590methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000591
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000592\begin{classdesc}{StreamHandler}{\optional{strm}}
593Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
594specified, the instance will use it for logging output; otherwise,
595\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000596\end{classdesc}
597
598\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000599If a formatter is specified, it is used to format the record.
600The record is then written to the stream with a trailing newline.
601If exception information is present, it is formatted using
602\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000603\end{methoddesc}
604
605\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000606Flushes the stream by calling its \method{flush()} method. Note that
607the \method{close()} method is inherited from \class{Handler} and
608so does nothing, so an explicit \method{flush()} call may be needed
609at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000610\end{methoddesc}
611
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000612\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000613
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000614The \class{FileHandler} class sends logging output to a disk file.
Fred Drake68e6d572003-01-28 22:02:35 +0000615It inherits the output functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000616
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000617\begin{classdesc}{FileHandler}{filename\optional{, mode}}
618Returns a new instance of the \class{FileHandler} class. The specified
619file is opened and used as the stream for logging. If \var{mode} is
Fred Drake9a5b6a62003-07-08 15:38:40 +0000620not specified, \constant{'a'} is used. By default, the file grows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000621indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000622\end{classdesc}
623
624\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000625Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000626\end{methoddesc}
627
628\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000629Outputs the record to the file.
630\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000631
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000632\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000633
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000634The \class{RotatingFileHandler} class supports rotation of disk log files.
635
Fred Drake9a5b6a62003-07-08 15:38:40 +0000636\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{,
637 maxBytes\optional{, backupCount}}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000638Returns a new instance of the \class{RotatingFileHandler} class. The
639specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +0000640\var{mode} is not specified, \code{'a'} is used. By default, the
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000641file grows indefinitely.
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000642
643You can use the \var{maxBytes} and
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000644\var{backupCount} values to allow the file to \dfn{rollover} at a
645predetermined size. When the size is about to be exceeded, the file is
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000646closed and a new file is silently opened for output. Rollover occurs
647whenever the current log file is nearly \var{maxBytes} in length; if
648\var{maxBytes} is zero, rollover never occurs. If \var{backupCount}
649is non-zero, the system will save old log files by appending the
650extensions ".1", ".2" etc., to the filename. For example, with
651a \var{backupCount} of 5 and a base file name of
652\file{app.log}, you would get \file{app.log},
653\file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being
654written to is always \file{app.log}. When this file is filled, it is
655closed and renamed to \file{app.log.1}, and if files \file{app.log.1},
656\file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2},
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000657\file{app.log.3} etc. respectively.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000658\end{classdesc}
659
660\begin{methoddesc}{doRollover}{}
661Does a rollover, as described above.
662\end{methoddesc}
663
664\begin{methoddesc}{emit}{record}
665Outputs the record to the file, catering for rollover as described
666in \method{setRollover()}.
667\end{methoddesc}
668
669\subsubsection{SocketHandler}
670
671The \class{SocketHandler} class sends logging output to a network
672socket. The base class uses a TCP socket.
673
674\begin{classdesc}{SocketHandler}{host, port}
675Returns a new instance of the \class{SocketHandler} class intended to
676communicate with a remote machine whose address is given by \var{host}
677and \var{port}.
678\end{classdesc}
679
680\begin{methoddesc}{close}{}
681Closes the socket.
682\end{methoddesc}
683
684\begin{methoddesc}{handleError}{}
685\end{methoddesc}
686
687\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000688Pickles the record's attribute dictionary and writes it to the socket in
689binary format. If there is an error with the socket, silently drops the
690packet. If the connection was previously lost, re-establishes the connection.
Fred Drake6b3b0462004-04-09 18:26:40 +0000691To unpickle the record at the receiving end into a \class{LogRecord}, use the
692\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000693\end{methoddesc}
694
695\begin{methoddesc}{handleError}{}
696Handles an error which has occurred during \method{emit()}. The
697most likely cause is a lost connection. Closes the socket so that
698we can retry on the next event.
699\end{methoddesc}
700
701\begin{methoddesc}{makeSocket}{}
702This is a factory method which allows subclasses to define the precise
703type of socket they want. The default implementation creates a TCP
704socket (\constant{socket.SOCK_STREAM}).
705\end{methoddesc}
706
707\begin{methoddesc}{makePickle}{record}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000708Pickles the record's attribute dictionary in binary format with a length
709prefix, and returns it ready for transmission across the socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000710\end{methoddesc}
711
712\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000713Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000714for partial sends which can happen when the network is busy.
715\end{methoddesc}
716
717\subsubsection{DatagramHandler}
718
719The \class{DatagramHandler} class inherits from \class{SocketHandler}
720to support sending logging messages over UDP sockets.
721
722\begin{classdesc}{DatagramHandler}{host, port}
723Returns a new instance of the \class{DatagramHandler} class intended to
724communicate with a remote machine whose address is given by \var{host}
725and \var{port}.
726\end{classdesc}
727
728\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000729Pickles the record's attribute dictionary and writes it to the socket in
730binary format. If there is an error with the socket, silently drops the
731packet.
Fred Drake6b3b0462004-04-09 18:26:40 +0000732To unpickle the record at the receiving end into a \class{LogRecord}, use the
733\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000734\end{methoddesc}
735
736\begin{methoddesc}{makeSocket}{}
737The factory method of \class{SocketHandler} is here overridden to create
738a UDP socket (\constant{socket.SOCK_DGRAM}).
739\end{methoddesc}
740
741\begin{methoddesc}{send}{s}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000742Send a pickled string to a socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000743\end{methoddesc}
744
745\subsubsection{SysLogHandler}
746
747The \class{SysLogHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000748remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000749
750\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
751Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +0000752communicate with a remote \UNIX{} machine whose address is given by
753\var{address} in the form of a \code{(\var{host}, \var{port})}
754tuple. If \var{address} is not specified, \code{('localhost', 514)} is
755used. The address is used to open a UDP socket. If \var{facility} is
756not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000757\end{classdesc}
758
759\begin{methoddesc}{close}{}
760Closes the socket to the remote host.
761\end{methoddesc}
762
763\begin{methoddesc}{emit}{record}
764The record is formatted, and then sent to the syslog server. If
765exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +0000766\end{methoddesc}
767
768\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000769Encodes the facility and priority into an integer. You can pass in strings
770or integers - if strings are passed, internal mapping dictionaries are used
771to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000772\end{methoddesc}
773
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000774\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000775
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000776The \class{NTEventLogHandler} class supports sending logging messages
777to a local Windows NT, Windows 2000 or Windows XP event log. Before
778you can use it, you need Mark Hammond's Win32 extensions for Python
779installed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000780
Fred Drake9a5b6a62003-07-08 15:38:40 +0000781\begin{classdesc}{NTEventLogHandler}{appname\optional{,
782 dllname\optional{, logtype}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000783Returns a new instance of the \class{NTEventLogHandler} class. The
784\var{appname} is used to define the application name as it appears in the
785event log. An appropriate registry entry is created using this name.
786The \var{dllname} should give the fully qualified pathname of a .dll or .exe
787which contains message definitions to hold in the log (if not specified,
Fred Drake9a5b6a62003-07-08 15:38:40 +0000788\code{'win32service.pyd'} is used - this is installed with the Win32
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000789extensions and contains some basic placeholder message definitions.
790Note that use of these placeholders will make your event logs big, as the
791entire message source is held in the log. If you want slimmer logs, you have
792to pass in the name of your own .dll or .exe which contains the message
793definitions you want to use in the event log). The \var{logtype} is one of
Fred Drake9a5b6a62003-07-08 15:38:40 +0000794\code{'Application'}, \code{'System'} or \code{'Security'}, and
795defaults to \code{'Application'}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000796\end{classdesc}
797
798\begin{methoddesc}{close}{}
799At this point, you can remove the application name from the registry as a
800source of event log entries. However, if you do this, you will not be able
801to see the events as you intended in the Event Log Viewer - it needs to be
802able to access the registry to get the .dll name. The current version does
803not do this (in fact it doesn't do anything).
804\end{methoddesc}
805
806\begin{methoddesc}{emit}{record}
807Determines the message ID, event category and event type, and then logs the
808message in the NT event log.
809\end{methoddesc}
810
811\begin{methoddesc}{getEventCategory}{record}
812Returns the event category for the record. Override this if you
813want to specify your own categories. This version returns 0.
814\end{methoddesc}
815
816\begin{methoddesc}{getEventType}{record}
817Returns the event type for the record. Override this if you want
818to specify your own types. This version does a mapping using the
819handler's typemap attribute, which is set up in \method{__init__()}
820to a dictionary which contains mappings for \constant{DEBUG},
821\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
822\constant{CRITICAL}. If you are using your own levels, you will either need
823to override this method or place a suitable dictionary in the
824handler's \var{typemap} attribute.
825\end{methoddesc}
826
827\begin{methoddesc}{getMessageID}{record}
828Returns the message ID for the record. If you are using your
829own messages, you could do this by having the \var{msg} passed to the
830logger being an ID rather than a format string. Then, in here,
831you could use a dictionary lookup to get the message ID. This
832version returns 1, which is the base message ID in
Fred Drake9a5b6a62003-07-08 15:38:40 +0000833\file{win32service.pyd}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000834\end{methoddesc}
835
836\subsubsection{SMTPHandler}
837
838The \class{SMTPHandler} class supports sending logging messages to an email
839address via SMTP.
840
841\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
842Returns a new instance of the \class{SMTPHandler} class. The
843instance is initialized with the from and to addresses and subject
844line of the email. The \var{toaddrs} should be a list of strings without
845domain names (That's what the \var{mailhost} is for). To specify a
846non-standard SMTP port, use the (host, port) tuple format for the
847\var{mailhost} argument. If you use a string, the standard SMTP port
848is used.
849\end{classdesc}
850
851\begin{methoddesc}{emit}{record}
852Formats the record and sends it to the specified addressees.
853\end{methoddesc}
854
855\begin{methoddesc}{getSubject}{record}
856If you want to specify a subject line which is record-dependent,
857override this method.
858\end{methoddesc}
859
860\subsubsection{MemoryHandler}
861
862The \class{MemoryHandler} supports buffering of logging records in memory,
863periodically flushing them to a \dfn{target} handler. Flushing occurs
864whenever the buffer is full, or when an event of a certain severity or
865greater is seen.
866
867\class{MemoryHandler} is a subclass of the more general
868\class{BufferingHandler}, which is an abstract class. This buffers logging
869records in memory. Whenever each record is added to the buffer, a
870check is made by calling \method{shouldFlush()} to see if the buffer
871should be flushed. If it should, then \method{flush()} is expected to
872do the needful.
873
874\begin{classdesc}{BufferingHandler}{capacity}
875Initializes the handler with a buffer of the specified capacity.
876\end{classdesc}
877
878\begin{methoddesc}{emit}{record}
879Appends the record to the buffer. If \method{shouldFlush()} returns true,
880calls \method{flush()} to process the buffer.
881\end{methoddesc}
882
883\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000884You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000885just zaps the buffer to empty.
886\end{methoddesc}
887
888\begin{methoddesc}{shouldFlush}{record}
889Returns true if the buffer is up to capacity. This method can be
890overridden to implement custom flushing strategies.
891\end{methoddesc}
892
893\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000894\optional{, target}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000895Returns a new instance of the \class{MemoryHandler} class. The
896instance is initialized with a buffer size of \var{capacity}. If
897\var{flushLevel} is not specified, \constant{ERROR} is used. If no
898\var{target} is specified, the target will need to be set using
899\method{setTarget()} before this handler does anything useful.
900\end{classdesc}
901
902\begin{methoddesc}{close}{}
903Calls \method{flush()}, sets the target to \constant{None} and
904clears the buffer.
905\end{methoddesc}
906
907\begin{methoddesc}{flush}{}
908For a \class{MemoryHandler}, flushing means just sending the buffered
909records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000910different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000911\end{methoddesc}
912
913\begin{methoddesc}{setTarget}{target}
914Sets the target handler for this handler.
915\end{methoddesc}
916
917\begin{methoddesc}{shouldFlush}{record}
918Checks for buffer full or a record at the \var{flushLevel} or higher.
919\end{methoddesc}
920
921\subsubsection{HTTPHandler}
922
923The \class{HTTPHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000924Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000925
926\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
927Returns a new instance of the \class{HTTPHandler} class. The
928instance is initialized with a host address, url and HTTP method.
Fred Drake68e6d572003-01-28 22:02:35 +0000929If no \var{method} is specified, \samp{GET} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000930\end{classdesc}
931
932\begin{methoddesc}{emit}{record}
933Sends the record to the Web server as an URL-encoded dictionary.
934\end{methoddesc}
935
936\subsection{Formatter Objects}
937
938\class{Formatter}s have the following attributes and methods. They are
939responsible for converting a \class{LogRecord} to (usually) a string
940which can be interpreted by either a human or an external system. The
941base
942\class{Formatter} allows a formatting string to be specified. If none is
Fred Drake8efc74d2004-04-15 06:18:48 +0000943supplied, the default value of \code{'\%(message)s'} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000944
945A Formatter can be initialized with a format string which makes use of
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000946knowledge of the \class{LogRecord} attributes - such as the default value
947mentioned above making use of the fact that the user's message and
Fred Drake6b3b0462004-04-09 18:26:40 +0000948arguments are pre-formatted into a \class{LogRecord}'s \var{message}
Anthony Baxtera6b7d342003-07-08 08:40:20 +0000949attribute. This format string contains standard python \%-style
950mapping keys. See section \ref{typesseq-strings}, ``String Formatting
951Operations,'' for more information on string formatting.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000952
Fred Drake6b3b0462004-04-09 18:26:40 +0000953Currently, the useful mapping keys in a \class{LogRecord} are:
Anthony Baxtera6b7d342003-07-08 08:40:20 +0000954
Fred Drake9a5b6a62003-07-08 15:38:40 +0000955\begin{tableii}{l|l}{code}{Format}{Description}
956\lineii{\%(name)s} {Name of the logger (logging channel).}
957\lineii{\%(levelno)s} {Numeric logging level for the message
958 (\constant{DEBUG}, \constant{INFO},
959 \constant{WARNING}, \constant{ERROR},
960 \constant{CRITICAL}).}
961\lineii{\%(levelname)s}{Text logging level for the message
962 (\code{'DEBUG'}, \code{'INFO'},
963 \code{'WARNING'}, \code{'ERROR'},
964 \code{'CRITICAL'}).}
965\lineii{\%(pathname)s} {Full pathname of the source file where the logging
966 call was issued (if available).}
967\lineii{\%(filename)s} {Filename portion of pathname.}
968\lineii{\%(module)s} {Module (name portion of filename).}
969\lineii{\%(lineno)d} {Source line number where the logging call was issued
970 (if available).}
Fred Drake6b3b0462004-04-09 18:26:40 +0000971\lineii{\%(created)f} {Time when the \class{LogRecord} was created (as
Fred Drake9a5b6a62003-07-08 15:38:40 +0000972 returned by \function{time.time()}).}
Fred Drake6b3b0462004-04-09 18:26:40 +0000973\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
974 was created. By default this is of the form
Fred Drake9a5b6a62003-07-08 15:38:40 +0000975 ``2003-07-08 16:49:45,896'' (the numbers after the
976 comma are millisecond portion of the time).}
977\lineii{\%(msecs)d} {Millisecond portion of the time when the
978 \class{LogRecord} was created.}
979\lineii{\%(thread)d} {Thread ID (if available).}
980\lineii{\%(process)d} {Process ID (if available).}
981\lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}
Anthony Baxtera6b7d342003-07-08 08:40:20 +0000982\end{tableii}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000983
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000984\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
985Returns a new instance of the \class{Formatter} class. The
986instance is initialized with a format string for the message as a whole,
987as well as a format string for the date/time portion of a message. If
Neal Norwitzdd3afa72003-07-08 16:26:34 +0000988no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000989is specified, the ISO8601 date format is used.
990\end{classdesc}
991
992\begin{methoddesc}{format}{record}
993The record's attribute dictionary is used as the operand to a
994string formatting operation. Returns the resulting string.
995Before formatting the dictionary, a couple of preparatory steps
996are carried out. The \var{message} attribute of the record is computed
997using \var{msg} \% \var{args}. If the formatting string contains
Fred Drake9a5b6a62003-07-08 15:38:40 +0000998\code{'(asctime)'}, \method{formatTime()} is called to format the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000999event time. If there is exception information, it is formatted using
1000\method{formatException()} and appended to the message.
1001\end{methoddesc}
1002
1003\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
1004This method should be called from \method{format()} by a formatter which
1005wants to make use of a formatted time. This method can be overridden
1006in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001007basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +00001008it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001009record. Otherwise, the ISO8601 format is used. The resulting
1010string is returned.
1011\end{methoddesc}
1012
1013\begin{methoddesc}{formatException}{exc_info}
1014Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +00001015as returned by \function{sys.exc_info()}) as a string. This default
1016implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001017The resulting string is returned.
1018\end{methoddesc}
1019
1020\subsection{Filter Objects}
1021
1022\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
1023more sophisticated filtering than is provided by levels. The base filter
1024class only allows events which are below a certain point in the logger
1025hierarchy. For example, a filter initialized with "A.B" will allow events
1026logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
1027"B.A.B" etc. If initialized with the empty string, all events are passed.
1028
1029\begin{classdesc}{Filter}{\optional{name}}
1030Returns an instance of the \class{Filter} class. If \var{name} is specified,
1031it names a logger which, together with its children, will have its events
1032allowed through the filter. If no name is specified, allows every event.
1033\end{classdesc}
1034
1035\begin{methoddesc}{filter}{record}
1036Is the specified record to be logged? Returns zero for no, nonzero for
1037yes. If deemed appropriate, the record may be modified in-place by this
1038method.
1039\end{methoddesc}
1040
1041\subsection{LogRecord Objects}
1042
Fred Drake6b3b0462004-04-09 18:26:40 +00001043\class{LogRecord} instances are created every time something is logged. They
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001044contain all the information pertinent to the event being logged. The
1045main information passed in is in msg and args, which are combined
1046using msg \% args to create the message field of the record. The record
1047also includes information such as when the record was created, the
1048source line where the logging call was made, and any exception
1049information to be logged.
1050
Fred Drake6b3b0462004-04-09 18:26:40 +00001051\class{LogRecord} has no methods; it's just a repository for
1052information about the logging event. The only reason it's a class
1053rather than a dictionary is to facilitate extension.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001054
1055\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001056 exc_info}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001057Returns an instance of \class{LogRecord} initialized with interesting
1058information. The \var{name} is the logger name; \var{lvl} is the
1059numeric level; \var{pathname} is the absolute pathname of the source
1060file in which the logging call was made; \var{lineno} is the line
1061number in that file where the logging call is found; \var{msg} is the
1062user-supplied message (a format string); \var{args} is the tuple
1063which, together with \var{msg}, makes up the user message; and
1064\var{exc_info} is the exception tuple obtained by calling
1065\function{sys.exc_info() }(or \constant{None}, if no exception information
1066is available).
1067\end{classdesc}
1068
1069\subsection{Thread Safety}
1070
1071The logging module is intended to be thread-safe without any special work
1072needing to be done by its clients. It achieves this though using threading
1073locks; there is one lock to serialize access to the module's shared data,
1074and each handler also creates a lock to serialize access to its underlying
1075I/O.
1076
1077\subsection{Configuration}
1078
1079
Fred Drake94ffbb72004-04-08 19:44:31 +00001080\subsubsection{Configuration functions%
1081 \label{logging-config-api}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001082
Fred Drake9a5b6a62003-07-08 15:38:40 +00001083The following functions allow the logging module to be
1084configured. Before they can be used, you must import
1085\module{logging.config}. Their use is optional --- you can configure
1086the logging module entirely by making calls to the main API (defined
1087in \module{logging} itself) and defining handlers which are declared
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001088either in \module{logging} or \module{logging.handlers}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001089
1090\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
1091Reads the logging configuration from a ConfigParser-format file named
1092\var{fname}. This function can be called several times from an application,
1093allowing an end user the ability to select from various pre-canned
1094configurations (if the developer provides a mechanism to present the
1095choices and load the chosen configuration). Defaults to be passed to
1096ConfigParser can be specified in the \var{defaults} argument.
1097\end{funcdesc}
1098
1099\begin{funcdesc}{listen}{\optional{port}}
1100Starts up a socket server on the specified port, and listens for new
1101configurations. If no port is specified, the module's default
1102\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
1103will be sent as a file suitable for processing by \function{fileConfig()}.
1104Returns a \class{Thread} instance on which you can call \method{start()}
1105to start the server, and which you can \method{join()} when appropriate.
1106To stop the server, call \function{stopListening()}.
1107\end{funcdesc}
1108
1109\begin{funcdesc}{stopListening}{}
1110Stops the listening server which was created with a call to
1111\function{listen()}. This is typically called before calling \method{join()}
1112on the return value from \function{listen()}.
1113\end{funcdesc}
1114
Fred Drake94ffbb72004-04-08 19:44:31 +00001115\subsubsection{Configuration file format%
1116 \label{logging-config-fileformat}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001117
Fred Drake6b3b0462004-04-09 18:26:40 +00001118The configuration file format understood by \function{fileConfig()} is
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001119based on ConfigParser functionality. The file must contain sections
1120called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
1121which identify by name the entities of each type which are defined in
1122the file. For each such entity, there is a separate section which
1123identified how that entity is configured. Thus, for a logger named
1124\code{log01} in the \code{[loggers]} section, the relevant
1125configuration details are held in a section
1126\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
1127the \code{[handlers]} section will have its configuration held in a
1128section called \code{[handler_hand01]}, while a formatter called
1129\code{form01} in the \code{[formatters]} section will have its
1130configuration specified in a section called
1131\code{[formatter_form01]}. The root logger configuration must be
1132specified in a section called \code{[logger_root]}.
1133
1134Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001135
1136\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001137[loggers]
1138keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +00001139
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001140[handlers]
1141keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1142
1143[formatters]
1144keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +00001145\end{verbatim}
1146
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001147The root logger must specify a level and a list of handlers. An
1148example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001149
1150\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001151[logger_root]
1152level=NOTSET
1153handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +00001154\end{verbatim}
1155
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001156The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1157ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1158\code{NOTSET} means that all messages will be logged. Level values are
1159\function{eval()}uated in the context of the \code{logging} package's
1160namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +00001161
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001162The \code{handlers} entry is a comma-separated list of handler names,
1163which must appear in the \code{[handlers]} section. These names must
1164appear in the \code{[handlers]} section and have corresponding
1165sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +00001166
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001167For loggers other than the root logger, some additional information is
1168required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +00001169
1170\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001171[logger_parser]
1172level=DEBUG
1173handlers=hand01
1174propagate=1
1175qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001176\end{verbatim}
1177
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001178The \code{level} and \code{handlers} entries are interpreted as for
1179the root logger, except that if a non-root logger's level is specified
1180as \code{NOTSET}, the system consults loggers higher up the hierarchy
1181to determine the effective level of the logger. The \code{propagate}
1182entry is set to 1 to indicate that messages must propagate to handlers
1183higher up the logger hierarchy from this logger, or 0 to indicate that
1184messages are \strong{not} propagated to handlers up the hierarchy. The
1185\code{qualname} entry is the hierarchical channel name of the logger,
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001186that is to say the name used by the application to get the logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001187
1188Sections which specify handler configuration are exemplified by the
1189following.
1190
Skip Montanaro649698f2002-11-14 03:57:19 +00001191\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001192[handler_hand01]
1193class=StreamHandler
1194level=NOTSET
1195formatter=form01
1196args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001197\end{verbatim}
1198
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001199The \code{class} entry indicates the handler's class (as determined by
1200\function{eval()} in the \code{logging} package's namespace). The
1201\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1202to mean "log everything".
1203
1204The \code{formatter} entry indicates the key name of the formatter for
1205this handler. If blank, a default formatter
1206(\code{logging._defaultFormatter}) is used. If a name is specified, it
1207must appear in the \code{[formatters]} section and have a
1208corresponding section in the configuration file.
1209
1210The \code{args} entry, when \function{eval()}uated in the context of
1211the \code{logging} package's namespace, is the list of arguments to
1212the constructor for the handler class. Refer to the constructors for
1213the relevant handlers, or to the examples below, to see how typical
1214entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001215
1216\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001217[handler_hand02]
1218class=FileHandler
1219level=DEBUG
1220formatter=form02
1221args=('python.log', 'w')
1222
1223[handler_hand03]
1224class=handlers.SocketHandler
1225level=INFO
1226formatter=form03
1227args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1228
1229[handler_hand04]
1230class=handlers.DatagramHandler
1231level=WARN
1232formatter=form04
1233args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1234
1235[handler_hand05]
1236class=handlers.SysLogHandler
1237level=ERROR
1238formatter=form05
1239args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1240
1241[handler_hand06]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001242class=handlers.NTEventLogHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001243level=CRITICAL
1244formatter=form06
1245args=('Python Application', '', 'Application')
1246
1247[handler_hand07]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001248class=handlers.SMTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001249level=WARN
1250formatter=form07
1251args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1252
1253[handler_hand08]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001254class=handlers.MemoryHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001255level=NOTSET
1256formatter=form08
1257target=
1258args=(10, ERROR)
1259
1260[handler_hand09]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001261class=handlers.HTTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001262level=NOTSET
1263formatter=form09
1264args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001265\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001266
1267Sections which specify formatter configuration are typified by the following.
1268
1269\begin{verbatim}
1270[formatter_form01]
1271format=F1 %(asctime)s %(levelname)s %(message)s
1272datefmt=
1273\end{verbatim}
1274
1275The \code{format} entry is the overall format string, and the
1276\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1277string. If empty, the package substitutes ISO8601 format date/times, which
1278is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1279The ISO8601 format also specifies milliseconds, which are appended to the
1280result of using the above format string, with a comma separator. An example
1281time in ISO8601 format is \code{2003-01-23 00:29:50,411}.