blob: daaabceebe3c9e6219e9c64f26ece20608b41843 [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
137a logger which is the root logger of the hierarchy.
138
139All calls to this function with a given name return the same logger instance.
140This means that logger instances never need to be passed between different
141parts of an application.
Skip Montanaro649698f2002-11-14 03:57:19 +0000142\end{funcdesc}
143
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000144\begin{funcdesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
145Logs a message with level \constant{DEBUG} on the root logger.
146The \var{msg} is the message format string, and the \var{args} are the
147arguments which are merged into \var{msg}. The only keyword argument in
148\var{kwargs} which is inspected is \var{exc_info} which, if it does not
149evaluate as false, causes exception information (via a call to
Fred Drakec23e0192003-01-28 22:09:16 +0000150\function{sys.exc_info()}) to be added to the logging message.
Skip Montanaro649698f2002-11-14 03:57:19 +0000151\end{funcdesc}
152
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000153\begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
154Logs a message with level \constant{INFO} on the root logger.
155The arguments are interpreted as for \function{debug()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000156\end{funcdesc}
157
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000158\begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
159Logs a message with level \constant{WARNING} on the root logger.
160The arguments are interpreted as for \function{debug()}.
161\end{funcdesc}
162
163\begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
164Logs a message with level \constant{ERROR} on the root logger.
165The arguments are interpreted as for \function{debug()}.
166\end{funcdesc}
167
168\begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
169Logs a message with level \constant{CRITICAL} on the root logger.
170The arguments are interpreted as for \function{debug()}.
171\end{funcdesc}
172
173\begin{funcdesc}{exception}{msg\optional{, *args}}
174Logs a message with level \constant{ERROR} on the root logger.
175The arguments are interpreted as for \function{debug()}. Exception info
176is added to the logging message. This function should only be called
177from an exception handler.
178\end{funcdesc}
179
180\begin{funcdesc}{disable}{lvl}
181Provides an overriding level \var{lvl} for all loggers which takes
182precedence over the logger's own level. When the need arises to
183temporarily throttle logging output down across the whole application,
184this function can be useful.
185\end{funcdesc}
186
187\begin{funcdesc}{addLevelName}{lvl, levelName}
188Associates level \var{lvl} with text \var{levelName} in an internal
189dictionary, which is used to map numeric levels to a textual
190representation, for example when a \class{Formatter} formats a message.
191This function can also be used to define your own levels. The only
192constraints are that all levels used must be registered using this
193function, levels should be positive integers and they should increase
194in increasing order of severity.
195\end{funcdesc}
196
197\begin{funcdesc}{getLevelName}{lvl}
198Returns the textual representation of logging level \var{lvl}. If the
199level is one of the predefined levels \constant{CRITICAL},
200\constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG}
201then you get the corresponding string. If you have associated levels
202with names using \function{addLevelName()} then the name you have associated
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000203with \var{lvl} is returned. If a numeric value corresponding to one of the
204defined levels is passed in, the corresponding string representation is
205returned. Otherwise, the string "Level \%s" \% lvl is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000206\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000207
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000208\begin{funcdesc}{makeLogRecord}{attrdict}
209Creates and returns a new \class{LogRecord} instance whose attributes are
210defined by \var{attrdict}. This function is useful for taking a pickled
211\class{LogRecord} attribute dictionary, sent over a socket, and reconstituting
212it as a \class{LogRecord} instance at the receiving end.
213\end{funcdesc}
214
Skip Montanaro649698f2002-11-14 03:57:19 +0000215\begin{funcdesc}{basicConfig}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000216Does basic configuration for the logging system by creating a
217\class{StreamHandler} with a default \class{Formatter} and adding it to
218the root logger. The functions \function{debug()}, \function{info()},
219\function{warning()}, \function{error()} and \function{critical()} will call
220\function{basicConfig()} automatically if no handlers are defined for the
221root logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000222\end{funcdesc}
223
Skip Montanaro649698f2002-11-14 03:57:19 +0000224\begin{funcdesc}{shutdown}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000225Informs the logging system to perform an orderly shutdown by flushing and
226closing all handlers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000227\end{funcdesc}
228
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000229\begin{funcdesc}{setLoggerClass}{klass}
230Tells the logging system to use the class \var{klass} when instantiating a
231logger. The class should define \method{__init__()} such that only a name
232argument is required, and the \method{__init__()} should call
233\method{Logger.__init__()}. This function is typically called before any
234loggers are instantiated by applications which need to use custom logger
235behavior.
236\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000237
Fred Drake68e6d572003-01-28 22:02:35 +0000238
239\begin{seealso}
240 \seepep{282}{A Logging System}
241 {The proposal which described this feature for inclusion in
242 the Python standard library.}
Fred Drake11514792004-01-08 14:59:02 +0000243 \seelink{http://www.red-dove.com/python_logging.html}
244 {Original Python \module{logging} package}
245 {This is the original source for the \module{logging}
246 package. The version of the package available from this
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000247 site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x,
248 which do not include the \module{logging} package in the standard
Fred Drake11514792004-01-08 14:59:02 +0000249 library.}
Fred Drake68e6d572003-01-28 22:02:35 +0000250\end{seealso}
251
252
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000253\subsection{Logger Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000254
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000255Loggers have the following attributes and methods. Note that Loggers are
256never instantiated directly, but always through the module-level function
257\function{logging.getLogger(name)}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000258
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000259\begin{datadesc}{propagate}
260If this evaluates to false, logging messages are not passed by this
261logger or by child loggers to higher level (ancestor) loggers. The
262constructor sets this attribute to 1.
Skip Montanaro649698f2002-11-14 03:57:19 +0000263\end{datadesc}
264
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000265\begin{methoddesc}{setLevel}{lvl}
266Sets the threshold for this logger to \var{lvl}. Logging messages
267which are less severe than \var{lvl} will be ignored. When a logger is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000268created, the level is set to \constant{NOTSET} (which causes all messages
269to be processed in the root logger, or delegation to the parent in non-root
270loggers).
Skip Montanaro649698f2002-11-14 03:57:19 +0000271\end{methoddesc}
272
273\begin{methoddesc}{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000274Indicates if a message of severity \var{lvl} would be processed by
275this logger. This method checks first the module-level level set by
276\function{logging.disable(lvl)} and then the logger's effective level as
277determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000278\end{methoddesc}
279
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000280\begin{methoddesc}{getEffectiveLevel}{}
281Indicates the effective level for this logger. If a value other than
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000282\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000283Otherwise, the hierarchy is traversed towards the root until a value
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000284other than \constant{NOTSET} is found, and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000285\end{methoddesc}
286
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000287\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
288Logs a message with level \constant{DEBUG} on this logger.
289The \var{msg} is the message format string, and the \var{args} are the
290arguments which are merged into \var{msg}. The only keyword argument in
291\var{kwargs} which is inspected is \var{exc_info} which, if it does not
292evaluate as false, causes exception information (via a call to
Fred Drakec23e0192003-01-28 22:09:16 +0000293\function{sys.exc_info()}) to be added to the logging message.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000294\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000295
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000296\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
297Logs a message with level \constant{INFO} on this logger.
298The arguments are interpreted as for \method{debug()}.
299\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000300
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000301\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
302Logs a message with level \constant{WARNING} on this logger.
303The arguments are interpreted as for \method{debug()}.
304\end{methoddesc}
305
306\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
307Logs a message with level \constant{ERROR} on this logger.
308The arguments are interpreted as for \method{debug()}.
309\end{methoddesc}
310
311\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
312Logs a message with level \constant{CRITICAL} on this logger.
313The arguments are interpreted as for \method{debug()}.
314\end{methoddesc}
315
316\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
Vinay Sajip1cf56d02004-08-04 08:36:44 +0000317Logs a message with integer level \var{lvl} on this logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000318The other arguments are interpreted as for \method{debug()}.
319\end{methoddesc}
320
321\begin{methoddesc}{exception}{msg\optional{, *args}}
322Logs a message with level \constant{ERROR} on this logger.
323The arguments are interpreted as for \method{debug()}. Exception info
324is added to the logging message. This method should only be called
325from an exception handler.
326\end{methoddesc}
327
328\begin{methoddesc}{addFilter}{filt}
329Adds the specified filter \var{filt} to this logger.
330\end{methoddesc}
331
332\begin{methoddesc}{removeFilter}{filt}
333Removes the specified filter \var{filt} from this logger.
334\end{methoddesc}
335
336\begin{methoddesc}{filter}{record}
337Applies this logger's filters to the record and returns a true value if
338the record is to be processed.
339\end{methoddesc}
340
341\begin{methoddesc}{addHandler}{hdlr}
342Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000343\end{methoddesc}
344
345\begin{methoddesc}{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000346Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000347\end{methoddesc}
348
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000349\begin{methoddesc}{findCaller}{}
350Finds the caller's source filename and line number. Returns the filename
351and line number as a 2-element tuple.
Skip Montanaro649698f2002-11-14 03:57:19 +0000352\end{methoddesc}
353
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000354\begin{methoddesc}{handle}{record}
355Handles a record by passing it to all handlers associated with this logger
356and its ancestors (until a false value of \var{propagate} is found).
357This method is used for unpickled records received from a socket, as well
358as those created locally. Logger-level filtering is applied using
359\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000360\end{methoddesc}
361
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000362\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info}
363This is a factory method which can be overridden in subclasses to create
364specialized \class{LogRecord} instances.
Skip Montanaro649698f2002-11-14 03:57:19 +0000365\end{methoddesc}
366
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000367\subsection{Basic example \label{minimal-example}}
368
369The \module{logging} package provides a lot of flexibility, and its
370configuration can appear daunting. This section demonstrates that simple
371use of the logging package is possible.
372
373The simplest example shows logging to the console:
374
375\begin{verbatim}
376import logging
377
378logging.debug('A debug message')
379logging.info('Some information')
380logging.warning('A shot across the bows')
381\end{verbatim}
382
383If you run the above script, you'll see this:
384\begin{verbatim}
385WARNING:root:A shot across the bows
386\end{verbatim}
387
388Because no particular logger was specified, the system used the root logger.
389The debug and info messages didn't appear because by default, the root
390logger is configured to only handle messages with a severity of WARNING
391or above. The message format is also a configuration default, as is the output
392destination of the messages - \code{sys.stderr}. The severity level,
393the message format and destination can be easily changed, as shown in
394the example below:
395
396\begin{verbatim}
397import logging
398
399logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000400 format='%(asctime)s %(levelname)s %(message)s',
401 filename='/tmp/myapp.log',
402 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000403logging.debug('A debug message')
404logging.info('Some information')
405logging.warning('A shot across the bows')
406\end{verbatim}
407
408The \method{basicConfig()} method is used to change the configuration
409defaults, which results in output (written to \code{/tmp/myapp.log})
410which should look something like the following:
411
412\begin{verbatim}
4132004-07-02 13:00:08,743 DEBUG A debug message
4142004-07-02 13:00:08,743 INFO Some information
4152004-07-02 13:00:08,743 WARNING A shot across the bows
416\end{verbatim}
417
418This time, all messages with a severity of DEBUG or above were handled,
419and the format of the messages was also changed, and output went to the
420specified file rather than the console.
421
422Formatting uses standard Python string formatting - see section
423\ref{typesseq-strings}. The format string takes the following
424common specifiers. For a complete list of specifiers, consult the
425\class{Formatter} documentation.
426
427\begin{tableii}{l|l}{code}{Format}{Description}
428\lineii{\%(name)s} {Name of the logger (logging channel).}
429\lineii{\%(levelname)s}{Text logging level for the message
430 (\code{'DEBUG'}, \code{'INFO'},
431 \code{'WARNING'}, \code{'ERROR'},
432 \code{'CRITICAL'}).}
433\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
434 was created. By default this is of the form
435 ``2003-07-08 16:49:45,896'' (the numbers after the
436 comma are millisecond portion of the time).}
437\lineii{\%(message)s} {The logged message.}
438\end{tableii}
439
440To change the date/time format, you can pass an additional keyword parameter,
441\var{datefmt}, as in the following:
442
443\begin{verbatim}
444import logging
445
446logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000447 format='%(asctime)s %(levelname)-8s %(message)s',
448 datefmt='%a, %d %b %Y %H:%M:%S',
449 filename='/temp/myapp.log',
450 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000451logging.debug('A debug message')
452logging.info('Some information')
453logging.warning('A shot across the bows')
454\end{verbatim}
455
456which would result in output like
457
458\begin{verbatim}
459Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
460Fri, 02 Jul 2004 13:06:18 INFO Some information
461Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
462\end{verbatim}
463
464The date format string follows the requirements of \function{strftime()} -
465see the documentation for the \refmodule{time} module.
466
467If, instead of sending logging output to the console or a file, you'd rather
468use a file-like object which you have created separately, you can pass it
469to \function{basicConfig()} using the \var{stream} keyword argument. Note
470that if both \var{stream} and \var{filename} keyword arguments are passed,
471the \var{stream} argument is ignored.
472
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000473Of course, you can put variable information in your output. To do this,
474simply have the message be a format string and pass in additional arguments
475containing the variable information, as in the following example:
476
477\begin{verbatim}
478import logging
479
480logging.basicConfig(level=logging.DEBUG,
481 format='%(asctime)s %(levelname)-8s %(message)s',
482 datefmt='%a, %d %b %Y %H:%M:%S',
483 filename='/temp/myapp.log',
484 filemode='w')
485logging.error('Pack my box with %d dozen %s', 12, 'liquor jugs')
486\end{verbatim}
487
488which would result in
489
490\begin{verbatim}
491Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 12 dozen liquor jugs
492\end{verbatim}
493
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000494\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000495
Fred Drake68e6d572003-01-28 22:02:35 +0000496Handlers have the following attributes and methods. Note that
497\class{Handler} is never instantiated directly; this class acts as a
498base for more useful subclasses. However, the \method{__init__()}
499method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000500
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000501\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000502Initializes the \class{Handler} instance by setting its level, setting
503the list of filters to the empty list and creating a lock (using
Raymond Hettingerc75c3e02003-09-01 22:50:52 +0000504\method{createLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000505\end{methoddesc}
506
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000507\begin{methoddesc}{createLock}{}
508Initializes a thread lock which can be used to serialize access to
509underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000510\end{methoddesc}
511
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000512\begin{methoddesc}{acquire}{}
513Acquires the thread lock created with \method{createLock()}.
514\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000515
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000516\begin{methoddesc}{release}{}
517Releases the thread lock acquired with \method{acquire()}.
518\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000519
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000520\begin{methoddesc}{setLevel}{lvl}
521Sets the threshold for this handler to \var{lvl}. Logging messages which are
522less severe than \var{lvl} will be ignored. When a handler is created, the
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000523level is set to \constant{NOTSET} (which causes all messages to be processed).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000524\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000525
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000526\begin{methoddesc}{setFormatter}{form}
527Sets the \class{Formatter} for this handler to \var{form}.
528\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000529
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000530\begin{methoddesc}{addFilter}{filt}
531Adds the specified filter \var{filt} to this handler.
532\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000533
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000534\begin{methoddesc}{removeFilter}{filt}
535Removes the specified filter \var{filt} from this handler.
536\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000537
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000538\begin{methoddesc}{filter}{record}
539Applies this handler's filters to the record and returns a true value if
540the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000541\end{methoddesc}
542
543\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000544Ensure all logging output has been flushed. This version does
545nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000546\end{methoddesc}
547
Skip Montanaro649698f2002-11-14 03:57:19 +0000548\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000549Tidy up any resources used by the handler. This version does
550nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000551\end{methoddesc}
552
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000553\begin{methoddesc}{handle}{record}
554Conditionally emits the specified logging record, depending on
555filters which may have been added to the handler. Wraps the actual
556emission of the record with acquisition/release of the I/O thread
557lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000558\end{methoddesc}
559
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000560\begin{methoddesc}{handleError}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000561This method should be called from handlers when an exception is
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000562encountered during an \method{emit()} call. By default it does nothing,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000563which means that exceptions get silently ignored. This is what is
564mostly wanted for a logging system - most users will not care
565about errors in the logging system, they are more interested in
566application errors. You could, however, replace this with a custom
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000567handler if you wish. The specified record is the one which was being
568processed when the exception occurred.
Skip Montanaro649698f2002-11-14 03:57:19 +0000569\end{methoddesc}
570
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000571\begin{methoddesc}{format}{record}
572Do formatting for a record - if a formatter is set, use it.
573Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000574\end{methoddesc}
575
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000576\begin{methoddesc}{emit}{record}
577Do whatever it takes to actually log the specified logging record.
578This version is intended to be implemented by subclasses and so
579raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000580\end{methoddesc}
581
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000582\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000583
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000584The \class{StreamHandler} class sends logging output to streams such as
585\var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more
586precisely, any object which supports \method{write()} and \method{flush()}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000587methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000588
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000589\begin{classdesc}{StreamHandler}{\optional{strm}}
590Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
591specified, the instance will use it for logging output; otherwise,
592\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000593\end{classdesc}
594
595\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000596If a formatter is specified, it is used to format the record.
597The record is then written to the stream with a trailing newline.
598If exception information is present, it is formatted using
599\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000600\end{methoddesc}
601
602\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000603Flushes the stream by calling its \method{flush()} method. Note that
604the \method{close()} method is inherited from \class{Handler} and
605so does nothing, so an explicit \method{flush()} call may be needed
606at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000607\end{methoddesc}
608
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000609\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000610
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000611The \class{FileHandler} class sends logging output to a disk file.
Fred Drake68e6d572003-01-28 22:02:35 +0000612It inherits the output functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000613
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000614\begin{classdesc}{FileHandler}{filename\optional{, mode}}
615Returns a new instance of the \class{FileHandler} class. The specified
616file is opened and used as the stream for logging. If \var{mode} is
Fred Drake9a5b6a62003-07-08 15:38:40 +0000617not specified, \constant{'a'} is used. By default, the file grows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000618indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000619\end{classdesc}
620
621\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000622Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000623\end{methoddesc}
624
625\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000626Outputs the record to the file.
627\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000628
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000629\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000630
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000631The \class{RotatingFileHandler} class supports rotation of disk log files.
632
Fred Drake9a5b6a62003-07-08 15:38:40 +0000633\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{,
634 maxBytes\optional{, backupCount}}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000635Returns a new instance of the \class{RotatingFileHandler} class. The
636specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +0000637\var{mode} is not specified, \code{'a'} is used. By default, the
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000638file grows indefinitely.
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000639
640You can use the \var{maxBytes} and
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000641\var{backupCount} values to allow the file to \dfn{rollover} at a
642predetermined size. When the size is about to be exceeded, the file is
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000643closed and a new file is silently opened for output. Rollover occurs
644whenever the current log file is nearly \var{maxBytes} in length; if
645\var{maxBytes} is zero, rollover never occurs. If \var{backupCount}
646is non-zero, the system will save old log files by appending the
647extensions ".1", ".2" etc., to the filename. For example, with
648a \var{backupCount} of 5 and a base file name of
649\file{app.log}, you would get \file{app.log},
650\file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being
651written to is always \file{app.log}. When this file is filled, it is
652closed and renamed to \file{app.log.1}, and if files \file{app.log.1},
653\file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2},
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000654\file{app.log.3} etc. respectively.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000655\end{classdesc}
656
657\begin{methoddesc}{doRollover}{}
658Does a rollover, as described above.
659\end{methoddesc}
660
661\begin{methoddesc}{emit}{record}
662Outputs the record to the file, catering for rollover as described
663in \method{setRollover()}.
664\end{methoddesc}
665
666\subsubsection{SocketHandler}
667
668The \class{SocketHandler} class sends logging output to a network
669socket. The base class uses a TCP socket.
670
671\begin{classdesc}{SocketHandler}{host, port}
672Returns a new instance of the \class{SocketHandler} class intended to
673communicate with a remote machine whose address is given by \var{host}
674and \var{port}.
675\end{classdesc}
676
677\begin{methoddesc}{close}{}
678Closes the socket.
679\end{methoddesc}
680
681\begin{methoddesc}{handleError}{}
682\end{methoddesc}
683
684\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000685Pickles the record's attribute dictionary and writes it to the socket in
686binary format. If there is an error with the socket, silently drops the
687packet. If the connection was previously lost, re-establishes the connection.
Fred Drake6b3b0462004-04-09 18:26:40 +0000688To unpickle the record at the receiving end into a \class{LogRecord}, use the
689\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000690\end{methoddesc}
691
692\begin{methoddesc}{handleError}{}
693Handles an error which has occurred during \method{emit()}. The
694most likely cause is a lost connection. Closes the socket so that
695we can retry on the next event.
696\end{methoddesc}
697
698\begin{methoddesc}{makeSocket}{}
699This is a factory method which allows subclasses to define the precise
700type of socket they want. The default implementation creates a TCP
701socket (\constant{socket.SOCK_STREAM}).
702\end{methoddesc}
703
704\begin{methoddesc}{makePickle}{record}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000705Pickles the record's attribute dictionary in binary format with a length
706prefix, and returns it ready for transmission across the socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000707\end{methoddesc}
708
709\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000710Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000711for partial sends which can happen when the network is busy.
712\end{methoddesc}
713
714\subsubsection{DatagramHandler}
715
716The \class{DatagramHandler} class inherits from \class{SocketHandler}
717to support sending logging messages over UDP sockets.
718
719\begin{classdesc}{DatagramHandler}{host, port}
720Returns a new instance of the \class{DatagramHandler} class intended to
721communicate with a remote machine whose address is given by \var{host}
722and \var{port}.
723\end{classdesc}
724
725\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000726Pickles the record's attribute dictionary and writes it to the socket in
727binary format. If there is an error with the socket, silently drops the
728packet.
Fred Drake6b3b0462004-04-09 18:26:40 +0000729To unpickle the record at the receiving end into a \class{LogRecord}, use the
730\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000731\end{methoddesc}
732
733\begin{methoddesc}{makeSocket}{}
734The factory method of \class{SocketHandler} is here overridden to create
735a UDP socket (\constant{socket.SOCK_DGRAM}).
736\end{methoddesc}
737
738\begin{methoddesc}{send}{s}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000739Send a pickled string to a socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000740\end{methoddesc}
741
742\subsubsection{SysLogHandler}
743
744The \class{SysLogHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000745remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000746
747\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
748Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +0000749communicate with a remote \UNIX{} machine whose address is given by
750\var{address} in the form of a \code{(\var{host}, \var{port})}
751tuple. If \var{address} is not specified, \code{('localhost', 514)} is
752used. The address is used to open a UDP socket. If \var{facility} is
753not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000754\end{classdesc}
755
756\begin{methoddesc}{close}{}
757Closes the socket to the remote host.
758\end{methoddesc}
759
760\begin{methoddesc}{emit}{record}
761The record is formatted, and then sent to the syslog server. If
762exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +0000763\end{methoddesc}
764
765\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000766Encodes the facility and priority into an integer. You can pass in strings
767or integers - if strings are passed, internal mapping dictionaries are used
768to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000769\end{methoddesc}
770
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000771\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000772
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000773The \class{NTEventLogHandler} class supports sending logging messages
774to a local Windows NT, Windows 2000 or Windows XP event log. Before
775you can use it, you need Mark Hammond's Win32 extensions for Python
776installed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000777
Fred Drake9a5b6a62003-07-08 15:38:40 +0000778\begin{classdesc}{NTEventLogHandler}{appname\optional{,
779 dllname\optional{, logtype}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000780Returns a new instance of the \class{NTEventLogHandler} class. The
781\var{appname} is used to define the application name as it appears in the
782event log. An appropriate registry entry is created using this name.
783The \var{dllname} should give the fully qualified pathname of a .dll or .exe
784which contains message definitions to hold in the log (if not specified,
Fred Drake9a5b6a62003-07-08 15:38:40 +0000785\code{'win32service.pyd'} is used - this is installed with the Win32
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000786extensions and contains some basic placeholder message definitions.
787Note that use of these placeholders will make your event logs big, as the
788entire message source is held in the log. If you want slimmer logs, you have
789to pass in the name of your own .dll or .exe which contains the message
790definitions you want to use in the event log). The \var{logtype} is one of
Fred Drake9a5b6a62003-07-08 15:38:40 +0000791\code{'Application'}, \code{'System'} or \code{'Security'}, and
792defaults to \code{'Application'}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000793\end{classdesc}
794
795\begin{methoddesc}{close}{}
796At this point, you can remove the application name from the registry as a
797source of event log entries. However, if you do this, you will not be able
798to see the events as you intended in the Event Log Viewer - it needs to be
799able to access the registry to get the .dll name. The current version does
800not do this (in fact it doesn't do anything).
801\end{methoddesc}
802
803\begin{methoddesc}{emit}{record}
804Determines the message ID, event category and event type, and then logs the
805message in the NT event log.
806\end{methoddesc}
807
808\begin{methoddesc}{getEventCategory}{record}
809Returns the event category for the record. Override this if you
810want to specify your own categories. This version returns 0.
811\end{methoddesc}
812
813\begin{methoddesc}{getEventType}{record}
814Returns the event type for the record. Override this if you want
815to specify your own types. This version does a mapping using the
816handler's typemap attribute, which is set up in \method{__init__()}
817to a dictionary which contains mappings for \constant{DEBUG},
818\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
819\constant{CRITICAL}. If you are using your own levels, you will either need
820to override this method or place a suitable dictionary in the
821handler's \var{typemap} attribute.
822\end{methoddesc}
823
824\begin{methoddesc}{getMessageID}{record}
825Returns the message ID for the record. If you are using your
826own messages, you could do this by having the \var{msg} passed to the
827logger being an ID rather than a format string. Then, in here,
828you could use a dictionary lookup to get the message ID. This
829version returns 1, which is the base message ID in
Fred Drake9a5b6a62003-07-08 15:38:40 +0000830\file{win32service.pyd}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000831\end{methoddesc}
832
833\subsubsection{SMTPHandler}
834
835The \class{SMTPHandler} class supports sending logging messages to an email
836address via SMTP.
837
838\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
839Returns a new instance of the \class{SMTPHandler} class. The
840instance is initialized with the from and to addresses and subject
841line of the email. The \var{toaddrs} should be a list of strings without
842domain names (That's what the \var{mailhost} is for). To specify a
843non-standard SMTP port, use the (host, port) tuple format for the
844\var{mailhost} argument. If you use a string, the standard SMTP port
845is used.
846\end{classdesc}
847
848\begin{methoddesc}{emit}{record}
849Formats the record and sends it to the specified addressees.
850\end{methoddesc}
851
852\begin{methoddesc}{getSubject}{record}
853If you want to specify a subject line which is record-dependent,
854override this method.
855\end{methoddesc}
856
857\subsubsection{MemoryHandler}
858
859The \class{MemoryHandler} supports buffering of logging records in memory,
860periodically flushing them to a \dfn{target} handler. Flushing occurs
861whenever the buffer is full, or when an event of a certain severity or
862greater is seen.
863
864\class{MemoryHandler} is a subclass of the more general
865\class{BufferingHandler}, which is an abstract class. This buffers logging
866records in memory. Whenever each record is added to the buffer, a
867check is made by calling \method{shouldFlush()} to see if the buffer
868should be flushed. If it should, then \method{flush()} is expected to
869do the needful.
870
871\begin{classdesc}{BufferingHandler}{capacity}
872Initializes the handler with a buffer of the specified capacity.
873\end{classdesc}
874
875\begin{methoddesc}{emit}{record}
876Appends the record to the buffer. If \method{shouldFlush()} returns true,
877calls \method{flush()} to process the buffer.
878\end{methoddesc}
879
880\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000881You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000882just zaps the buffer to empty.
883\end{methoddesc}
884
885\begin{methoddesc}{shouldFlush}{record}
886Returns true if the buffer is up to capacity. This method can be
887overridden to implement custom flushing strategies.
888\end{methoddesc}
889
890\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000891\optional{, target}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000892Returns a new instance of the \class{MemoryHandler} class. The
893instance is initialized with a buffer size of \var{capacity}. If
894\var{flushLevel} is not specified, \constant{ERROR} is used. If no
895\var{target} is specified, the target will need to be set using
896\method{setTarget()} before this handler does anything useful.
897\end{classdesc}
898
899\begin{methoddesc}{close}{}
900Calls \method{flush()}, sets the target to \constant{None} and
901clears the buffer.
902\end{methoddesc}
903
904\begin{methoddesc}{flush}{}
905For a \class{MemoryHandler}, flushing means just sending the buffered
906records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000907different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000908\end{methoddesc}
909
910\begin{methoddesc}{setTarget}{target}
911Sets the target handler for this handler.
912\end{methoddesc}
913
914\begin{methoddesc}{shouldFlush}{record}
915Checks for buffer full or a record at the \var{flushLevel} or higher.
916\end{methoddesc}
917
918\subsubsection{HTTPHandler}
919
920The \class{HTTPHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000921Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000922
923\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
924Returns a new instance of the \class{HTTPHandler} class. The
925instance is initialized with a host address, url and HTTP method.
Fred Drake68e6d572003-01-28 22:02:35 +0000926If no \var{method} is specified, \samp{GET} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000927\end{classdesc}
928
929\begin{methoddesc}{emit}{record}
930Sends the record to the Web server as an URL-encoded dictionary.
931\end{methoddesc}
932
933\subsection{Formatter Objects}
934
935\class{Formatter}s have the following attributes and methods. They are
936responsible for converting a \class{LogRecord} to (usually) a string
937which can be interpreted by either a human or an external system. The
938base
939\class{Formatter} allows a formatting string to be specified. If none is
Fred Drake8efc74d2004-04-15 06:18:48 +0000940supplied, the default value of \code{'\%(message)s'} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000941
942A Formatter can be initialized with a format string which makes use of
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000943knowledge of the \class{LogRecord} attributes - such as the default value
944mentioned above making use of the fact that the user's message and
Fred Drake6b3b0462004-04-09 18:26:40 +0000945arguments are pre-formatted into a \class{LogRecord}'s \var{message}
Anthony Baxtera6b7d342003-07-08 08:40:20 +0000946attribute. This format string contains standard python \%-style
947mapping keys. See section \ref{typesseq-strings}, ``String Formatting
948Operations,'' for more information on string formatting.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000949
Fred Drake6b3b0462004-04-09 18:26:40 +0000950Currently, the useful mapping keys in a \class{LogRecord} are:
Anthony Baxtera6b7d342003-07-08 08:40:20 +0000951
Fred Drake9a5b6a62003-07-08 15:38:40 +0000952\begin{tableii}{l|l}{code}{Format}{Description}
953\lineii{\%(name)s} {Name of the logger (logging channel).}
954\lineii{\%(levelno)s} {Numeric logging level for the message
955 (\constant{DEBUG}, \constant{INFO},
956 \constant{WARNING}, \constant{ERROR},
957 \constant{CRITICAL}).}
958\lineii{\%(levelname)s}{Text logging level for the message
959 (\code{'DEBUG'}, \code{'INFO'},
960 \code{'WARNING'}, \code{'ERROR'},
961 \code{'CRITICAL'}).}
962\lineii{\%(pathname)s} {Full pathname of the source file where the logging
963 call was issued (if available).}
964\lineii{\%(filename)s} {Filename portion of pathname.}
965\lineii{\%(module)s} {Module (name portion of filename).}
966\lineii{\%(lineno)d} {Source line number where the logging call was issued
967 (if available).}
Fred Drake6b3b0462004-04-09 18:26:40 +0000968\lineii{\%(created)f} {Time when the \class{LogRecord} was created (as
Fred Drake9a5b6a62003-07-08 15:38:40 +0000969 returned by \function{time.time()}).}
Fred Drake6b3b0462004-04-09 18:26:40 +0000970\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
971 was created. By default this is of the form
Fred Drake9a5b6a62003-07-08 15:38:40 +0000972 ``2003-07-08 16:49:45,896'' (the numbers after the
973 comma are millisecond portion of the time).}
974\lineii{\%(msecs)d} {Millisecond portion of the time when the
975 \class{LogRecord} was created.}
976\lineii{\%(thread)d} {Thread ID (if available).}
977\lineii{\%(process)d} {Process ID (if available).}
978\lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}
Anthony Baxtera6b7d342003-07-08 08:40:20 +0000979\end{tableii}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000980
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000981\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
982Returns a new instance of the \class{Formatter} class. The
983instance is initialized with a format string for the message as a whole,
984as well as a format string for the date/time portion of a message. If
Neal Norwitzdd3afa72003-07-08 16:26:34 +0000985no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000986is specified, the ISO8601 date format is used.
987\end{classdesc}
988
989\begin{methoddesc}{format}{record}
990The record's attribute dictionary is used as the operand to a
991string formatting operation. Returns the resulting string.
992Before formatting the dictionary, a couple of preparatory steps
993are carried out. The \var{message} attribute of the record is computed
994using \var{msg} \% \var{args}. If the formatting string contains
Fred Drake9a5b6a62003-07-08 15:38:40 +0000995\code{'(asctime)'}, \method{formatTime()} is called to format the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000996event time. If there is exception information, it is formatted using
997\method{formatException()} and appended to the message.
998\end{methoddesc}
999
1000\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
1001This method should be called from \method{format()} by a formatter which
1002wants to make use of a formatted time. This method can be overridden
1003in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001004basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +00001005it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001006record. Otherwise, the ISO8601 format is used. The resulting
1007string is returned.
1008\end{methoddesc}
1009
1010\begin{methoddesc}{formatException}{exc_info}
1011Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +00001012as returned by \function{sys.exc_info()}) as a string. This default
1013implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001014The resulting string is returned.
1015\end{methoddesc}
1016
1017\subsection{Filter Objects}
1018
1019\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
1020more sophisticated filtering than is provided by levels. The base filter
1021class only allows events which are below a certain point in the logger
1022hierarchy. For example, a filter initialized with "A.B" will allow events
1023logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
1024"B.A.B" etc. If initialized with the empty string, all events are passed.
1025
1026\begin{classdesc}{Filter}{\optional{name}}
1027Returns an instance of the \class{Filter} class. If \var{name} is specified,
1028it names a logger which, together with its children, will have its events
1029allowed through the filter. If no name is specified, allows every event.
1030\end{classdesc}
1031
1032\begin{methoddesc}{filter}{record}
1033Is the specified record to be logged? Returns zero for no, nonzero for
1034yes. If deemed appropriate, the record may be modified in-place by this
1035method.
1036\end{methoddesc}
1037
1038\subsection{LogRecord Objects}
1039
Fred Drake6b3b0462004-04-09 18:26:40 +00001040\class{LogRecord} instances are created every time something is logged. They
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001041contain all the information pertinent to the event being logged. The
1042main information passed in is in msg and args, which are combined
1043using msg \% args to create the message field of the record. The record
1044also includes information such as when the record was created, the
1045source line where the logging call was made, and any exception
1046information to be logged.
1047
Fred Drake6b3b0462004-04-09 18:26:40 +00001048\class{LogRecord} has no methods; it's just a repository for
1049information about the logging event. The only reason it's a class
1050rather than a dictionary is to facilitate extension.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001051
1052\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001053 exc_info}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001054Returns an instance of \class{LogRecord} initialized with interesting
1055information. The \var{name} is the logger name; \var{lvl} is the
1056numeric level; \var{pathname} is the absolute pathname of the source
1057file in which the logging call was made; \var{lineno} is the line
1058number in that file where the logging call is found; \var{msg} is the
1059user-supplied message (a format string); \var{args} is the tuple
1060which, together with \var{msg}, makes up the user message; and
1061\var{exc_info} is the exception tuple obtained by calling
1062\function{sys.exc_info() }(or \constant{None}, if no exception information
1063is available).
1064\end{classdesc}
1065
1066\subsection{Thread Safety}
1067
1068The logging module is intended to be thread-safe without any special work
1069needing to be done by its clients. It achieves this though using threading
1070locks; there is one lock to serialize access to the module's shared data,
1071and each handler also creates a lock to serialize access to its underlying
1072I/O.
1073
1074\subsection{Configuration}
1075
1076
Fred Drake94ffbb72004-04-08 19:44:31 +00001077\subsubsection{Configuration functions%
1078 \label{logging-config-api}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001079
Fred Drake9a5b6a62003-07-08 15:38:40 +00001080The following functions allow the logging module to be
1081configured. Before they can be used, you must import
1082\module{logging.config}. Their use is optional --- you can configure
1083the logging module entirely by making calls to the main API (defined
1084in \module{logging} itself) and defining handlers which are declared
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001085either in \module{logging} or \module{logging.handlers}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001086
1087\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
1088Reads the logging configuration from a ConfigParser-format file named
1089\var{fname}. This function can be called several times from an application,
1090allowing an end user the ability to select from various pre-canned
1091configurations (if the developer provides a mechanism to present the
1092choices and load the chosen configuration). Defaults to be passed to
1093ConfigParser can be specified in the \var{defaults} argument.
1094\end{funcdesc}
1095
1096\begin{funcdesc}{listen}{\optional{port}}
1097Starts up a socket server on the specified port, and listens for new
1098configurations. If no port is specified, the module's default
1099\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
1100will be sent as a file suitable for processing by \function{fileConfig()}.
1101Returns a \class{Thread} instance on which you can call \method{start()}
1102to start the server, and which you can \method{join()} when appropriate.
1103To stop the server, call \function{stopListening()}.
1104\end{funcdesc}
1105
1106\begin{funcdesc}{stopListening}{}
1107Stops the listening server which was created with a call to
1108\function{listen()}. This is typically called before calling \method{join()}
1109on the return value from \function{listen()}.
1110\end{funcdesc}
1111
Fred Drake94ffbb72004-04-08 19:44:31 +00001112\subsubsection{Configuration file format%
1113 \label{logging-config-fileformat}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001114
Fred Drake6b3b0462004-04-09 18:26:40 +00001115The configuration file format understood by \function{fileConfig()} is
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001116based on ConfigParser functionality. The file must contain sections
1117called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
1118which identify by name the entities of each type which are defined in
1119the file. For each such entity, there is a separate section which
1120identified how that entity is configured. Thus, for a logger named
1121\code{log01} in the \code{[loggers]} section, the relevant
1122configuration details are held in a section
1123\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
1124the \code{[handlers]} section will have its configuration held in a
1125section called \code{[handler_hand01]}, while a formatter called
1126\code{form01} in the \code{[formatters]} section will have its
1127configuration specified in a section called
1128\code{[formatter_form01]}. The root logger configuration must be
1129specified in a section called \code{[logger_root]}.
1130
1131Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001132
1133\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001134[loggers]
1135keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +00001136
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001137[handlers]
1138keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1139
1140[formatters]
1141keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +00001142\end{verbatim}
1143
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001144The root logger must specify a level and a list of handlers. An
1145example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001146
1147\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001148[logger_root]
1149level=NOTSET
1150handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +00001151\end{verbatim}
1152
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001153The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1154ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1155\code{NOTSET} means that all messages will be logged. Level values are
1156\function{eval()}uated in the context of the \code{logging} package's
1157namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +00001158
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001159The \code{handlers} entry is a comma-separated list of handler names,
1160which must appear in the \code{[handlers]} section. These names must
1161appear in the \code{[handlers]} section and have corresponding
1162sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +00001163
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001164For loggers other than the root logger, some additional information is
1165required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +00001166
1167\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001168[logger_parser]
1169level=DEBUG
1170handlers=hand01
1171propagate=1
1172qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001173\end{verbatim}
1174
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001175The \code{level} and \code{handlers} entries are interpreted as for
1176the root logger, except that if a non-root logger's level is specified
1177as \code{NOTSET}, the system consults loggers higher up the hierarchy
1178to determine the effective level of the logger. The \code{propagate}
1179entry is set to 1 to indicate that messages must propagate to handlers
1180higher up the logger hierarchy from this logger, or 0 to indicate that
1181messages are \strong{not} propagated to handlers up the hierarchy. The
1182\code{qualname} entry is the hierarchical channel name of the logger,
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001183that is to say the name used by the application to get the logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001184
1185Sections which specify handler configuration are exemplified by the
1186following.
1187
Skip Montanaro649698f2002-11-14 03:57:19 +00001188\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001189[handler_hand01]
1190class=StreamHandler
1191level=NOTSET
1192formatter=form01
1193args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001194\end{verbatim}
1195
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001196The \code{class} entry indicates the handler's class (as determined by
1197\function{eval()} in the \code{logging} package's namespace). The
1198\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1199to mean "log everything".
1200
1201The \code{formatter} entry indicates the key name of the formatter for
1202this handler. If blank, a default formatter
1203(\code{logging._defaultFormatter}) is used. If a name is specified, it
1204must appear in the \code{[formatters]} section and have a
1205corresponding section in the configuration file.
1206
1207The \code{args} entry, when \function{eval()}uated in the context of
1208the \code{logging} package's namespace, is the list of arguments to
1209the constructor for the handler class. Refer to the constructors for
1210the relevant handlers, or to the examples below, to see how typical
1211entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001212
1213\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001214[handler_hand02]
1215class=FileHandler
1216level=DEBUG
1217formatter=form02
1218args=('python.log', 'w')
1219
1220[handler_hand03]
1221class=handlers.SocketHandler
1222level=INFO
1223formatter=form03
1224args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1225
1226[handler_hand04]
1227class=handlers.DatagramHandler
1228level=WARN
1229formatter=form04
1230args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1231
1232[handler_hand05]
1233class=handlers.SysLogHandler
1234level=ERROR
1235formatter=form05
1236args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1237
1238[handler_hand06]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001239class=handlers.NTEventLogHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001240level=CRITICAL
1241formatter=form06
1242args=('Python Application', '', 'Application')
1243
1244[handler_hand07]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001245class=handlers.SMTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001246level=WARN
1247formatter=form07
1248args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1249
1250[handler_hand08]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001251class=handlers.MemoryHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001252level=NOTSET
1253formatter=form08
1254target=
1255args=(10, ERROR)
1256
1257[handler_hand09]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001258class=handlers.HTTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001259level=NOTSET
1260formatter=form09
1261args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001262\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001263
1264Sections which specify formatter configuration are typified by the following.
1265
1266\begin{verbatim}
1267[formatter_form01]
1268format=F1 %(asctime)s %(levelname)s %(message)s
1269datefmt=
1270\end{verbatim}
1271
1272The \code{format} entry is the overall format string, and the
1273\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1274string. If empty, the package substitutes ISO8601 format date/times, which
1275is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1276The ISO8601 format also specifies milliseconds, which are appended to the
1277result of using the above format string, with a comma separator. An example
1278time in ISO8601 format is \code{2003-01-23 00:29:50,411}.