blob: 869b5c17a6b94d9b2be195f64be481ab9ccaf5f3 [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
82directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler.
83
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000084\item \class{RotatingFileHandler} instances send error messages to disk
85files, with support for maximum log file sizes and log file rotation.
86
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +000087\item \class{TimedRotatingFileHandler} instances send error messages to
88disk files rotating the log file at certain timed intervals.
89
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000090\item \class{SocketHandler} instances send error messages to
91TCP/IP sockets.
92
93\item \class{DatagramHandler} instances send error messages to UDP
94sockets.
95
96\item \class{SMTPHandler} instances send error messages to a
97designated email address.
98
99\item \class{SysLogHandler} instances send error messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000100\UNIX{} syslog daemon, possibly on a remote machine.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000101
102\item \class{NTEventLogHandler} instances send error messages to a
103Windows NT/2000/XP event log.
104
105\item \class{MemoryHandler} instances send error messages to a
106buffer in memory, which is flushed whenever specific criteria are
107met.
108
109\item \class{HTTPHandler} instances send error messages to an
Fred Drake68e6d572003-01-28 22:02:35 +0000110HTTP server using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000111
112\end{enumerate}
113
114The \class{StreamHandler} and \class{FileHandler} classes are defined
115in the core logging package. The other handlers are defined in a sub-
116module, \module{logging.handlers}. (There is also another sub-module,
117\module{logging.config}, for configuration functionality.)
118
119Logged messages are formatted for presentation through instances of the
120\class{Formatter} class. They are initialized with a format string
121suitable for use with the \% operator and a dictionary.
122
123For formatting multiple messages in a batch, instances of
124\class{BufferingFormatter} can be used. In addition to the format string
125(which is applied to each message in the batch), there is provision for
126header and trailer format strings.
127
128When filtering based on logger level and/or handler level is not enough,
129instances of \class{Filter} can be added to both \class{Logger} and
Fred Drakec23e0192003-01-28 22:09:16 +0000130\class{Handler} instances (through their \method{addFilter()} method).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000131Before deciding to process a message further, both loggers and handlers
132consult all their filters for permission. If any filter returns a false
133value, the message is not processed further.
134
135The basic \class{Filter} functionality allows filtering by specific logger
136name. If this feature is used, messages sent to the named logger and its
137children are allowed through the filter, and all others dropped.
138
139In addition to the classes described above, there are a number of module-
140level functions.
141
142\begin{funcdesc}{getLogger}{\optional{name}}
143Return a logger with the specified name or, if no name is specified, return
Vinay Sajip17952b72004-08-31 10:21:51 +0000144a logger which is the root logger of the hierarchy. If specified, the name
145is typically a dot-separated hierarchical name like \var{"a"}, \var{"a.b"}
146or \var{"a.b.c.d"}. Choice of these names is entirely up to the developer
147who is using logging.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000148
149All calls to this function with a given name return the same logger instance.
150This means that logger instances never need to be passed between different
151parts of an application.
Skip Montanaro649698f2002-11-14 03:57:19 +0000152\end{funcdesc}
153
Vinay Sajipc6646c02004-09-22 12:55:16 +0000154\begin{funcdesc}{getLoggerClass}{}
155Return either the standard \class{Logger} class, or the last class passed to
156\function{setLoggerClass()}. This function may be called from within a new
157class definition, to ensure that installing a customised \class{Logger} class
158will not undo customisations already applied by other code. For example:
159
160\begin{verbatim}
161 class MyLogger(logging.getLoggerClass()):
162 # ... override behaviour here
163\end{verbatim}
164
165\end{funcdesc}
166
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000167\begin{funcdesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
168Logs a message with level \constant{DEBUG} on the root logger.
169The \var{msg} is the message format string, and the \var{args} are the
170arguments which are merged into \var{msg}. The only keyword argument in
171\var{kwargs} which is inspected is \var{exc_info} which, if it does not
Vinay Sajip1dc5b1e2004-10-03 19:10:05 +0000172evaluate as false, causes exception information to be added to the logging
173message. If an exception tuple (in the format returned by
174\function{sys.exc_info()}) is provided, it is used; otherwise,
175\function{sys.exc_info()} is called to get the exception information.
Skip Montanaro649698f2002-11-14 03:57:19 +0000176\end{funcdesc}
177
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000178\begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
179Logs a message with level \constant{INFO} on the root logger.
180The arguments are interpreted as for \function{debug()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000181\end{funcdesc}
182
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000183\begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
184Logs a message with level \constant{WARNING} on the root logger.
185The arguments are interpreted as for \function{debug()}.
186\end{funcdesc}
187
188\begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
189Logs a message with level \constant{ERROR} on the root logger.
190The arguments are interpreted as for \function{debug()}.
191\end{funcdesc}
192
193\begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
194Logs a message with level \constant{CRITICAL} on the root logger.
195The arguments are interpreted as for \function{debug()}.
196\end{funcdesc}
197
198\begin{funcdesc}{exception}{msg\optional{, *args}}
199Logs a message with level \constant{ERROR} on the root logger.
200The arguments are interpreted as for \function{debug()}. Exception info
201is added to the logging message. This function should only be called
202from an exception handler.
203\end{funcdesc}
204
Vinay Sajip739d49e2004-09-24 11:46:44 +0000205\begin{funcdesc}{log}{level, msg\optional{, *args\optional{, **kwargs}}}
206Logs a message with level \var{level} on the root logger.
207The other arguments are interpreted as for \function{debug()}.
208\end{funcdesc}
209
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000210\begin{funcdesc}{disable}{lvl}
211Provides an overriding level \var{lvl} for all loggers which takes
212precedence over the logger's own level. When the need arises to
213temporarily throttle logging output down across the whole application,
214this function can be useful.
215\end{funcdesc}
216
217\begin{funcdesc}{addLevelName}{lvl, levelName}
218Associates level \var{lvl} with text \var{levelName} in an internal
219dictionary, which is used to map numeric levels to a textual
220representation, for example when a \class{Formatter} formats a message.
221This function can also be used to define your own levels. The only
222constraints are that all levels used must be registered using this
223function, levels should be positive integers and they should increase
224in increasing order of severity.
225\end{funcdesc}
226
227\begin{funcdesc}{getLevelName}{lvl}
228Returns the textual representation of logging level \var{lvl}. If the
229level is one of the predefined levels \constant{CRITICAL},
230\constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG}
231then you get the corresponding string. If you have associated levels
232with names using \function{addLevelName()} then the name you have associated
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000233with \var{lvl} is returned. If a numeric value corresponding to one of the
234defined levels is passed in, the corresponding string representation is
235returned. Otherwise, the string "Level \%s" \% lvl is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000236\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000237
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000238\begin{funcdesc}{makeLogRecord}{attrdict}
239Creates and returns a new \class{LogRecord} instance whose attributes are
240defined by \var{attrdict}. This function is useful for taking a pickled
241\class{LogRecord} attribute dictionary, sent over a socket, and reconstituting
242it as a \class{LogRecord} instance at the receiving end.
243\end{funcdesc}
244
Skip Montanaro649698f2002-11-14 03:57:19 +0000245\begin{funcdesc}{basicConfig}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000246Does basic configuration for the logging system by creating a
247\class{StreamHandler} with a default \class{Formatter} and adding it to
248the root logger. The functions \function{debug()}, \function{info()},
249\function{warning()}, \function{error()} and \function{critical()} will call
250\function{basicConfig()} automatically if no handlers are defined for the
251root logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000252\end{funcdesc}
253
Skip Montanaro649698f2002-11-14 03:57:19 +0000254\begin{funcdesc}{shutdown}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000255Informs the logging system to perform an orderly shutdown by flushing and
256closing all handlers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000257\end{funcdesc}
258
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000259\begin{funcdesc}{setLoggerClass}{klass}
260Tells the logging system to use the class \var{klass} when instantiating a
261logger. The class should define \method{__init__()} such that only a name
262argument is required, and the \method{__init__()} should call
263\method{Logger.__init__()}. This function is typically called before any
264loggers are instantiated by applications which need to use custom logger
265behavior.
266\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000267
Fred Drake68e6d572003-01-28 22:02:35 +0000268
269\begin{seealso}
270 \seepep{282}{A Logging System}
271 {The proposal which described this feature for inclusion in
272 the Python standard library.}
Fred Drake11514792004-01-08 14:59:02 +0000273 \seelink{http://www.red-dove.com/python_logging.html}
274 {Original Python \module{logging} package}
275 {This is the original source for the \module{logging}
276 package. The version of the package available from this
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000277 site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x,
278 which do not include the \module{logging} package in the standard
Fred Drake11514792004-01-08 14:59:02 +0000279 library.}
Fred Drake68e6d572003-01-28 22:02:35 +0000280\end{seealso}
281
282
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000283\subsection{Logger Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000284
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000285Loggers have the following attributes and methods. Note that Loggers are
286never instantiated directly, but always through the module-level function
287\function{logging.getLogger(name)}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000288
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000289\begin{datadesc}{propagate}
290If this evaluates to false, logging messages are not passed by this
291logger or by child loggers to higher level (ancestor) loggers. The
292constructor sets this attribute to 1.
Skip Montanaro649698f2002-11-14 03:57:19 +0000293\end{datadesc}
294
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000295\begin{methoddesc}{setLevel}{lvl}
296Sets the threshold for this logger to \var{lvl}. Logging messages
297which are less severe than \var{lvl} will be ignored. When a logger is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000298created, the level is set to \constant{NOTSET} (which causes all messages
299to be processed in the root logger, or delegation to the parent in non-root
300loggers).
Skip Montanaro649698f2002-11-14 03:57:19 +0000301\end{methoddesc}
302
303\begin{methoddesc}{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000304Indicates if a message of severity \var{lvl} would be processed by
305this logger. This method checks first the module-level level set by
306\function{logging.disable(lvl)} and then the logger's effective level as
307determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000308\end{methoddesc}
309
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000310\begin{methoddesc}{getEffectiveLevel}{}
311Indicates the effective level for this logger. If a value other than
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000312\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000313Otherwise, the hierarchy is traversed towards the root until a value
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000314other than \constant{NOTSET} is found, and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000315\end{methoddesc}
316
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000317\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
318Logs a message with level \constant{DEBUG} on this logger.
319The \var{msg} is the message format string, and the \var{args} are the
320arguments which are merged into \var{msg}. The only keyword argument in
321\var{kwargs} which is inspected is \var{exc_info} which, if it does not
Vinay Sajip1dc5b1e2004-10-03 19:10:05 +0000322evaluate as false, causes exception information to be added to the logging
323message. If an exception tuple (as provided by \function{sys.exc_info()})
324is provided, it is used; otherwise, \function{sys.exc_info()} is called
325to get the exception information.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000326\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000327
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000328\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
329Logs a message with level \constant{INFO} on this logger.
330The arguments are interpreted as for \method{debug()}.
331\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000332
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000333\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
334Logs a message with level \constant{WARNING} on this logger.
335The arguments are interpreted as for \method{debug()}.
336\end{methoddesc}
337
338\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
339Logs a message with level \constant{ERROR} on this logger.
340The arguments are interpreted as for \method{debug()}.
341\end{methoddesc}
342
343\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
344Logs a message with level \constant{CRITICAL} on this logger.
345The arguments are interpreted as for \method{debug()}.
346\end{methoddesc}
347
348\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
Vinay Sajip1cf56d02004-08-04 08:36:44 +0000349Logs a message with integer level \var{lvl} on this logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000350The other arguments are interpreted as for \method{debug()}.
351\end{methoddesc}
352
353\begin{methoddesc}{exception}{msg\optional{, *args}}
354Logs a message with level \constant{ERROR} on this logger.
355The arguments are interpreted as for \method{debug()}. Exception info
356is added to the logging message. This method should only be called
357from an exception handler.
358\end{methoddesc}
359
360\begin{methoddesc}{addFilter}{filt}
361Adds the specified filter \var{filt} to this logger.
362\end{methoddesc}
363
364\begin{methoddesc}{removeFilter}{filt}
365Removes the specified filter \var{filt} from this logger.
366\end{methoddesc}
367
368\begin{methoddesc}{filter}{record}
369Applies this logger's filters to the record and returns a true value if
370the record is to be processed.
371\end{methoddesc}
372
373\begin{methoddesc}{addHandler}{hdlr}
374Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000375\end{methoddesc}
376
377\begin{methoddesc}{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000378Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000379\end{methoddesc}
380
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000381\begin{methoddesc}{findCaller}{}
382Finds the caller's source filename and line number. Returns the filename
383and line number as a 2-element tuple.
Skip Montanaro649698f2002-11-14 03:57:19 +0000384\end{methoddesc}
385
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000386\begin{methoddesc}{handle}{record}
387Handles a record by passing it to all handlers associated with this logger
388and its ancestors (until a false value of \var{propagate} is found).
389This method is used for unpickled records received from a socket, as well
390as those created locally. Logger-level filtering is applied using
391\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000392\end{methoddesc}
393
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000394\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info}
395This is a factory method which can be overridden in subclasses to create
396specialized \class{LogRecord} instances.
Skip Montanaro649698f2002-11-14 03:57:19 +0000397\end{methoddesc}
398
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000399\subsection{Basic example \label{minimal-example}}
400
401The \module{logging} package provides a lot of flexibility, and its
402configuration can appear daunting. This section demonstrates that simple
403use of the logging package is possible.
404
405The simplest example shows logging to the console:
406
407\begin{verbatim}
408import logging
409
410logging.debug('A debug message')
411logging.info('Some information')
412logging.warning('A shot across the bows')
413\end{verbatim}
414
415If you run the above script, you'll see this:
416\begin{verbatim}
417WARNING:root:A shot across the bows
418\end{verbatim}
419
420Because no particular logger was specified, the system used the root logger.
421The debug and info messages didn't appear because by default, the root
422logger is configured to only handle messages with a severity of WARNING
423or above. The message format is also a configuration default, as is the output
424destination of the messages - \code{sys.stderr}. The severity level,
425the message format and destination can be easily changed, as shown in
426the example below:
427
428\begin{verbatim}
429import logging
430
431logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000432 format='%(asctime)s %(levelname)s %(message)s',
433 filename='/tmp/myapp.log',
434 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000435logging.debug('A debug message')
436logging.info('Some information')
437logging.warning('A shot across the bows')
438\end{verbatim}
439
440The \method{basicConfig()} method is used to change the configuration
441defaults, which results in output (written to \code{/tmp/myapp.log})
442which should look something like the following:
443
444\begin{verbatim}
4452004-07-02 13:00:08,743 DEBUG A debug message
4462004-07-02 13:00:08,743 INFO Some information
4472004-07-02 13:00:08,743 WARNING A shot across the bows
448\end{verbatim}
449
450This time, all messages with a severity of DEBUG or above were handled,
451and the format of the messages was also changed, and output went to the
452specified file rather than the console.
453
454Formatting uses standard Python string formatting - see section
455\ref{typesseq-strings}. The format string takes the following
456common specifiers. For a complete list of specifiers, consult the
457\class{Formatter} documentation.
458
459\begin{tableii}{l|l}{code}{Format}{Description}
460\lineii{\%(name)s} {Name of the logger (logging channel).}
461\lineii{\%(levelname)s}{Text logging level for the message
462 (\code{'DEBUG'}, \code{'INFO'},
463 \code{'WARNING'}, \code{'ERROR'},
464 \code{'CRITICAL'}).}
465\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
466 was created. By default this is of the form
467 ``2003-07-08 16:49:45,896'' (the numbers after the
468 comma are millisecond portion of the time).}
469\lineii{\%(message)s} {The logged message.}
470\end{tableii}
471
472To change the date/time format, you can pass an additional keyword parameter,
473\var{datefmt}, as in the following:
474
475\begin{verbatim}
476import logging
477
478logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000479 format='%(asctime)s %(levelname)-8s %(message)s',
480 datefmt='%a, %d %b %Y %H:%M:%S',
481 filename='/temp/myapp.log',
482 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000483logging.debug('A debug message')
484logging.info('Some information')
485logging.warning('A shot across the bows')
486\end{verbatim}
487
488which would result in output like
489
490\begin{verbatim}
491Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
492Fri, 02 Jul 2004 13:06:18 INFO Some information
493Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
494\end{verbatim}
495
496The date format string follows the requirements of \function{strftime()} -
497see the documentation for the \refmodule{time} module.
498
499If, instead of sending logging output to the console or a file, you'd rather
500use a file-like object which you have created separately, you can pass it
501to \function{basicConfig()} using the \var{stream} keyword argument. Note
502that if both \var{stream} and \var{filename} keyword arguments are passed,
503the \var{stream} argument is ignored.
504
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000505Of course, you can put variable information in your output. To do this,
506simply have the message be a format string and pass in additional arguments
507containing the variable information, as in the following example:
508
509\begin{verbatim}
510import logging
511
512logging.basicConfig(level=logging.DEBUG,
513 format='%(asctime)s %(levelname)-8s %(message)s',
514 datefmt='%a, %d %b %Y %H:%M:%S',
515 filename='/temp/myapp.log',
516 filemode='w')
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000517logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000518\end{verbatim}
519
520which would result in
521
522\begin{verbatim}
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000523Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000524\end{verbatim}
525
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000526\subsection{Logging to multiple destinations \label{multiple-destinations}}
527
528Let's say you want to log to console and file with different message formats
529and in differing circumstances. Say you want to log messages with levels
530of DEBUG and higher to file, and those messages at level INFO and higher to
531the console. Let's also assume that the file should contain timestamps, but
532the console messages should not. Here's how you can achieve this:
533
534\begin{verbatim}
535import logging
536
Fred Drake048840c2004-10-29 14:35:42 +0000537# set up logging to file - see previous section for more details
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000538logging.basicConfig(level=logging.DEBUG,
539 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
540 datefmt='%m-%d %H:%M',
541 filename='/temp/myapp.log',
542 filemode='w')
Fred Drake048840c2004-10-29 14:35:42 +0000543# define a Handler which writes INFO messages or higher to the sys.stderr
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000544console = logging.StreamHandler()
545console.setLevel(logging.INFO)
Fred Drake048840c2004-10-29 14:35:42 +0000546# set a format which is simpler for console use
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000547formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Fred Drake048840c2004-10-29 14:35:42 +0000548# tell the handler to use this format
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000549console.setFormatter(formatter)
Fred Drake048840c2004-10-29 14:35:42 +0000550# add the handler to the root logger
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000551logging.getLogger('').addHandler(console)
552
Fred Drake048840c2004-10-29 14:35:42 +0000553# Now, we can log to the root logger, or any other logger. First the root...
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000554logging.info('Jackdaws love my big sphinx of quartz.')
555
Fred Drake048840c2004-10-29 14:35:42 +0000556# Now, define a couple of other loggers which might represent areas in your
557# application:
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000558
559logger1 = logging.getLogger('myapp.area1')
560logger2 = logging.getLogger('myapp.area2')
561
562logger1.debug('Quick zephyrs blow, vexing daft Jim.')
563logger1.info('How quickly daft jumping zebras vex.')
564logger2.warning('Jail zesty vixen who grabbed pay from quack.')
565logger2.error('The five boxing wizards jump quickly.')
566\end{verbatim}
567
568When you run this, on the console you will see
569
570\begin{verbatim}
571root : INFO Jackdaws love my big sphinx of quartz.
572myapp.area1 : INFO How quickly daft jumping zebras vex.
573myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
574myapp.area2 : ERROR The five boxing wizards jump quickly.
575\end{verbatim}
576
577and in the file you will see something like
578
579\begin{verbatim}
58010-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
58110-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
58210-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
58310-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
58410-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
585\end{verbatim}
586
587As you can see, the DEBUG message only shows up in the file. The other
588messages are sent to both destinations.
589
Vinay Sajip006483b2004-10-29 12:30:28 +0000590This example uses console and file handlers, but you can use any number and
591combination of handlers you choose.
592
593\subsection{Sending and receiving logging events across a network
594\label{network-logging}}
595
596Let's say you want to send logging events across a network, and handle them
597at the receiving end. A simple way of doing this is attaching a
598\class{SocketHandler} instance to the root logger at the sending end:
599
600\begin{verbatim}
601import logging, logging.handlers
602
603rootLogger = logging.getLogger('')
604rootLogger.setLevel(logging.DEBUG)
605socketHandler = logging.handlers.SocketHandler('localhost',
606 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
607# don't bother with a formatter, since a socket handler sends the event as
608# an unformatted pickle
609rootLogger.addHandler(socketHandler)
610
Fred Drake048840c2004-10-29 14:35:42 +0000611# Now, we can log to the root logger, or any other logger. First the root...
Vinay Sajip006483b2004-10-29 12:30:28 +0000612logging.info('Jackdaws love my big sphinx of quartz.')
613
Fred Drake048840c2004-10-29 14:35:42 +0000614# Now, define a couple of other loggers which might represent areas in your
615# application:
Vinay Sajip006483b2004-10-29 12:30:28 +0000616
617logger1 = logging.getLogger('myapp.area1')
618logger2 = logging.getLogger('myapp.area2')
619
620logger1.debug('Quick zephyrs blow, vexing daft Jim.')
621logger1.info('How quickly daft jumping zebras vex.')
622logger2.warning('Jail zesty vixen who grabbed pay from quack.')
623logger2.error('The five boxing wizards jump quickly.')
624\end{verbatim}
625
626At the receiving end, you can set up a receiver using the
627\module{SocketServer} module. Here is a basic working example:
628
629\begin{verbatim}
Fred Drake048840c2004-10-29 14:35:42 +0000630import cPickle
631import logging
632import logging.handlers
633import SocketServer
634import struct
Vinay Sajip006483b2004-10-29 12:30:28 +0000635
Vinay Sajip006483b2004-10-29 12:30:28 +0000636
Fred Drake048840c2004-10-29 14:35:42 +0000637class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
638 """Handler for a streaming logging request.
639
640 This basically logs the record using whatever logging policy is
641 configured locally.
Vinay Sajip006483b2004-10-29 12:30:28 +0000642 """
643
644 def handle(self):
645 """
646 Handle multiple requests - each expected to be a 4-byte length,
647 followed by the LogRecord in pickle format. Logs the record
648 according to whatever policy is configured locally.
649 """
650 while 1:
651 chunk = self.connection.recv(4)
652 if len(chunk) < 4:
653 break
654 slen = struct.unpack(">L", chunk)[0]
655 chunk = self.connection.recv(slen)
656 while len(chunk) < slen:
657 chunk = chunk + self.connection.recv(slen - len(chunk))
658 obj = self.unPickle(chunk)
659 record = logging.makeLogRecord(obj)
660 self.handleLogRecord(record)
661
662 def unPickle(self, data):
663 return cPickle.loads(data)
664
665 def handleLogRecord(self, record):
Fred Drake048840c2004-10-29 14:35:42 +0000666 # if a name is specified, we use the named logger rather than the one
667 # implied by the record.
Vinay Sajip006483b2004-10-29 12:30:28 +0000668 if self.server.logname is not None:
669 name = self.server.logname
670 else:
671 name = record.name
672 logger = logging.getLogger(name)
Fred Drake048840c2004-10-29 14:35:42 +0000673 # N.B. EVERY record gets logged. This is because Logger.handle
674 # is normally called AFTER logger-level filtering. If you want
675 # to do filtering, do it at the client end to save wasting
676 # cycles and network bandwidth!
Vinay Sajip006483b2004-10-29 12:30:28 +0000677 logger.handle(record)
678
Fred Drake048840c2004-10-29 14:35:42 +0000679class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
680 """simple TCP socket-based logging receiver suitable for testing.
Vinay Sajip006483b2004-10-29 12:30:28 +0000681 """
682
683 allow_reuse_address = 1
684
685 def __init__(self, host='localhost',
Fred Drake048840c2004-10-29 14:35:42 +0000686 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
687 handler=LogRecordStreamHandler):
688 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
Vinay Sajip006483b2004-10-29 12:30:28 +0000689 self.abort = 0
690 self.timeout = 1
691 self.logname = None
692
693 def serve_until_stopped(self):
694 import select
695 abort = 0
696 while not abort:
697 rd, wr, ex = select.select([self.socket.fileno()],
698 [], [],
699 self.timeout)
700 if rd:
701 self.handle_request()
702 abort = self.abort
703
704def main():
705 logging.basicConfig(
706 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s",
707 datefmt="%H:%M:%S")
708 tcpserver = LogRecordSocketReceiver()
709 print "About to start TCP server..."
710 tcpserver.serve_until_stopped()
711
712if __name__ == "__main__":
713 main()
714\end{verbatim}
715
716If you first run the server, and then the client. On the client side, nothing
717is printed on the client console; on the server side, you should see something
718like this:
719
720\begin{verbatim}
721About to start TCP server...
722 59 root INFO Jackdaws love my big sphinx of quartz.
723 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
724 69 myapp.area1 INFO How quickly daft jumping zebras vex.
725 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
726 69 myapp.area2 ERROR The five boxing wizards jump quickly.
727\end{verbatim}
728
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000729\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000730
Fred Drake68e6d572003-01-28 22:02:35 +0000731Handlers have the following attributes and methods. Note that
732\class{Handler} is never instantiated directly; this class acts as a
733base for more useful subclasses. However, the \method{__init__()}
734method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000735
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000736\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000737Initializes the \class{Handler} instance by setting its level, setting
738the list of filters to the empty list and creating a lock (using
Raymond Hettingerc75c3e02003-09-01 22:50:52 +0000739\method{createLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000740\end{methoddesc}
741
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000742\begin{methoddesc}{createLock}{}
743Initializes a thread lock which can be used to serialize access to
744underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000745\end{methoddesc}
746
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000747\begin{methoddesc}{acquire}{}
748Acquires the thread lock created with \method{createLock()}.
749\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000750
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000751\begin{methoddesc}{release}{}
752Releases the thread lock acquired with \method{acquire()}.
753\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000754
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000755\begin{methoddesc}{setLevel}{lvl}
756Sets the threshold for this handler to \var{lvl}. Logging messages which are
757less severe than \var{lvl} will be ignored. When a handler is created, the
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000758level is set to \constant{NOTSET} (which causes all messages to be processed).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000759\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000760
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000761\begin{methoddesc}{setFormatter}{form}
762Sets the \class{Formatter} for this handler to \var{form}.
763\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000764
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000765\begin{methoddesc}{addFilter}{filt}
766Adds the specified filter \var{filt} to this handler.
767\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000768
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000769\begin{methoddesc}{removeFilter}{filt}
770Removes the specified filter \var{filt} from this handler.
771\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000772
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000773\begin{methoddesc}{filter}{record}
774Applies this handler's filters to the record and returns a true value if
775the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000776\end{methoddesc}
777
778\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000779Ensure all logging output has been flushed. This version does
780nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000781\end{methoddesc}
782
Skip Montanaro649698f2002-11-14 03:57:19 +0000783\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000784Tidy up any resources used by the handler. This version does
785nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000786\end{methoddesc}
787
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000788\begin{methoddesc}{handle}{record}
789Conditionally emits the specified logging record, depending on
790filters which may have been added to the handler. Wraps the actual
791emission of the record with acquisition/release of the I/O thread
792lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000793\end{methoddesc}
794
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000795\begin{methoddesc}{handleError}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000796This method should be called from handlers when an exception is
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000797encountered during an \method{emit()} call. By default it does nothing,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000798which means that exceptions get silently ignored. This is what is
799mostly wanted for a logging system - most users will not care
800about errors in the logging system, they are more interested in
801application errors. You could, however, replace this with a custom
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000802handler if you wish. The specified record is the one which was being
803processed when the exception occurred.
Skip Montanaro649698f2002-11-14 03:57:19 +0000804\end{methoddesc}
805
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000806\begin{methoddesc}{format}{record}
807Do formatting for a record - if a formatter is set, use it.
808Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000809\end{methoddesc}
810
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000811\begin{methoddesc}{emit}{record}
812Do whatever it takes to actually log the specified logging record.
813This version is intended to be implemented by subclasses and so
814raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000815\end{methoddesc}
816
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000817\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000818
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000819The \class{StreamHandler} class sends logging output to streams such as
820\var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more
821precisely, any object which supports \method{write()} and \method{flush()}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000822methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000823
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000824\begin{classdesc}{StreamHandler}{\optional{strm}}
825Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
826specified, the instance will use it for logging output; otherwise,
827\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000828\end{classdesc}
829
830\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000831If a formatter is specified, it is used to format the record.
832The record is then written to the stream with a trailing newline.
833If exception information is present, it is formatted using
834\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000835\end{methoddesc}
836
837\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000838Flushes the stream by calling its \method{flush()} method. Note that
839the \method{close()} method is inherited from \class{Handler} and
840so does nothing, so an explicit \method{flush()} call may be needed
841at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000842\end{methoddesc}
843
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000844\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000845
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000846The \class{FileHandler} class sends logging output to a disk file.
Fred Drake68e6d572003-01-28 22:02:35 +0000847It inherits the output functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000848
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000849\begin{classdesc}{FileHandler}{filename\optional{, mode}}
850Returns a new instance of the \class{FileHandler} class. The specified
851file is opened and used as the stream for logging. If \var{mode} is
Fred Drake9a5b6a62003-07-08 15:38:40 +0000852not specified, \constant{'a'} is used. By default, the file grows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000853indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000854\end{classdesc}
855
856\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000857Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000858\end{methoddesc}
859
860\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000861Outputs the record to the file.
862\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000863
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000864\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000865
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000866The \class{RotatingFileHandler} class supports rotation of disk log files.
867
Fred Drake9a5b6a62003-07-08 15:38:40 +0000868\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{,
869 maxBytes\optional{, backupCount}}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000870Returns a new instance of the \class{RotatingFileHandler} class. The
871specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +0000872\var{mode} is not specified, \code{'a'} is used. By default, the
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000873file grows indefinitely.
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000874
875You can use the \var{maxBytes} and
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000876\var{backupCount} values to allow the file to \dfn{rollover} at a
877predetermined size. When the size is about to be exceeded, the file is
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000878closed and a new file is silently opened for output. Rollover occurs
879whenever the current log file is nearly \var{maxBytes} in length; if
880\var{maxBytes} is zero, rollover never occurs. If \var{backupCount}
881is non-zero, the system will save old log files by appending the
882extensions ".1", ".2" etc., to the filename. For example, with
883a \var{backupCount} of 5 and a base file name of
884\file{app.log}, you would get \file{app.log},
885\file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being
886written to is always \file{app.log}. When this file is filled, it is
887closed and renamed to \file{app.log.1}, and if files \file{app.log.1},
888\file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2},
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000889\file{app.log.3} etc. respectively.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000890\end{classdesc}
891
892\begin{methoddesc}{doRollover}{}
893Does a rollover, as described above.
894\end{methoddesc}
895
896\begin{methoddesc}{emit}{record}
Johannes Gijsbersf1643222004-11-07 16:11:35 +0000897Outputs the record to the file, catering for rollover as described previously.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000898\end{methoddesc}
899
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +0000900\subsubsection{TimedRotatingFileHandler}
901
902The \class{TimedRotatingFileHandler} class supports rotation of disk log files
903at certain timed intervals.
904
905\begin{classdesc}{TimedRotatingFileHandler}{filename
906 \optional{,when
907 \optional{,interval
908 \optional{,backupCount}}}}
909
910Returns a new instance of the \class{TimedRotatingFileHandler} class. The
911specified file is opened and used as the stream for logging. On rotating
912it also sets the filename suffix. Rotating happens based on the product
913of \var{when} and \var{interval}.
914
915You can use the \var{when} to specify the type of \var{interval}. The
916list of possible values is, note that they are not case sensitive:
917
918\begin{tableii}{l|l}{}{Value}{Type of interval}
919 \lineii{S}{Seconds}
920 \lineii{M}{Minutes}
921 \lineii{H}{Hours}
922 \lineii{D}{Days}
923 \lineii{W}{Week day (0=Monday)}
924 \lineii{midnight}{Roll over at midnight}
925\end{tableii}
926
927If \var{backupCount} is non-zero, the system will save old log files by
928appending the extensions ".1", ".2" etc., to the filename. For example,
929with a \var{backupCount} of 5 and a base file name of \file{app.log},
930you would get \file{app.log}, \file{app.log.1}, \file{app.log.2}, up to
931\file{app.log.5}. The file being written to is always \file{app.log}.
932When this file is filled, it is closed and renamed to \file{app.log.1},
933and if files \file{app.log.1}, \file{app.log.2}, etc. exist, then they
934are renamed to \file{app.log.2}, \file{app.log.3} etc. respectively.
935\end{classdesc}
936
937\begin{methoddesc}{doRollover}{}
938Does a rollover, as described above.
939\end{methoddesc}
940
941\begin{methoddesc}{emit}{record}
942Outputs the record to the file, catering for rollover as described
943above.
944\end{methoddesc}
945
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000946\subsubsection{SocketHandler}
947
948The \class{SocketHandler} class sends logging output to a network
949socket. The base class uses a TCP socket.
950
951\begin{classdesc}{SocketHandler}{host, port}
952Returns a new instance of the \class{SocketHandler} class intended to
953communicate with a remote machine whose address is given by \var{host}
954and \var{port}.
955\end{classdesc}
956
957\begin{methoddesc}{close}{}
958Closes the socket.
959\end{methoddesc}
960
961\begin{methoddesc}{handleError}{}
962\end{methoddesc}
963
964\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000965Pickles the record's attribute dictionary and writes it to the socket in
966binary format. If there is an error with the socket, silently drops the
967packet. If the connection was previously lost, re-establishes the connection.
Fred Drake6b3b0462004-04-09 18:26:40 +0000968To unpickle the record at the receiving end into a \class{LogRecord}, use the
969\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000970\end{methoddesc}
971
972\begin{methoddesc}{handleError}{}
973Handles an error which has occurred during \method{emit()}. The
974most likely cause is a lost connection. Closes the socket so that
975we can retry on the next event.
976\end{methoddesc}
977
978\begin{methoddesc}{makeSocket}{}
979This is a factory method which allows subclasses to define the precise
980type of socket they want. The default implementation creates a TCP
981socket (\constant{socket.SOCK_STREAM}).
982\end{methoddesc}
983
984\begin{methoddesc}{makePickle}{record}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000985Pickles the record's attribute dictionary in binary format with a length
986prefix, and returns it ready for transmission across the socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000987\end{methoddesc}
988
989\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000990Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000991for partial sends which can happen when the network is busy.
992\end{methoddesc}
993
994\subsubsection{DatagramHandler}
995
996The \class{DatagramHandler} class inherits from \class{SocketHandler}
997to support sending logging messages over UDP sockets.
998
999\begin{classdesc}{DatagramHandler}{host, port}
1000Returns a new instance of the \class{DatagramHandler} class intended to
1001communicate with a remote machine whose address is given by \var{host}
1002and \var{port}.
1003\end{classdesc}
1004
1005\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001006Pickles the record's attribute dictionary and writes it to the socket in
1007binary format. If there is an error with the socket, silently drops the
1008packet.
Fred Drake6b3b0462004-04-09 18:26:40 +00001009To unpickle the record at the receiving end into a \class{LogRecord}, use the
1010\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001011\end{methoddesc}
1012
1013\begin{methoddesc}{makeSocket}{}
1014The factory method of \class{SocketHandler} is here overridden to create
1015a UDP socket (\constant{socket.SOCK_DGRAM}).
1016\end{methoddesc}
1017
1018\begin{methoddesc}{send}{s}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001019Send a pickled string to a socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001020\end{methoddesc}
1021
1022\subsubsection{SysLogHandler}
1023
1024The \class{SysLogHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +00001025remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001026
1027\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
1028Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +00001029communicate with a remote \UNIX{} machine whose address is given by
1030\var{address} in the form of a \code{(\var{host}, \var{port})}
1031tuple. If \var{address} is not specified, \code{('localhost', 514)} is
1032used. The address is used to open a UDP socket. If \var{facility} is
1033not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001034\end{classdesc}
1035
1036\begin{methoddesc}{close}{}
1037Closes the socket to the remote host.
1038\end{methoddesc}
1039
1040\begin{methoddesc}{emit}{record}
1041The record is formatted, and then sent to the syslog server. If
1042exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +00001043\end{methoddesc}
1044
1045\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001046Encodes the facility and priority into an integer. You can pass in strings
1047or integers - if strings are passed, internal mapping dictionaries are used
1048to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +00001049\end{methoddesc}
1050
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001051\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +00001052
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001053The \class{NTEventLogHandler} class supports sending logging messages
1054to a local Windows NT, Windows 2000 or Windows XP event log. Before
1055you can use it, you need Mark Hammond's Win32 extensions for Python
1056installed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001057
Fred Drake9a5b6a62003-07-08 15:38:40 +00001058\begin{classdesc}{NTEventLogHandler}{appname\optional{,
1059 dllname\optional{, logtype}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001060Returns a new instance of the \class{NTEventLogHandler} class. The
1061\var{appname} is used to define the application name as it appears in the
1062event log. An appropriate registry entry is created using this name.
1063The \var{dllname} should give the fully qualified pathname of a .dll or .exe
1064which contains message definitions to hold in the log (if not specified,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001065\code{'win32service.pyd'} is used - this is installed with the Win32
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001066extensions and contains some basic placeholder message definitions.
1067Note that use of these placeholders will make your event logs big, as the
1068entire message source is held in the log. If you want slimmer logs, you have
1069to pass in the name of your own .dll or .exe which contains the message
1070definitions you want to use in the event log). The \var{logtype} is one of
Fred Drake9a5b6a62003-07-08 15:38:40 +00001071\code{'Application'}, \code{'System'} or \code{'Security'}, and
1072defaults to \code{'Application'}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001073\end{classdesc}
1074
1075\begin{methoddesc}{close}{}
1076At this point, you can remove the application name from the registry as a
1077source of event log entries. However, if you do this, you will not be able
1078to see the events as you intended in the Event Log Viewer - it needs to be
1079able to access the registry to get the .dll name. The current version does
1080not do this (in fact it doesn't do anything).
1081\end{methoddesc}
1082
1083\begin{methoddesc}{emit}{record}
1084Determines the message ID, event category and event type, and then logs the
1085message in the NT event log.
1086\end{methoddesc}
1087
1088\begin{methoddesc}{getEventCategory}{record}
1089Returns the event category for the record. Override this if you
1090want to specify your own categories. This version returns 0.
1091\end{methoddesc}
1092
1093\begin{methoddesc}{getEventType}{record}
1094Returns the event type for the record. Override this if you want
1095to specify your own types. This version does a mapping using the
1096handler's typemap attribute, which is set up in \method{__init__()}
1097to a dictionary which contains mappings for \constant{DEBUG},
1098\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
1099\constant{CRITICAL}. If you are using your own levels, you will either need
1100to override this method or place a suitable dictionary in the
1101handler's \var{typemap} attribute.
1102\end{methoddesc}
1103
1104\begin{methoddesc}{getMessageID}{record}
1105Returns the message ID for the record. If you are using your
1106own messages, you could do this by having the \var{msg} passed to the
1107logger being an ID rather than a format string. Then, in here,
1108you could use a dictionary lookup to get the message ID. This
1109version returns 1, which is the base message ID in
Fred Drake9a5b6a62003-07-08 15:38:40 +00001110\file{win32service.pyd}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001111\end{methoddesc}
1112
1113\subsubsection{SMTPHandler}
1114
1115The \class{SMTPHandler} class supports sending logging messages to an email
1116address via SMTP.
1117
1118\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
1119Returns a new instance of the \class{SMTPHandler} class. The
1120instance is initialized with the from and to addresses and subject
1121line of the email. The \var{toaddrs} should be a list of strings without
1122domain names (That's what the \var{mailhost} is for). To specify a
1123non-standard SMTP port, use the (host, port) tuple format for the
1124\var{mailhost} argument. If you use a string, the standard SMTP port
1125is used.
1126\end{classdesc}
1127
1128\begin{methoddesc}{emit}{record}
1129Formats the record and sends it to the specified addressees.
1130\end{methoddesc}
1131
1132\begin{methoddesc}{getSubject}{record}
1133If you want to specify a subject line which is record-dependent,
1134override this method.
1135\end{methoddesc}
1136
1137\subsubsection{MemoryHandler}
1138
1139The \class{MemoryHandler} supports buffering of logging records in memory,
1140periodically flushing them to a \dfn{target} handler. Flushing occurs
1141whenever the buffer is full, or when an event of a certain severity or
1142greater is seen.
1143
1144\class{MemoryHandler} is a subclass of the more general
1145\class{BufferingHandler}, which is an abstract class. This buffers logging
1146records in memory. Whenever each record is added to the buffer, a
1147check is made by calling \method{shouldFlush()} to see if the buffer
1148should be flushed. If it should, then \method{flush()} is expected to
1149do the needful.
1150
1151\begin{classdesc}{BufferingHandler}{capacity}
1152Initializes the handler with a buffer of the specified capacity.
1153\end{classdesc}
1154
1155\begin{methoddesc}{emit}{record}
1156Appends the record to the buffer. If \method{shouldFlush()} returns true,
1157calls \method{flush()} to process the buffer.
1158\end{methoddesc}
1159
1160\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001161You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001162just zaps the buffer to empty.
1163\end{methoddesc}
1164
1165\begin{methoddesc}{shouldFlush}{record}
1166Returns true if the buffer is up to capacity. This method can be
1167overridden to implement custom flushing strategies.
1168\end{methoddesc}
1169
1170\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001171\optional{, target}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001172Returns a new instance of the \class{MemoryHandler} class. The
1173instance is initialized with a buffer size of \var{capacity}. If
1174\var{flushLevel} is not specified, \constant{ERROR} is used. If no
1175\var{target} is specified, the target will need to be set using
1176\method{setTarget()} before this handler does anything useful.
1177\end{classdesc}
1178
1179\begin{methoddesc}{close}{}
1180Calls \method{flush()}, sets the target to \constant{None} and
1181clears the buffer.
1182\end{methoddesc}
1183
1184\begin{methoddesc}{flush}{}
1185For a \class{MemoryHandler}, flushing means just sending the buffered
1186records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001187different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001188\end{methoddesc}
1189
1190\begin{methoddesc}{setTarget}{target}
1191Sets the target handler for this handler.
1192\end{methoddesc}
1193
1194\begin{methoddesc}{shouldFlush}{record}
1195Checks for buffer full or a record at the \var{flushLevel} or higher.
1196\end{methoddesc}
1197
1198\subsubsection{HTTPHandler}
1199
1200The \class{HTTPHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +00001201Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001202
1203\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
1204Returns a new instance of the \class{HTTPHandler} class. The
1205instance is initialized with a host address, url and HTTP method.
Fred Drake68e6d572003-01-28 22:02:35 +00001206If no \var{method} is specified, \samp{GET} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001207\end{classdesc}
1208
1209\begin{methoddesc}{emit}{record}
1210Sends the record to the Web server as an URL-encoded dictionary.
1211\end{methoddesc}
1212
1213\subsection{Formatter Objects}
1214
1215\class{Formatter}s have the following attributes and methods. They are
1216responsible for converting a \class{LogRecord} to (usually) a string
1217which can be interpreted by either a human or an external system. The
1218base
1219\class{Formatter} allows a formatting string to be specified. If none is
Fred Drake8efc74d2004-04-15 06:18:48 +00001220supplied, the default value of \code{'\%(message)s'} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001221
1222A Formatter can be initialized with a format string which makes use of
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001223knowledge of the \class{LogRecord} attributes - such as the default value
1224mentioned above making use of the fact that the user's message and
Fred Drake6b3b0462004-04-09 18:26:40 +00001225arguments are pre-formatted into a \class{LogRecord}'s \var{message}
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001226attribute. This format string contains standard python \%-style
1227mapping keys. See section \ref{typesseq-strings}, ``String Formatting
1228Operations,'' for more information on string formatting.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001229
Fred Drake6b3b0462004-04-09 18:26:40 +00001230Currently, the useful mapping keys in a \class{LogRecord} are:
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001231
Fred Drake9a5b6a62003-07-08 15:38:40 +00001232\begin{tableii}{l|l}{code}{Format}{Description}
1233\lineii{\%(name)s} {Name of the logger (logging channel).}
1234\lineii{\%(levelno)s} {Numeric logging level for the message
1235 (\constant{DEBUG}, \constant{INFO},
1236 \constant{WARNING}, \constant{ERROR},
1237 \constant{CRITICAL}).}
1238\lineii{\%(levelname)s}{Text logging level for the message
1239 (\code{'DEBUG'}, \code{'INFO'},
1240 \code{'WARNING'}, \code{'ERROR'},
1241 \code{'CRITICAL'}).}
1242\lineii{\%(pathname)s} {Full pathname of the source file where the logging
1243 call was issued (if available).}
1244\lineii{\%(filename)s} {Filename portion of pathname.}
1245\lineii{\%(module)s} {Module (name portion of filename).}
1246\lineii{\%(lineno)d} {Source line number where the logging call was issued
1247 (if available).}
Fred Drake6b3b0462004-04-09 18:26:40 +00001248\lineii{\%(created)f} {Time when the \class{LogRecord} was created (as
Fred Drake9a5b6a62003-07-08 15:38:40 +00001249 returned by \function{time.time()}).}
Fred Drake6b3b0462004-04-09 18:26:40 +00001250\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
1251 was created. By default this is of the form
Fred Drake9a5b6a62003-07-08 15:38:40 +00001252 ``2003-07-08 16:49:45,896'' (the numbers after the
1253 comma are millisecond portion of the time).}
1254\lineii{\%(msecs)d} {Millisecond portion of the time when the
1255 \class{LogRecord} was created.}
1256\lineii{\%(thread)d} {Thread ID (if available).}
1257\lineii{\%(process)d} {Process ID (if available).}
1258\lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001259\end{tableii}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001260
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001261\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
1262Returns a new instance of the \class{Formatter} class. The
1263instance is initialized with a format string for the message as a whole,
1264as well as a format string for the date/time portion of a message. If
Neal Norwitzdd3afa72003-07-08 16:26:34 +00001265no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001266is specified, the ISO8601 date format is used.
1267\end{classdesc}
1268
1269\begin{methoddesc}{format}{record}
1270The record's attribute dictionary is used as the operand to a
1271string formatting operation. Returns the resulting string.
1272Before formatting the dictionary, a couple of preparatory steps
1273are carried out. The \var{message} attribute of the record is computed
1274using \var{msg} \% \var{args}. If the formatting string contains
Fred Drake9a5b6a62003-07-08 15:38:40 +00001275\code{'(asctime)'}, \method{formatTime()} is called to format the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001276event time. If there is exception information, it is formatted using
1277\method{formatException()} and appended to the message.
1278\end{methoddesc}
1279
1280\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
1281This method should be called from \method{format()} by a formatter which
1282wants to make use of a formatted time. This method can be overridden
1283in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001284basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +00001285it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001286record. Otherwise, the ISO8601 format is used. The resulting
1287string is returned.
1288\end{methoddesc}
1289
1290\begin{methoddesc}{formatException}{exc_info}
1291Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +00001292as returned by \function{sys.exc_info()}) as a string. This default
1293implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001294The resulting string is returned.
1295\end{methoddesc}
1296
1297\subsection{Filter Objects}
1298
1299\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
1300more sophisticated filtering than is provided by levels. The base filter
1301class only allows events which are below a certain point in the logger
1302hierarchy. For example, a filter initialized with "A.B" will allow events
1303logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
1304"B.A.B" etc. If initialized with the empty string, all events are passed.
1305
1306\begin{classdesc}{Filter}{\optional{name}}
1307Returns an instance of the \class{Filter} class. If \var{name} is specified,
1308it names a logger which, together with its children, will have its events
1309allowed through the filter. If no name is specified, allows every event.
1310\end{classdesc}
1311
1312\begin{methoddesc}{filter}{record}
1313Is the specified record to be logged? Returns zero for no, nonzero for
1314yes. If deemed appropriate, the record may be modified in-place by this
1315method.
1316\end{methoddesc}
1317
1318\subsection{LogRecord Objects}
1319
Fred Drake6b3b0462004-04-09 18:26:40 +00001320\class{LogRecord} instances are created every time something is logged. They
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001321contain all the information pertinent to the event being logged. The
1322main information passed in is in msg and args, which are combined
1323using msg \% args to create the message field of the record. The record
1324also includes information such as when the record was created, the
1325source line where the logging call was made, and any exception
1326information to be logged.
1327
Fred Drake6b3b0462004-04-09 18:26:40 +00001328\class{LogRecord} has no methods; it's just a repository for
1329information about the logging event. The only reason it's a class
1330rather than a dictionary is to facilitate extension.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001331
1332\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001333 exc_info}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001334Returns an instance of \class{LogRecord} initialized with interesting
1335information. The \var{name} is the logger name; \var{lvl} is the
1336numeric level; \var{pathname} is the absolute pathname of the source
1337file in which the logging call was made; \var{lineno} is the line
1338number in that file where the logging call is found; \var{msg} is the
1339user-supplied message (a format string); \var{args} is the tuple
1340which, together with \var{msg}, makes up the user message; and
1341\var{exc_info} is the exception tuple obtained by calling
1342\function{sys.exc_info() }(or \constant{None}, if no exception information
1343is available).
1344\end{classdesc}
1345
1346\subsection{Thread Safety}
1347
1348The logging module is intended to be thread-safe without any special work
1349needing to be done by its clients. It achieves this though using threading
1350locks; there is one lock to serialize access to the module's shared data,
1351and each handler also creates a lock to serialize access to its underlying
1352I/O.
1353
1354\subsection{Configuration}
1355
1356
Fred Drake94ffbb72004-04-08 19:44:31 +00001357\subsubsection{Configuration functions%
1358 \label{logging-config-api}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001359
Fred Drake9a5b6a62003-07-08 15:38:40 +00001360The following functions allow the logging module to be
1361configured. Before they can be used, you must import
1362\module{logging.config}. Their use is optional --- you can configure
1363the logging module entirely by making calls to the main API (defined
1364in \module{logging} itself) and defining handlers which are declared
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001365either in \module{logging} or \module{logging.handlers}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001366
1367\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
1368Reads the logging configuration from a ConfigParser-format file named
1369\var{fname}. This function can be called several times from an application,
1370allowing an end user the ability to select from various pre-canned
1371configurations (if the developer provides a mechanism to present the
1372choices and load the chosen configuration). Defaults to be passed to
1373ConfigParser can be specified in the \var{defaults} argument.
1374\end{funcdesc}
1375
1376\begin{funcdesc}{listen}{\optional{port}}
1377Starts up a socket server on the specified port, and listens for new
1378configurations. If no port is specified, the module's default
1379\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
1380will be sent as a file suitable for processing by \function{fileConfig()}.
1381Returns a \class{Thread} instance on which you can call \method{start()}
1382to start the server, and which you can \method{join()} when appropriate.
1383To stop the server, call \function{stopListening()}.
1384\end{funcdesc}
1385
1386\begin{funcdesc}{stopListening}{}
1387Stops the listening server which was created with a call to
1388\function{listen()}. This is typically called before calling \method{join()}
1389on the return value from \function{listen()}.
1390\end{funcdesc}
1391
Fred Drake94ffbb72004-04-08 19:44:31 +00001392\subsubsection{Configuration file format%
1393 \label{logging-config-fileformat}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001394
Fred Drake6b3b0462004-04-09 18:26:40 +00001395The configuration file format understood by \function{fileConfig()} is
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001396based on ConfigParser functionality. The file must contain sections
1397called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
1398which identify by name the entities of each type which are defined in
1399the file. For each such entity, there is a separate section which
1400identified how that entity is configured. Thus, for a logger named
1401\code{log01} in the \code{[loggers]} section, the relevant
1402configuration details are held in a section
1403\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
1404the \code{[handlers]} section will have its configuration held in a
1405section called \code{[handler_hand01]}, while a formatter called
1406\code{form01} in the \code{[formatters]} section will have its
1407configuration specified in a section called
1408\code{[formatter_form01]}. The root logger configuration must be
1409specified in a section called \code{[logger_root]}.
1410
1411Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001412
1413\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001414[loggers]
1415keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +00001416
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001417[handlers]
1418keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1419
1420[formatters]
1421keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +00001422\end{verbatim}
1423
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001424The root logger must specify a level and a list of handlers. An
1425example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001426
1427\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001428[logger_root]
1429level=NOTSET
1430handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +00001431\end{verbatim}
1432
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001433The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1434ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1435\code{NOTSET} means that all messages will be logged. Level values are
1436\function{eval()}uated in the context of the \code{logging} package's
1437namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +00001438
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001439The \code{handlers} entry is a comma-separated list of handler names,
1440which must appear in the \code{[handlers]} section. These names must
1441appear in the \code{[handlers]} section and have corresponding
1442sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +00001443
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001444For loggers other than the root logger, some additional information is
1445required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +00001446
1447\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001448[logger_parser]
1449level=DEBUG
1450handlers=hand01
1451propagate=1
1452qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001453\end{verbatim}
1454
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001455The \code{level} and \code{handlers} entries are interpreted as for
1456the root logger, except that if a non-root logger's level is specified
1457as \code{NOTSET}, the system consults loggers higher up the hierarchy
1458to determine the effective level of the logger. The \code{propagate}
1459entry is set to 1 to indicate that messages must propagate to handlers
1460higher up the logger hierarchy from this logger, or 0 to indicate that
1461messages are \strong{not} propagated to handlers up the hierarchy. The
1462\code{qualname} entry is the hierarchical channel name of the logger,
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001463that is to say the name used by the application to get the logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001464
1465Sections which specify handler configuration are exemplified by the
1466following.
1467
Skip Montanaro649698f2002-11-14 03:57:19 +00001468\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001469[handler_hand01]
1470class=StreamHandler
1471level=NOTSET
1472formatter=form01
1473args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001474\end{verbatim}
1475
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001476The \code{class} entry indicates the handler's class (as determined by
1477\function{eval()} in the \code{logging} package's namespace). The
1478\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1479to mean "log everything".
1480
1481The \code{formatter} entry indicates the key name of the formatter for
1482this handler. If blank, a default formatter
1483(\code{logging._defaultFormatter}) is used. If a name is specified, it
1484must appear in the \code{[formatters]} section and have a
1485corresponding section in the configuration file.
1486
1487The \code{args} entry, when \function{eval()}uated in the context of
1488the \code{logging} package's namespace, is the list of arguments to
1489the constructor for the handler class. Refer to the constructors for
1490the relevant handlers, or to the examples below, to see how typical
1491entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001492
1493\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001494[handler_hand02]
1495class=FileHandler
1496level=DEBUG
1497formatter=form02
1498args=('python.log', 'w')
1499
1500[handler_hand03]
1501class=handlers.SocketHandler
1502level=INFO
1503formatter=form03
1504args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1505
1506[handler_hand04]
1507class=handlers.DatagramHandler
1508level=WARN
1509formatter=form04
1510args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1511
1512[handler_hand05]
1513class=handlers.SysLogHandler
1514level=ERROR
1515formatter=form05
1516args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1517
1518[handler_hand06]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001519class=handlers.NTEventLogHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001520level=CRITICAL
1521formatter=form06
1522args=('Python Application', '', 'Application')
1523
1524[handler_hand07]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001525class=handlers.SMTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001526level=WARN
1527formatter=form07
1528args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1529
1530[handler_hand08]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001531class=handlers.MemoryHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001532level=NOTSET
1533formatter=form08
1534target=
1535args=(10, ERROR)
1536
1537[handler_hand09]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001538class=handlers.HTTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001539level=NOTSET
1540formatter=form09
1541args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001542\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001543
1544Sections which specify formatter configuration are typified by the following.
1545
1546\begin{verbatim}
1547[formatter_form01]
1548format=F1 %(asctime)s %(levelname)s %(message)s
1549datefmt=
1550\end{verbatim}
1551
1552The \code{format} entry is the overall format string, and the
1553\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1554string. If empty, the package substitutes ISO8601 format date/times, which
1555is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1556The ISO8601 format also specifies milliseconds, which are appended to the
1557result of using the above format string, with a comma separator. An example
1558time in ISO8601 format is \code{2003-01-23 00:29:50,411}.