blob: 6360a9acd5cb52190405e74c2d3eac0703079253 [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
Johannes Gijsbersf1643222004-11-07 16:11:35 +000080\item \class{BaseRotatingHandler} is tha base class for handlers that
81rotate log files at a certain point. It is not meant to be instantiated
Vinay Sajipedde4922004-11-11 13:54:48 +000082directly. Instead, use \class{RotatingFileHandler} or
83\class{TimedRotatingFileHandler}.
Johannes Gijsbersf1643222004-11-07 16:11:35 +000084
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000085\item \class{RotatingFileHandler} instances send error messages to disk
86files, with support for maximum log file sizes and log file rotation.
87
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +000088\item \class{TimedRotatingFileHandler} instances send error messages to
89disk files rotating the log file at certain timed intervals.
90
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000091\item \class{SocketHandler} instances send error messages to
92TCP/IP sockets.
93
94\item \class{DatagramHandler} instances send error messages to UDP
95sockets.
96
97\item \class{SMTPHandler} instances send error messages to a
98designated email address.
99
100\item \class{SysLogHandler} instances send error messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000101\UNIX{} syslog daemon, possibly on a remote machine.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000102
103\item \class{NTEventLogHandler} instances send error messages to a
104Windows NT/2000/XP event log.
105
106\item \class{MemoryHandler} instances send error messages to a
107buffer in memory, which is flushed whenever specific criteria are
108met.
109
110\item \class{HTTPHandler} instances send error messages to an
Fred Drake68e6d572003-01-28 22:02:35 +0000111HTTP server using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000112
113\end{enumerate}
114
115The \class{StreamHandler} and \class{FileHandler} classes are defined
116in the core logging package. The other handlers are defined in a sub-
117module, \module{logging.handlers}. (There is also another sub-module,
118\module{logging.config}, for configuration functionality.)
119
120Logged messages are formatted for presentation through instances of the
121\class{Formatter} class. They are initialized with a format string
122suitable for use with the \% operator and a dictionary.
123
124For formatting multiple messages in a batch, instances of
125\class{BufferingFormatter} can be used. In addition to the format string
126(which is applied to each message in the batch), there is provision for
127header and trailer format strings.
128
129When filtering based on logger level and/or handler level is not enough,
130instances of \class{Filter} can be added to both \class{Logger} and
Fred Drakec23e0192003-01-28 22:09:16 +0000131\class{Handler} instances (through their \method{addFilter()} method).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000132Before deciding to process a message further, both loggers and handlers
133consult all their filters for permission. If any filter returns a false
134value, the message is not processed further.
135
136The basic \class{Filter} functionality allows filtering by specific logger
137name. If this feature is used, messages sent to the named logger and its
138children are allowed through the filter, and all others dropped.
139
140In addition to the classes described above, there are a number of module-
141level functions.
142
143\begin{funcdesc}{getLogger}{\optional{name}}
144Return a logger with the specified name or, if no name is specified, return
Vinay Sajip17952b72004-08-31 10:21:51 +0000145a logger which is the root logger of the hierarchy. If specified, the name
146is typically a dot-separated hierarchical name like \var{"a"}, \var{"a.b"}
147or \var{"a.b.c.d"}. Choice of these names is entirely up to the developer
148who is using logging.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000149
150All calls to this function with a given name return the same logger instance.
151This means that logger instances never need to be passed between different
152parts of an application.
Skip Montanaro649698f2002-11-14 03:57:19 +0000153\end{funcdesc}
154
Vinay Sajipc6646c02004-09-22 12:55:16 +0000155\begin{funcdesc}{getLoggerClass}{}
156Return either the standard \class{Logger} class, or the last class passed to
157\function{setLoggerClass()}. This function may be called from within a new
158class definition, to ensure that installing a customised \class{Logger} class
159will not undo customisations already applied by other code. For example:
160
161\begin{verbatim}
162 class MyLogger(logging.getLoggerClass()):
163 # ... override behaviour here
164\end{verbatim}
165
166\end{funcdesc}
167
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000168\begin{funcdesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
169Logs a message with level \constant{DEBUG} on the root logger.
170The \var{msg} is the message format string, and the \var{args} are the
171arguments which are merged into \var{msg}. The only keyword argument in
172\var{kwargs} which is inspected is \var{exc_info} which, if it does not
Vinay Sajip1dc5b1e2004-10-03 19:10:05 +0000173evaluate as false, causes exception information to be added to the logging
174message. If an exception tuple (in the format returned by
175\function{sys.exc_info()}) is provided, it is used; otherwise,
176\function{sys.exc_info()} is called to get the exception information.
Skip Montanaro649698f2002-11-14 03:57:19 +0000177\end{funcdesc}
178
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000179\begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
180Logs a message with level \constant{INFO} on the root logger.
181The arguments are interpreted as for \function{debug()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000182\end{funcdesc}
183
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000184\begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
185Logs a message with level \constant{WARNING} on the root logger.
186The arguments are interpreted as for \function{debug()}.
187\end{funcdesc}
188
189\begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
190Logs a message with level \constant{ERROR} on the root logger.
191The arguments are interpreted as for \function{debug()}.
192\end{funcdesc}
193
194\begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
195Logs a message with level \constant{CRITICAL} on the root logger.
196The arguments are interpreted as for \function{debug()}.
197\end{funcdesc}
198
199\begin{funcdesc}{exception}{msg\optional{, *args}}
200Logs a message with level \constant{ERROR} on the root logger.
201The arguments are interpreted as for \function{debug()}. Exception info
202is added to the logging message. This function should only be called
203from an exception handler.
204\end{funcdesc}
205
Vinay Sajip739d49e2004-09-24 11:46:44 +0000206\begin{funcdesc}{log}{level, msg\optional{, *args\optional{, **kwargs}}}
207Logs a message with level \var{level} on the root logger.
208The other arguments are interpreted as for \function{debug()}.
209\end{funcdesc}
210
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000211\begin{funcdesc}{disable}{lvl}
212Provides an overriding level \var{lvl} for all loggers which takes
213precedence over the logger's own level. When the need arises to
214temporarily throttle logging output down across the whole application,
215this function can be useful.
216\end{funcdesc}
217
218\begin{funcdesc}{addLevelName}{lvl, levelName}
219Associates level \var{lvl} with text \var{levelName} in an internal
220dictionary, which is used to map numeric levels to a textual
221representation, for example when a \class{Formatter} formats a message.
222This function can also be used to define your own levels. The only
223constraints are that all levels used must be registered using this
224function, levels should be positive integers and they should increase
225in increasing order of severity.
226\end{funcdesc}
227
228\begin{funcdesc}{getLevelName}{lvl}
229Returns the textual representation of logging level \var{lvl}. If the
230level is one of the predefined levels \constant{CRITICAL},
231\constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG}
232then you get the corresponding string. If you have associated levels
233with names using \function{addLevelName()} then the name you have associated
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000234with \var{lvl} is returned. If a numeric value corresponding to one of the
235defined levels is passed in, the corresponding string representation is
236returned. Otherwise, the string "Level \%s" \% lvl is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000237\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000238
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000239\begin{funcdesc}{makeLogRecord}{attrdict}
240Creates and returns a new \class{LogRecord} instance whose attributes are
241defined by \var{attrdict}. This function is useful for taking a pickled
242\class{LogRecord} attribute dictionary, sent over a socket, and reconstituting
243it as a \class{LogRecord} instance at the receiving end.
244\end{funcdesc}
245
Skip Montanaro649698f2002-11-14 03:57:19 +0000246\begin{funcdesc}{basicConfig}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000247Does basic configuration for the logging system by creating a
248\class{StreamHandler} with a default \class{Formatter} and adding it to
249the root logger. The functions \function{debug()}, \function{info()},
250\function{warning()}, \function{error()} and \function{critical()} will call
251\function{basicConfig()} automatically if no handlers are defined for the
252root logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000253\end{funcdesc}
254
Skip Montanaro649698f2002-11-14 03:57:19 +0000255\begin{funcdesc}{shutdown}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000256Informs the logging system to perform an orderly shutdown by flushing and
257closing all handlers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000258\end{funcdesc}
259
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000260\begin{funcdesc}{setLoggerClass}{klass}
261Tells the logging system to use the class \var{klass} when instantiating a
262logger. The class should define \method{__init__()} such that only a name
263argument is required, and the \method{__init__()} should call
264\method{Logger.__init__()}. This function is typically called before any
265loggers are instantiated by applications which need to use custom logger
266behavior.
267\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000268
Fred Drake68e6d572003-01-28 22:02:35 +0000269
270\begin{seealso}
271 \seepep{282}{A Logging System}
272 {The proposal which described this feature for inclusion in
273 the Python standard library.}
Fred Drake11514792004-01-08 14:59:02 +0000274 \seelink{http://www.red-dove.com/python_logging.html}
275 {Original Python \module{logging} package}
276 {This is the original source for the \module{logging}
277 package. The version of the package available from this
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000278 site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x,
279 which do not include the \module{logging} package in the standard
Fred Drake11514792004-01-08 14:59:02 +0000280 library.}
Fred Drake68e6d572003-01-28 22:02:35 +0000281\end{seealso}
282
283
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000284\subsection{Logger Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000285
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000286Loggers have the following attributes and methods. Note that Loggers are
287never instantiated directly, but always through the module-level function
288\function{logging.getLogger(name)}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000289
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000290\begin{datadesc}{propagate}
291If this evaluates to false, logging messages are not passed by this
292logger or by child loggers to higher level (ancestor) loggers. The
293constructor sets this attribute to 1.
Skip Montanaro649698f2002-11-14 03:57:19 +0000294\end{datadesc}
295
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000296\begin{methoddesc}{setLevel}{lvl}
297Sets the threshold for this logger to \var{lvl}. Logging messages
298which are less severe than \var{lvl} will be ignored. When a logger is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000299created, the level is set to \constant{NOTSET} (which causes all messages
300to be processed in the root logger, or delegation to the parent in non-root
301loggers).
Skip Montanaro649698f2002-11-14 03:57:19 +0000302\end{methoddesc}
303
304\begin{methoddesc}{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000305Indicates if a message of severity \var{lvl} would be processed by
306this logger. This method checks first the module-level level set by
307\function{logging.disable(lvl)} and then the logger's effective level as
308determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000309\end{methoddesc}
310
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000311\begin{methoddesc}{getEffectiveLevel}{}
312Indicates the effective level for this logger. If a value other than
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000313\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000314Otherwise, the hierarchy is traversed towards the root until a value
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000315other than \constant{NOTSET} is found, and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000316\end{methoddesc}
317
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000318\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
319Logs a message with level \constant{DEBUG} on this logger.
320The \var{msg} is the message format string, and the \var{args} are the
321arguments which are merged into \var{msg}. The only keyword argument in
322\var{kwargs} which is inspected is \var{exc_info} which, if it does not
Vinay Sajip1dc5b1e2004-10-03 19:10:05 +0000323evaluate as false, causes exception information to be added to the logging
324message. If an exception tuple (as provided by \function{sys.exc_info()})
325is provided, it is used; otherwise, \function{sys.exc_info()} is called
326to get the exception information.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000327\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000328
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000329\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
330Logs a message with level \constant{INFO} on this logger.
331The arguments are interpreted as for \method{debug()}.
332\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000333
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000334\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
335Logs a message with level \constant{WARNING} on this logger.
336The arguments are interpreted as for \method{debug()}.
337\end{methoddesc}
338
339\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
340Logs a message with level \constant{ERROR} on this logger.
341The arguments are interpreted as for \method{debug()}.
342\end{methoddesc}
343
344\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
345Logs a message with level \constant{CRITICAL} on this logger.
346The arguments are interpreted as for \method{debug()}.
347\end{methoddesc}
348
349\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
Vinay Sajip1cf56d02004-08-04 08:36:44 +0000350Logs a message with integer level \var{lvl} on this logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000351The other arguments are interpreted as for \method{debug()}.
352\end{methoddesc}
353
354\begin{methoddesc}{exception}{msg\optional{, *args}}
355Logs a message with level \constant{ERROR} on this logger.
356The arguments are interpreted as for \method{debug()}. Exception info
357is added to the logging message. This method should only be called
358from an exception handler.
359\end{methoddesc}
360
361\begin{methoddesc}{addFilter}{filt}
362Adds the specified filter \var{filt} to this logger.
363\end{methoddesc}
364
365\begin{methoddesc}{removeFilter}{filt}
366Removes the specified filter \var{filt} from this logger.
367\end{methoddesc}
368
369\begin{methoddesc}{filter}{record}
370Applies this logger's filters to the record and returns a true value if
371the record is to be processed.
372\end{methoddesc}
373
374\begin{methoddesc}{addHandler}{hdlr}
375Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000376\end{methoddesc}
377
378\begin{methoddesc}{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000379Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000380\end{methoddesc}
381
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000382\begin{methoddesc}{findCaller}{}
383Finds the caller's source filename and line number. Returns the filename
384and line number as a 2-element tuple.
Skip Montanaro649698f2002-11-14 03:57:19 +0000385\end{methoddesc}
386
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000387\begin{methoddesc}{handle}{record}
388Handles a record by passing it to all handlers associated with this logger
389and its ancestors (until a false value of \var{propagate} is found).
390This method is used for unpickled records received from a socket, as well
391as those created locally. Logger-level filtering is applied using
392\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000393\end{methoddesc}
394
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000395\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info}
396This is a factory method which can be overridden in subclasses to create
397specialized \class{LogRecord} instances.
Skip Montanaro649698f2002-11-14 03:57:19 +0000398\end{methoddesc}
399
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000400\subsection{Basic example \label{minimal-example}}
401
402The \module{logging} package provides a lot of flexibility, and its
403configuration can appear daunting. This section demonstrates that simple
404use of the logging package is possible.
405
406The simplest example shows logging to the console:
407
408\begin{verbatim}
409import logging
410
411logging.debug('A debug message')
412logging.info('Some information')
413logging.warning('A shot across the bows')
414\end{verbatim}
415
416If you run the above script, you'll see this:
417\begin{verbatim}
418WARNING:root:A shot across the bows
419\end{verbatim}
420
421Because no particular logger was specified, the system used the root logger.
422The debug and info messages didn't appear because by default, the root
423logger is configured to only handle messages with a severity of WARNING
424or above. The message format is also a configuration default, as is the output
425destination of the messages - \code{sys.stderr}. The severity level,
426the message format and destination can be easily changed, as shown in
427the example below:
428
429\begin{verbatim}
430import logging
431
432logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000433 format='%(asctime)s %(levelname)s %(message)s',
434 filename='/tmp/myapp.log',
435 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000436logging.debug('A debug message')
437logging.info('Some information')
438logging.warning('A shot across the bows')
439\end{verbatim}
440
441The \method{basicConfig()} method is used to change the configuration
442defaults, which results in output (written to \code{/tmp/myapp.log})
443which should look something like the following:
444
445\begin{verbatim}
4462004-07-02 13:00:08,743 DEBUG A debug message
4472004-07-02 13:00:08,743 INFO Some information
4482004-07-02 13:00:08,743 WARNING A shot across the bows
449\end{verbatim}
450
451This time, all messages with a severity of DEBUG or above were handled,
452and the format of the messages was also changed, and output went to the
453specified file rather than the console.
454
455Formatting uses standard Python string formatting - see section
456\ref{typesseq-strings}. The format string takes the following
457common specifiers. For a complete list of specifiers, consult the
458\class{Formatter} documentation.
459
460\begin{tableii}{l|l}{code}{Format}{Description}
461\lineii{\%(name)s} {Name of the logger (logging channel).}
462\lineii{\%(levelname)s}{Text logging level for the message
463 (\code{'DEBUG'}, \code{'INFO'},
464 \code{'WARNING'}, \code{'ERROR'},
465 \code{'CRITICAL'}).}
466\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
467 was created. By default this is of the form
468 ``2003-07-08 16:49:45,896'' (the numbers after the
469 comma are millisecond portion of the time).}
470\lineii{\%(message)s} {The logged message.}
471\end{tableii}
472
473To change the date/time format, you can pass an additional keyword parameter,
474\var{datefmt}, as in the following:
475
476\begin{verbatim}
477import logging
478
479logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000480 format='%(asctime)s %(levelname)-8s %(message)s',
481 datefmt='%a, %d %b %Y %H:%M:%S',
482 filename='/temp/myapp.log',
483 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000484logging.debug('A debug message')
485logging.info('Some information')
486logging.warning('A shot across the bows')
487\end{verbatim}
488
489which would result in output like
490
491\begin{verbatim}
492Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
493Fri, 02 Jul 2004 13:06:18 INFO Some information
494Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
495\end{verbatim}
496
497The date format string follows the requirements of \function{strftime()} -
498see the documentation for the \refmodule{time} module.
499
500If, instead of sending logging output to the console or a file, you'd rather
501use a file-like object which you have created separately, you can pass it
502to \function{basicConfig()} using the \var{stream} keyword argument. Note
503that if both \var{stream} and \var{filename} keyword arguments are passed,
504the \var{stream} argument is ignored.
505
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000506Of course, you can put variable information in your output. To do this,
507simply have the message be a format string and pass in additional arguments
508containing the variable information, as in the following example:
509
510\begin{verbatim}
511import logging
512
513logging.basicConfig(level=logging.DEBUG,
514 format='%(asctime)s %(levelname)-8s %(message)s',
515 datefmt='%a, %d %b %Y %H:%M:%S',
516 filename='/temp/myapp.log',
517 filemode='w')
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000518logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000519\end{verbatim}
520
521which would result in
522
523\begin{verbatim}
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000524Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000525\end{verbatim}
526
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000527\subsection{Logging to multiple destinations \label{multiple-destinations}}
528
529Let's say you want to log to console and file with different message formats
530and in differing circumstances. Say you want to log messages with levels
531of DEBUG and higher to file, and those messages at level INFO and higher to
532the console. Let's also assume that the file should contain timestamps, but
533the console messages should not. Here's how you can achieve this:
534
535\begin{verbatim}
536import logging
537
Fred Drake048840c2004-10-29 14:35:42 +0000538# set up logging to file - see previous section for more details
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000539logging.basicConfig(level=logging.DEBUG,
540 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
541 datefmt='%m-%d %H:%M',
542 filename='/temp/myapp.log',
543 filemode='w')
Fred Drake048840c2004-10-29 14:35:42 +0000544# define a Handler which writes INFO messages or higher to the sys.stderr
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000545console = logging.StreamHandler()
546console.setLevel(logging.INFO)
Fred Drake048840c2004-10-29 14:35:42 +0000547# set a format which is simpler for console use
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000548formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Fred Drake048840c2004-10-29 14:35:42 +0000549# tell the handler to use this format
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000550console.setFormatter(formatter)
Fred Drake048840c2004-10-29 14:35:42 +0000551# add the handler to the root logger
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000552logging.getLogger('').addHandler(console)
553
Fred Drake048840c2004-10-29 14:35:42 +0000554# Now, we can log to the root logger, or any other logger. First the root...
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000555logging.info('Jackdaws love my big sphinx of quartz.')
556
Fred Drake048840c2004-10-29 14:35:42 +0000557# Now, define a couple of other loggers which might represent areas in your
558# application:
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000559
560logger1 = logging.getLogger('myapp.area1')
561logger2 = logging.getLogger('myapp.area2')
562
563logger1.debug('Quick zephyrs blow, vexing daft Jim.')
564logger1.info('How quickly daft jumping zebras vex.')
565logger2.warning('Jail zesty vixen who grabbed pay from quack.')
566logger2.error('The five boxing wizards jump quickly.')
567\end{verbatim}
568
569When you run this, on the console you will see
570
571\begin{verbatim}
572root : INFO Jackdaws love my big sphinx of quartz.
573myapp.area1 : INFO How quickly daft jumping zebras vex.
574myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
575myapp.area2 : ERROR The five boxing wizards jump quickly.
576\end{verbatim}
577
578and in the file you will see something like
579
580\begin{verbatim}
58110-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
58210-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
58310-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
58410-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
58510-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
586\end{verbatim}
587
588As you can see, the DEBUG message only shows up in the file. The other
589messages are sent to both destinations.
590
Vinay Sajip006483b2004-10-29 12:30:28 +0000591This example uses console and file handlers, but you can use any number and
592combination of handlers you choose.
593
594\subsection{Sending and receiving logging events across a network
595\label{network-logging}}
596
597Let's say you want to send logging events across a network, and handle them
598at the receiving end. A simple way of doing this is attaching a
599\class{SocketHandler} instance to the root logger at the sending end:
600
601\begin{verbatim}
602import logging, logging.handlers
603
604rootLogger = logging.getLogger('')
605rootLogger.setLevel(logging.DEBUG)
606socketHandler = logging.handlers.SocketHandler('localhost',
607 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
608# don't bother with a formatter, since a socket handler sends the event as
609# an unformatted pickle
610rootLogger.addHandler(socketHandler)
611
Fred Drake048840c2004-10-29 14:35:42 +0000612# Now, we can log to the root logger, or any other logger. First the root...
Vinay Sajip006483b2004-10-29 12:30:28 +0000613logging.info('Jackdaws love my big sphinx of quartz.')
614
Fred Drake048840c2004-10-29 14:35:42 +0000615# Now, define a couple of other loggers which might represent areas in your
616# application:
Vinay Sajip006483b2004-10-29 12:30:28 +0000617
618logger1 = logging.getLogger('myapp.area1')
619logger2 = logging.getLogger('myapp.area2')
620
621logger1.debug('Quick zephyrs blow, vexing daft Jim.')
622logger1.info('How quickly daft jumping zebras vex.')
623logger2.warning('Jail zesty vixen who grabbed pay from quack.')
624logger2.error('The five boxing wizards jump quickly.')
625\end{verbatim}
626
627At the receiving end, you can set up a receiver using the
628\module{SocketServer} module. Here is a basic working example:
629
630\begin{verbatim}
Fred Drake048840c2004-10-29 14:35:42 +0000631import cPickle
632import logging
633import logging.handlers
634import SocketServer
635import struct
Vinay Sajip006483b2004-10-29 12:30:28 +0000636
Vinay Sajip006483b2004-10-29 12:30:28 +0000637
Fred Drake048840c2004-10-29 14:35:42 +0000638class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
639 """Handler for a streaming logging request.
640
641 This basically logs the record using whatever logging policy is
642 configured locally.
Vinay Sajip006483b2004-10-29 12:30:28 +0000643 """
644
645 def handle(self):
646 """
647 Handle multiple requests - each expected to be a 4-byte length,
648 followed by the LogRecord in pickle format. Logs the record
649 according to whatever policy is configured locally.
650 """
651 while 1:
652 chunk = self.connection.recv(4)
653 if len(chunk) < 4:
654 break
655 slen = struct.unpack(">L", chunk)[0]
656 chunk = self.connection.recv(slen)
657 while len(chunk) < slen:
658 chunk = chunk + self.connection.recv(slen - len(chunk))
659 obj = self.unPickle(chunk)
660 record = logging.makeLogRecord(obj)
661 self.handleLogRecord(record)
662
663 def unPickle(self, data):
664 return cPickle.loads(data)
665
666 def handleLogRecord(self, record):
Fred Drake048840c2004-10-29 14:35:42 +0000667 # if a name is specified, we use the named logger rather than the one
668 # implied by the record.
Vinay Sajip006483b2004-10-29 12:30:28 +0000669 if self.server.logname is not None:
670 name = self.server.logname
671 else:
672 name = record.name
673 logger = logging.getLogger(name)
Fred Drake048840c2004-10-29 14:35:42 +0000674 # N.B. EVERY record gets logged. This is because Logger.handle
675 # is normally called AFTER logger-level filtering. If you want
676 # to do filtering, do it at the client end to save wasting
677 # cycles and network bandwidth!
Vinay Sajip006483b2004-10-29 12:30:28 +0000678 logger.handle(record)
679
Fred Drake048840c2004-10-29 14:35:42 +0000680class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
681 """simple TCP socket-based logging receiver suitable for testing.
Vinay Sajip006483b2004-10-29 12:30:28 +0000682 """
683
684 allow_reuse_address = 1
685
686 def __init__(self, host='localhost',
Fred Drake048840c2004-10-29 14:35:42 +0000687 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
688 handler=LogRecordStreamHandler):
689 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
Vinay Sajip006483b2004-10-29 12:30:28 +0000690 self.abort = 0
691 self.timeout = 1
692 self.logname = None
693
694 def serve_until_stopped(self):
695 import select
696 abort = 0
697 while not abort:
698 rd, wr, ex = select.select([self.socket.fileno()],
699 [], [],
700 self.timeout)
701 if rd:
702 self.handle_request()
703 abort = self.abort
704
705def main():
706 logging.basicConfig(
Vinay Sajipedde4922004-11-11 13:54:48 +0000707 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
Vinay Sajip006483b2004-10-29 12:30:28 +0000708 tcpserver = LogRecordSocketReceiver()
709 print "About to start TCP server..."
710 tcpserver.serve_until_stopped()
711
712if __name__ == "__main__":
713 main()
714\end{verbatim}
715
Vinay Sajipedde4922004-11-11 13:54:48 +0000716First run the server, and then the client. On the client side, nothing is
717printed on the console; on the server side, you should see something like:
Vinay Sajip006483b2004-10-29 12:30:28 +0000718
719\begin{verbatim}
720About to start TCP server...
721 59 root INFO Jackdaws love my big sphinx of quartz.
722 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
723 69 myapp.area1 INFO How quickly daft jumping zebras vex.
724 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
725 69 myapp.area2 ERROR The five boxing wizards jump quickly.
726\end{verbatim}
727
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000728\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000729
Fred Drake68e6d572003-01-28 22:02:35 +0000730Handlers have the following attributes and methods. Note that
731\class{Handler} is never instantiated directly; this class acts as a
732base for more useful subclasses. However, the \method{__init__()}
733method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000734
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000735\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000736Initializes the \class{Handler} instance by setting its level, setting
737the list of filters to the empty list and creating a lock (using
Raymond Hettingerc75c3e02003-09-01 22:50:52 +0000738\method{createLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000739\end{methoddesc}
740
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000741\begin{methoddesc}{createLock}{}
742Initializes a thread lock which can be used to serialize access to
743underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000744\end{methoddesc}
745
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000746\begin{methoddesc}{acquire}{}
747Acquires the thread lock created with \method{createLock()}.
748\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000749
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000750\begin{methoddesc}{release}{}
751Releases the thread lock acquired with \method{acquire()}.
752\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000753
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000754\begin{methoddesc}{setLevel}{lvl}
755Sets the threshold for this handler to \var{lvl}. Logging messages which are
756less severe than \var{lvl} will be ignored. When a handler is created, the
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000757level is set to \constant{NOTSET} (which causes all messages to be processed).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000758\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000759
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000760\begin{methoddesc}{setFormatter}{form}
761Sets the \class{Formatter} for this handler to \var{form}.
762\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000763
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000764\begin{methoddesc}{addFilter}{filt}
765Adds the specified filter \var{filt} to this handler.
766\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000767
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000768\begin{methoddesc}{removeFilter}{filt}
769Removes the specified filter \var{filt} from this handler.
770\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000771
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000772\begin{methoddesc}{filter}{record}
773Applies this handler's filters to the record and returns a true value if
774the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000775\end{methoddesc}
776
777\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000778Ensure all logging output has been flushed. This version does
779nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000780\end{methoddesc}
781
Skip Montanaro649698f2002-11-14 03:57:19 +0000782\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000783Tidy up any resources used by the handler. This version does
784nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000785\end{methoddesc}
786
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000787\begin{methoddesc}{handle}{record}
788Conditionally emits the specified logging record, depending on
789filters which may have been added to the handler. Wraps the actual
790emission of the record with acquisition/release of the I/O thread
791lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000792\end{methoddesc}
793
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000794\begin{methoddesc}{handleError}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000795This method should be called from handlers when an exception is
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000796encountered during an \method{emit()} call. By default it does nothing,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000797which means that exceptions get silently ignored. This is what is
798mostly wanted for a logging system - most users will not care
799about errors in the logging system, they are more interested in
800application errors. You could, however, replace this with a custom
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000801handler if you wish. The specified record is the one which was being
802processed when the exception occurred.
Skip Montanaro649698f2002-11-14 03:57:19 +0000803\end{methoddesc}
804
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000805\begin{methoddesc}{format}{record}
806Do formatting for a record - if a formatter is set, use it.
807Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000808\end{methoddesc}
809
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000810\begin{methoddesc}{emit}{record}
811Do whatever it takes to actually log the specified logging record.
812This version is intended to be implemented by subclasses and so
813raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000814\end{methoddesc}
815
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000816\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000817
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000818The \class{StreamHandler} class sends logging output to streams such as
819\var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more
820precisely, any object which supports \method{write()} and \method{flush()}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000821methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000822
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000823\begin{classdesc}{StreamHandler}{\optional{strm}}
824Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
825specified, the instance will use it for logging output; otherwise,
826\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000827\end{classdesc}
828
829\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000830If a formatter is specified, it is used to format the record.
831The record is then written to the stream with a trailing newline.
832If exception information is present, it is formatted using
833\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000834\end{methoddesc}
835
836\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000837Flushes the stream by calling its \method{flush()} method. Note that
838the \method{close()} method is inherited from \class{Handler} and
839so does nothing, so an explicit \method{flush()} call may be needed
840at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000841\end{methoddesc}
842
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000843\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000844
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000845The \class{FileHandler} class sends logging output to a disk file.
Fred Drake68e6d572003-01-28 22:02:35 +0000846It inherits the output functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000847
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000848\begin{classdesc}{FileHandler}{filename\optional{, mode}}
849Returns a new instance of the \class{FileHandler} class. The specified
850file is opened and used as the stream for logging. If \var{mode} is
Fred Drake9a5b6a62003-07-08 15:38:40 +0000851not specified, \constant{'a'} is used. By default, the file grows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000852indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000853\end{classdesc}
854
855\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000856Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000857\end{methoddesc}
858
859\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000860Outputs the record to the file.
861\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000862
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000863\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000864
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000865The \class{RotatingFileHandler} class supports rotation of disk log files.
866
Fred Drake9a5b6a62003-07-08 15:38:40 +0000867\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{,
868 maxBytes\optional{, backupCount}}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000869Returns a new instance of the \class{RotatingFileHandler} class. The
870specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +0000871\var{mode} is not specified, \code{'a'} is used. By default, the
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000872file grows indefinitely.
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000873
874You can use the \var{maxBytes} and
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000875\var{backupCount} values to allow the file to \dfn{rollover} at a
876predetermined size. When the size is about to be exceeded, the file is
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000877closed and a new file is silently opened for output. Rollover occurs
878whenever the current log file is nearly \var{maxBytes} in length; if
879\var{maxBytes} is zero, rollover never occurs. If \var{backupCount}
880is non-zero, the system will save old log files by appending the
881extensions ".1", ".2" etc., to the filename. For example, with
882a \var{backupCount} of 5 and a base file name of
883\file{app.log}, you would get \file{app.log},
884\file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being
885written to is always \file{app.log}. When this file is filled, it is
886closed and renamed to \file{app.log.1}, and if files \file{app.log.1},
887\file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2},
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000888\file{app.log.3} etc. respectively.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000889\end{classdesc}
890
891\begin{methoddesc}{doRollover}{}
892Does a rollover, as described above.
893\end{methoddesc}
894
895\begin{methoddesc}{emit}{record}
Johannes Gijsbersf1643222004-11-07 16:11:35 +0000896Outputs the record to the file, catering for rollover as described previously.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000897\end{methoddesc}
898
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +0000899\subsubsection{TimedRotatingFileHandler}
900
901The \class{TimedRotatingFileHandler} class supports rotation of disk log files
902at certain timed intervals.
903
904\begin{classdesc}{TimedRotatingFileHandler}{filename
905 \optional{,when
906 \optional{,interval
907 \optional{,backupCount}}}}
908
909Returns a new instance of the \class{TimedRotatingFileHandler} class. The
910specified file is opened and used as the stream for logging. On rotating
911it also sets the filename suffix. Rotating happens based on the product
Vinay Sajipedde4922004-11-11 13:54:48 +0000912of \var{when} and \var{interval}.
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +0000913
914You can use the \var{when} to specify the type of \var{interval}. The
915list of possible values is, note that they are not case sensitive:
916
917\begin{tableii}{l|l}{}{Value}{Type of interval}
918 \lineii{S}{Seconds}
919 \lineii{M}{Minutes}
920 \lineii{H}{Hours}
921 \lineii{D}{Days}
922 \lineii{W}{Week day (0=Monday)}
923 \lineii{midnight}{Roll over at midnight}
924\end{tableii}
925
926If \var{backupCount} is non-zero, the system will save old log files by
927appending the extensions ".1", ".2" etc., to the filename. For example,
928with a \var{backupCount} of 5 and a base file name of \file{app.log},
929you would get \file{app.log}, \file{app.log.1}, \file{app.log.2}, up to
930\file{app.log.5}. The file being written to is always \file{app.log}.
931When this file is filled, it is closed and renamed to \file{app.log.1},
932and if files \file{app.log.1}, \file{app.log.2}, etc. exist, then they
933are renamed to \file{app.log.2}, \file{app.log.3} etc. respectively.
934\end{classdesc}
935
936\begin{methoddesc}{doRollover}{}
937Does a rollover, as described above.
938\end{methoddesc}
939
940\begin{methoddesc}{emit}{record}
941Outputs the record to the file, catering for rollover as described
942above.
943\end{methoddesc}
944
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000945\subsubsection{SocketHandler}
946
947The \class{SocketHandler} class sends logging output to a network
948socket. The base class uses a TCP socket.
949
950\begin{classdesc}{SocketHandler}{host, port}
951Returns a new instance of the \class{SocketHandler} class intended to
952communicate with a remote machine whose address is given by \var{host}
953and \var{port}.
954\end{classdesc}
955
956\begin{methoddesc}{close}{}
957Closes the socket.
958\end{methoddesc}
959
960\begin{methoddesc}{handleError}{}
961\end{methoddesc}
962
963\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000964Pickles the record's attribute dictionary and writes it to the socket in
965binary format. If there is an error with the socket, silently drops the
966packet. If the connection was previously lost, re-establishes the connection.
Fred Drake6b3b0462004-04-09 18:26:40 +0000967To unpickle the record at the receiving end into a \class{LogRecord}, use the
968\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000969\end{methoddesc}
970
971\begin{methoddesc}{handleError}{}
972Handles an error which has occurred during \method{emit()}. The
973most likely cause is a lost connection. Closes the socket so that
974we can retry on the next event.
975\end{methoddesc}
976
977\begin{methoddesc}{makeSocket}{}
978This is a factory method which allows subclasses to define the precise
979type of socket they want. The default implementation creates a TCP
980socket (\constant{socket.SOCK_STREAM}).
981\end{methoddesc}
982
983\begin{methoddesc}{makePickle}{record}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000984Pickles the record's attribute dictionary in binary format with a length
985prefix, and returns it ready for transmission across the socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000986\end{methoddesc}
987
988\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000989Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000990for partial sends which can happen when the network is busy.
991\end{methoddesc}
992
993\subsubsection{DatagramHandler}
994
995The \class{DatagramHandler} class inherits from \class{SocketHandler}
996to support sending logging messages over UDP sockets.
997
998\begin{classdesc}{DatagramHandler}{host, port}
999Returns a new instance of the \class{DatagramHandler} class intended to
1000communicate with a remote machine whose address is given by \var{host}
1001and \var{port}.
1002\end{classdesc}
1003
1004\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001005Pickles the record's attribute dictionary and writes it to the socket in
1006binary format. If there is an error with the socket, silently drops the
1007packet.
Fred Drake6b3b0462004-04-09 18:26:40 +00001008To unpickle the record at the receiving end into a \class{LogRecord}, use the
1009\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001010\end{methoddesc}
1011
1012\begin{methoddesc}{makeSocket}{}
1013The factory method of \class{SocketHandler} is here overridden to create
1014a UDP socket (\constant{socket.SOCK_DGRAM}).
1015\end{methoddesc}
1016
1017\begin{methoddesc}{send}{s}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001018Send a pickled string to a socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001019\end{methoddesc}
1020
1021\subsubsection{SysLogHandler}
1022
1023The \class{SysLogHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +00001024remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001025
1026\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
1027Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +00001028communicate with a remote \UNIX{} machine whose address is given by
1029\var{address} in the form of a \code{(\var{host}, \var{port})}
1030tuple. If \var{address} is not specified, \code{('localhost', 514)} is
1031used. The address is used to open a UDP socket. If \var{facility} is
1032not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001033\end{classdesc}
1034
1035\begin{methoddesc}{close}{}
1036Closes the socket to the remote host.
1037\end{methoddesc}
1038
1039\begin{methoddesc}{emit}{record}
1040The record is formatted, and then sent to the syslog server. If
1041exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +00001042\end{methoddesc}
1043
1044\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001045Encodes the facility and priority into an integer. You can pass in strings
1046or integers - if strings are passed, internal mapping dictionaries are used
1047to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +00001048\end{methoddesc}
1049
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001050\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +00001051
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001052The \class{NTEventLogHandler} class supports sending logging messages
1053to a local Windows NT, Windows 2000 or Windows XP event log. Before
1054you can use it, you need Mark Hammond's Win32 extensions for Python
1055installed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001056
Fred Drake9a5b6a62003-07-08 15:38:40 +00001057\begin{classdesc}{NTEventLogHandler}{appname\optional{,
1058 dllname\optional{, logtype}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001059Returns a new instance of the \class{NTEventLogHandler} class. The
1060\var{appname} is used to define the application name as it appears in the
1061event log. An appropriate registry entry is created using this name.
1062The \var{dllname} should give the fully qualified pathname of a .dll or .exe
1063which contains message definitions to hold in the log (if not specified,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001064\code{'win32service.pyd'} is used - this is installed with the Win32
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001065extensions and contains some basic placeholder message definitions.
1066Note that use of these placeholders will make your event logs big, as the
1067entire message source is held in the log. If you want slimmer logs, you have
1068to pass in the name of your own .dll or .exe which contains the message
1069definitions you want to use in the event log). The \var{logtype} is one of
Fred Drake9a5b6a62003-07-08 15:38:40 +00001070\code{'Application'}, \code{'System'} or \code{'Security'}, and
1071defaults to \code{'Application'}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001072\end{classdesc}
1073
1074\begin{methoddesc}{close}{}
1075At this point, you can remove the application name from the registry as a
1076source of event log entries. However, if you do this, you will not be able
1077to see the events as you intended in the Event Log Viewer - it needs to be
1078able to access the registry to get the .dll name. The current version does
1079not do this (in fact it doesn't do anything).
1080\end{methoddesc}
1081
1082\begin{methoddesc}{emit}{record}
1083Determines the message ID, event category and event type, and then logs the
1084message in the NT event log.
1085\end{methoddesc}
1086
1087\begin{methoddesc}{getEventCategory}{record}
1088Returns the event category for the record. Override this if you
1089want to specify your own categories. This version returns 0.
1090\end{methoddesc}
1091
1092\begin{methoddesc}{getEventType}{record}
1093Returns the event type for the record. Override this if you want
1094to specify your own types. This version does a mapping using the
1095handler's typemap attribute, which is set up in \method{__init__()}
1096to a dictionary which contains mappings for \constant{DEBUG},
1097\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
1098\constant{CRITICAL}. If you are using your own levels, you will either need
1099to override this method or place a suitable dictionary in the
1100handler's \var{typemap} attribute.
1101\end{methoddesc}
1102
1103\begin{methoddesc}{getMessageID}{record}
1104Returns the message ID for the record. If you are using your
1105own messages, you could do this by having the \var{msg} passed to the
1106logger being an ID rather than a format string. Then, in here,
1107you could use a dictionary lookup to get the message ID. This
1108version returns 1, which is the base message ID in
Fred Drake9a5b6a62003-07-08 15:38:40 +00001109\file{win32service.pyd}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001110\end{methoddesc}
1111
1112\subsubsection{SMTPHandler}
1113
1114The \class{SMTPHandler} class supports sending logging messages to an email
1115address via SMTP.
1116
1117\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
1118Returns a new instance of the \class{SMTPHandler} class. The
1119instance is initialized with the from and to addresses and subject
1120line of the email. The \var{toaddrs} should be a list of strings without
1121domain names (That's what the \var{mailhost} is for). To specify a
1122non-standard SMTP port, use the (host, port) tuple format for the
1123\var{mailhost} argument. If you use a string, the standard SMTP port
1124is used.
1125\end{classdesc}
1126
1127\begin{methoddesc}{emit}{record}
1128Formats the record and sends it to the specified addressees.
1129\end{methoddesc}
1130
1131\begin{methoddesc}{getSubject}{record}
1132If you want to specify a subject line which is record-dependent,
1133override this method.
1134\end{methoddesc}
1135
1136\subsubsection{MemoryHandler}
1137
1138The \class{MemoryHandler} supports buffering of logging records in memory,
1139periodically flushing them to a \dfn{target} handler. Flushing occurs
1140whenever the buffer is full, or when an event of a certain severity or
1141greater is seen.
1142
1143\class{MemoryHandler} is a subclass of the more general
1144\class{BufferingHandler}, which is an abstract class. This buffers logging
1145records in memory. Whenever each record is added to the buffer, a
1146check is made by calling \method{shouldFlush()} to see if the buffer
1147should be flushed. If it should, then \method{flush()} is expected to
1148do the needful.
1149
1150\begin{classdesc}{BufferingHandler}{capacity}
1151Initializes the handler with a buffer of the specified capacity.
1152\end{classdesc}
1153
1154\begin{methoddesc}{emit}{record}
1155Appends the record to the buffer. If \method{shouldFlush()} returns true,
1156calls \method{flush()} to process the buffer.
1157\end{methoddesc}
1158
1159\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001160You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001161just zaps the buffer to empty.
1162\end{methoddesc}
1163
1164\begin{methoddesc}{shouldFlush}{record}
1165Returns true if the buffer is up to capacity. This method can be
1166overridden to implement custom flushing strategies.
1167\end{methoddesc}
1168
1169\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001170\optional{, target}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001171Returns a new instance of the \class{MemoryHandler} class. The
1172instance is initialized with a buffer size of \var{capacity}. If
1173\var{flushLevel} is not specified, \constant{ERROR} is used. If no
1174\var{target} is specified, the target will need to be set using
1175\method{setTarget()} before this handler does anything useful.
1176\end{classdesc}
1177
1178\begin{methoddesc}{close}{}
1179Calls \method{flush()}, sets the target to \constant{None} and
1180clears the buffer.
1181\end{methoddesc}
1182
1183\begin{methoddesc}{flush}{}
1184For a \class{MemoryHandler}, flushing means just sending the buffered
1185records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001186different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001187\end{methoddesc}
1188
1189\begin{methoddesc}{setTarget}{target}
1190Sets the target handler for this handler.
1191\end{methoddesc}
1192
1193\begin{methoddesc}{shouldFlush}{record}
1194Checks for buffer full or a record at the \var{flushLevel} or higher.
1195\end{methoddesc}
1196
1197\subsubsection{HTTPHandler}
1198
1199The \class{HTTPHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +00001200Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001201
1202\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
1203Returns a new instance of the \class{HTTPHandler} class. The
1204instance is initialized with a host address, url and HTTP method.
Fred Drake68e6d572003-01-28 22:02:35 +00001205If no \var{method} is specified, \samp{GET} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001206\end{classdesc}
1207
1208\begin{methoddesc}{emit}{record}
1209Sends the record to the Web server as an URL-encoded dictionary.
1210\end{methoddesc}
1211
1212\subsection{Formatter Objects}
1213
1214\class{Formatter}s have the following attributes and methods. They are
1215responsible for converting a \class{LogRecord} to (usually) a string
1216which can be interpreted by either a human or an external system. The
1217base
1218\class{Formatter} allows a formatting string to be specified. If none is
Fred Drake8efc74d2004-04-15 06:18:48 +00001219supplied, the default value of \code{'\%(message)s'} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001220
1221A Formatter can be initialized with a format string which makes use of
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001222knowledge of the \class{LogRecord} attributes - such as the default value
1223mentioned above making use of the fact that the user's message and
Fred Drake6b3b0462004-04-09 18:26:40 +00001224arguments are pre-formatted into a \class{LogRecord}'s \var{message}
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001225attribute. This format string contains standard python \%-style
1226mapping keys. See section \ref{typesseq-strings}, ``String Formatting
1227Operations,'' for more information on string formatting.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001228
Fred Drake6b3b0462004-04-09 18:26:40 +00001229Currently, the useful mapping keys in a \class{LogRecord} are:
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001230
Fred Drake9a5b6a62003-07-08 15:38:40 +00001231\begin{tableii}{l|l}{code}{Format}{Description}
1232\lineii{\%(name)s} {Name of the logger (logging channel).}
1233\lineii{\%(levelno)s} {Numeric logging level for the message
1234 (\constant{DEBUG}, \constant{INFO},
1235 \constant{WARNING}, \constant{ERROR},
1236 \constant{CRITICAL}).}
1237\lineii{\%(levelname)s}{Text logging level for the message
1238 (\code{'DEBUG'}, \code{'INFO'},
1239 \code{'WARNING'}, \code{'ERROR'},
1240 \code{'CRITICAL'}).}
1241\lineii{\%(pathname)s} {Full pathname of the source file where the logging
1242 call was issued (if available).}
1243\lineii{\%(filename)s} {Filename portion of pathname.}
1244\lineii{\%(module)s} {Module (name portion of filename).}
1245\lineii{\%(lineno)d} {Source line number where the logging call was issued
1246 (if available).}
Fred Drake6b3b0462004-04-09 18:26:40 +00001247\lineii{\%(created)f} {Time when the \class{LogRecord} was created (as
Fred Drake9a5b6a62003-07-08 15:38:40 +00001248 returned by \function{time.time()}).}
Fred Drake6b3b0462004-04-09 18:26:40 +00001249\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
1250 was created. By default this is of the form
Fred Drake9a5b6a62003-07-08 15:38:40 +00001251 ``2003-07-08 16:49:45,896'' (the numbers after the
1252 comma are millisecond portion of the time).}
1253\lineii{\%(msecs)d} {Millisecond portion of the time when the
1254 \class{LogRecord} was created.}
1255\lineii{\%(thread)d} {Thread ID (if available).}
1256\lineii{\%(process)d} {Process ID (if available).}
1257\lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001258\end{tableii}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001259
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001260\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
1261Returns a new instance of the \class{Formatter} class. The
1262instance is initialized with a format string for the message as a whole,
1263as well as a format string for the date/time portion of a message. If
Neal Norwitzdd3afa72003-07-08 16:26:34 +00001264no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001265is specified, the ISO8601 date format is used.
1266\end{classdesc}
1267
1268\begin{methoddesc}{format}{record}
1269The record's attribute dictionary is used as the operand to a
1270string formatting operation. Returns the resulting string.
1271Before formatting the dictionary, a couple of preparatory steps
1272are carried out. The \var{message} attribute of the record is computed
1273using \var{msg} \% \var{args}. If the formatting string contains
Fred Drake9a5b6a62003-07-08 15:38:40 +00001274\code{'(asctime)'}, \method{formatTime()} is called to format the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001275event time. If there is exception information, it is formatted using
1276\method{formatException()} and appended to the message.
1277\end{methoddesc}
1278
1279\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
1280This method should be called from \method{format()} by a formatter which
1281wants to make use of a formatted time. This method can be overridden
1282in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001283basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +00001284it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001285record. Otherwise, the ISO8601 format is used. The resulting
1286string is returned.
1287\end{methoddesc}
1288
1289\begin{methoddesc}{formatException}{exc_info}
1290Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +00001291as returned by \function{sys.exc_info()}) as a string. This default
1292implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001293The resulting string is returned.
1294\end{methoddesc}
1295
1296\subsection{Filter Objects}
1297
1298\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
1299more sophisticated filtering than is provided by levels. The base filter
1300class only allows events which are below a certain point in the logger
1301hierarchy. For example, a filter initialized with "A.B" will allow events
1302logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
1303"B.A.B" etc. If initialized with the empty string, all events are passed.
1304
1305\begin{classdesc}{Filter}{\optional{name}}
1306Returns an instance of the \class{Filter} class. If \var{name} is specified,
1307it names a logger which, together with its children, will have its events
1308allowed through the filter. If no name is specified, allows every event.
1309\end{classdesc}
1310
1311\begin{methoddesc}{filter}{record}
1312Is the specified record to be logged? Returns zero for no, nonzero for
1313yes. If deemed appropriate, the record may be modified in-place by this
1314method.
1315\end{methoddesc}
1316
1317\subsection{LogRecord Objects}
1318
Fred Drake6b3b0462004-04-09 18:26:40 +00001319\class{LogRecord} instances are created every time something is logged. They
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001320contain all the information pertinent to the event being logged. The
1321main information passed in is in msg and args, which are combined
1322using msg \% args to create the message field of the record. The record
1323also includes information such as when the record was created, the
1324source line where the logging call was made, and any exception
1325information to be logged.
1326
Fred Drake6b3b0462004-04-09 18:26:40 +00001327\class{LogRecord} has no methods; it's just a repository for
1328information about the logging event. The only reason it's a class
1329rather than a dictionary is to facilitate extension.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001330
1331\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001332 exc_info}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001333Returns an instance of \class{LogRecord} initialized with interesting
1334information. The \var{name} is the logger name; \var{lvl} is the
1335numeric level; \var{pathname} is the absolute pathname of the source
1336file in which the logging call was made; \var{lineno} is the line
1337number in that file where the logging call is found; \var{msg} is the
1338user-supplied message (a format string); \var{args} is the tuple
1339which, together with \var{msg}, makes up the user message; and
1340\var{exc_info} is the exception tuple obtained by calling
1341\function{sys.exc_info() }(or \constant{None}, if no exception information
1342is available).
1343\end{classdesc}
1344
1345\subsection{Thread Safety}
1346
1347The logging module is intended to be thread-safe without any special work
1348needing to be done by its clients. It achieves this though using threading
1349locks; there is one lock to serialize access to the module's shared data,
1350and each handler also creates a lock to serialize access to its underlying
1351I/O.
1352
1353\subsection{Configuration}
1354
1355
Fred Drake94ffbb72004-04-08 19:44:31 +00001356\subsubsection{Configuration functions%
1357 \label{logging-config-api}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001358
Fred Drake9a5b6a62003-07-08 15:38:40 +00001359The following functions allow the logging module to be
1360configured. Before they can be used, you must import
1361\module{logging.config}. Their use is optional --- you can configure
1362the logging module entirely by making calls to the main API (defined
1363in \module{logging} itself) and defining handlers which are declared
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001364either in \module{logging} or \module{logging.handlers}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001365
1366\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
1367Reads the logging configuration from a ConfigParser-format file named
1368\var{fname}. This function can be called several times from an application,
1369allowing an end user the ability to select from various pre-canned
1370configurations (if the developer provides a mechanism to present the
1371choices and load the chosen configuration). Defaults to be passed to
1372ConfigParser can be specified in the \var{defaults} argument.
1373\end{funcdesc}
1374
1375\begin{funcdesc}{listen}{\optional{port}}
1376Starts up a socket server on the specified port, and listens for new
1377configurations. If no port is specified, the module's default
1378\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
1379will be sent as a file suitable for processing by \function{fileConfig()}.
1380Returns a \class{Thread} instance on which you can call \method{start()}
1381to start the server, and which you can \method{join()} when appropriate.
1382To stop the server, call \function{stopListening()}.
1383\end{funcdesc}
1384
1385\begin{funcdesc}{stopListening}{}
1386Stops the listening server which was created with a call to
1387\function{listen()}. This is typically called before calling \method{join()}
1388on the return value from \function{listen()}.
1389\end{funcdesc}
1390
Fred Drake94ffbb72004-04-08 19:44:31 +00001391\subsubsection{Configuration file format%
1392 \label{logging-config-fileformat}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001393
Fred Drake6b3b0462004-04-09 18:26:40 +00001394The configuration file format understood by \function{fileConfig()} is
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001395based on ConfigParser functionality. The file must contain sections
1396called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
1397which identify by name the entities of each type which are defined in
1398the file. For each such entity, there is a separate section which
1399identified how that entity is configured. Thus, for a logger named
1400\code{log01} in the \code{[loggers]} section, the relevant
1401configuration details are held in a section
1402\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
1403the \code{[handlers]} section will have its configuration held in a
1404section called \code{[handler_hand01]}, while a formatter called
1405\code{form01} in the \code{[formatters]} section will have its
1406configuration specified in a section called
1407\code{[formatter_form01]}. The root logger configuration must be
1408specified in a section called \code{[logger_root]}.
1409
1410Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001411
1412\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001413[loggers]
1414keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +00001415
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001416[handlers]
1417keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1418
1419[formatters]
1420keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +00001421\end{verbatim}
1422
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001423The root logger must specify a level and a list of handlers. An
1424example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001425
1426\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001427[logger_root]
1428level=NOTSET
1429handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +00001430\end{verbatim}
1431
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001432The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1433ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1434\code{NOTSET} means that all messages will be logged. Level values are
1435\function{eval()}uated in the context of the \code{logging} package's
1436namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +00001437
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001438The \code{handlers} entry is a comma-separated list of handler names,
1439which must appear in the \code{[handlers]} section. These names must
1440appear in the \code{[handlers]} section and have corresponding
1441sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +00001442
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001443For loggers other than the root logger, some additional information is
1444required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +00001445
1446\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001447[logger_parser]
1448level=DEBUG
1449handlers=hand01
1450propagate=1
1451qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001452\end{verbatim}
1453
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001454The \code{level} and \code{handlers} entries are interpreted as for
1455the root logger, except that if a non-root logger's level is specified
1456as \code{NOTSET}, the system consults loggers higher up the hierarchy
1457to determine the effective level of the logger. The \code{propagate}
1458entry is set to 1 to indicate that messages must propagate to handlers
1459higher up the logger hierarchy from this logger, or 0 to indicate that
1460messages are \strong{not} propagated to handlers up the hierarchy. The
1461\code{qualname} entry is the hierarchical channel name of the logger,
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001462that is to say the name used by the application to get the logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001463
1464Sections which specify handler configuration are exemplified by the
1465following.
1466
Skip Montanaro649698f2002-11-14 03:57:19 +00001467\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001468[handler_hand01]
1469class=StreamHandler
1470level=NOTSET
1471formatter=form01
1472args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001473\end{verbatim}
1474
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001475The \code{class} entry indicates the handler's class (as determined by
1476\function{eval()} in the \code{logging} package's namespace). The
1477\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1478to mean "log everything".
1479
1480The \code{formatter} entry indicates the key name of the formatter for
1481this handler. If blank, a default formatter
1482(\code{logging._defaultFormatter}) is used. If a name is specified, it
1483must appear in the \code{[formatters]} section and have a
1484corresponding section in the configuration file.
1485
1486The \code{args} entry, when \function{eval()}uated in the context of
1487the \code{logging} package's namespace, is the list of arguments to
1488the constructor for the handler class. Refer to the constructors for
1489the relevant handlers, or to the examples below, to see how typical
1490entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001491
1492\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001493[handler_hand02]
1494class=FileHandler
1495level=DEBUG
1496formatter=form02
1497args=('python.log', 'w')
1498
1499[handler_hand03]
1500class=handlers.SocketHandler
1501level=INFO
1502formatter=form03
1503args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1504
1505[handler_hand04]
1506class=handlers.DatagramHandler
1507level=WARN
1508formatter=form04
1509args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1510
1511[handler_hand05]
1512class=handlers.SysLogHandler
1513level=ERROR
1514formatter=form05
1515args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1516
1517[handler_hand06]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001518class=handlers.NTEventLogHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001519level=CRITICAL
1520formatter=form06
1521args=('Python Application', '', 'Application')
1522
1523[handler_hand07]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001524class=handlers.SMTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001525level=WARN
1526formatter=form07
1527args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1528
1529[handler_hand08]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001530class=handlers.MemoryHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001531level=NOTSET
1532formatter=form08
1533target=
1534args=(10, ERROR)
1535
1536[handler_hand09]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001537class=handlers.HTTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001538level=NOTSET
1539formatter=form09
1540args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001541\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001542
1543Sections which specify formatter configuration are typified by the following.
1544
1545\begin{verbatim}
1546[formatter_form01]
1547format=F1 %(asctime)s %(levelname)s %(message)s
1548datefmt=
1549\end{verbatim}
1550
1551The \code{format} entry is the overall format string, and the
1552\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1553string. If empty, the package substitutes ISO8601 format date/times, which
1554is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1555The ISO8601 format also specifies milliseconds, which are appended to the
1556result of using the above format string, with a comma separator. An example
1557time in ISO8601 format is \code{2003-01-23 00:29:50,411}.