blob: 63293d6e4a1428687a27f8031f88d126b3a8db08 [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
Vinay Sajipe8fdc452004-12-02 21:27:42 +000038The numeric values of logging levels are given in the following table. These
39are primarily of interest if you want to define your own levels, and need
40them to have specific values relative to the predefined levels. If you
41define a level with the same numeric value, it overwrites the predefined
42value; the predefined name is lost.
43
44\begin{tableii}{l|l}{code}{Level}{Numeric value}
45 \lineii{CRITICAL}{50}
46 \lineii{ERROR}{40}
47 \lineii{WARNING}{30}
48 \lineii{INFO}{20}
49 \lineii{DEBUG}{10}
50 \lineii{NOTSET}{0}
51\end{tableii}
52
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000053Levels can also be associated with loggers, being set either by the
54developer or through loading a saved logging configuration. When a
55logging method is called on a logger, the logger compares its own
56level with the level associated with the method call. If the logger's
57level is higher than the method call's, no logging message is actually
58generated. This is the basic mechanism controlling the verbosity of
59logging output.
Skip Montanaro649698f2002-11-14 03:57:19 +000060
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000061Logging messages are encoded as instances of the \class{LogRecord} class.
Georg Brandl0f194232006-01-01 21:35:20 +000062When a logger decides to actually log an event, a \class{LogRecord}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000063instance is created from the logging message.
Skip Montanaro649698f2002-11-14 03:57:19 +000064
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000065Logging messages are subjected to a dispatch mechanism through the
66use of \dfn{handlers}, which are instances of subclasses of the
67\class{Handler} class. Handlers are responsible for ensuring that a logged
68message (in the form of a \class{LogRecord}) ends up in a particular
69location (or set of locations) which is useful for the target audience for
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +000070that message (such as end users, support desk staff, system administrators,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000071developers). Handlers are passed \class{LogRecord} instances intended for
72particular destinations. Each logger can have zero, one or more handlers
Fred Drake6b3b0462004-04-09 18:26:40 +000073associated with it (via the \method{addHandler()} method of \class{Logger}).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000074In addition to any handlers directly associated with a logger,
Fred Drakec23e0192003-01-28 22:09:16 +000075\emph{all handlers associated with all ancestors of the logger} are
76called to dispatch the message.
Skip Montanaro649698f2002-11-14 03:57:19 +000077
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000078Just as for loggers, handlers can have levels associated with them.
79A handler's level acts as a filter in the same way as a logger's level does.
Fred Drakec23e0192003-01-28 22:09:16 +000080If a handler decides to actually dispatch an event, the \method{emit()} method
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000081is used to send the message to its destination. Most user-defined subclasses
Fred Drakec23e0192003-01-28 22:09:16 +000082of \class{Handler} will need to override this \method{emit()}.
Skip Montanaro649698f2002-11-14 03:57:19 +000083
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000084In addition to the base \class{Handler} class, many useful subclasses
85are provided:
Skip Montanaro649698f2002-11-14 03:57:19 +000086
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000087\begin{enumerate}
Skip Montanaro649698f2002-11-14 03:57:19 +000088
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000089\item \class{StreamHandler} instances send error messages to
90streams (file-like objects).
Skip Montanaro649698f2002-11-14 03:57:19 +000091
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000092\item \class{FileHandler} instances send error messages to disk
93files.
94
Andrew M. Kuchlinge0245142005-08-18 21:45:31 +000095\item \class{BaseRotatingHandler} is the base class for handlers that
Johannes Gijsbersf1643222004-11-07 16:11:35 +000096rotate log files at a certain point. It is not meant to be instantiated
Vinay Sajipedde4922004-11-11 13:54:48 +000097directly. Instead, use \class{RotatingFileHandler} or
98\class{TimedRotatingFileHandler}.
Johannes Gijsbersf1643222004-11-07 16:11:35 +000099
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000100\item \class{RotatingFileHandler} instances send error messages to disk
101files, with support for maximum log file sizes and log file rotation.
102
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +0000103\item \class{TimedRotatingFileHandler} instances send error messages to
104disk files rotating the log file at certain timed intervals.
105
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000106\item \class{SocketHandler} instances send error messages to
107TCP/IP sockets.
108
109\item \class{DatagramHandler} instances send error messages to UDP
110sockets.
111
112\item \class{SMTPHandler} instances send error messages to a
113designated email address.
114
115\item \class{SysLogHandler} instances send error messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000116\UNIX{} syslog daemon, possibly on a remote machine.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000117
118\item \class{NTEventLogHandler} instances send error messages to a
119Windows NT/2000/XP event log.
120
121\item \class{MemoryHandler} instances send error messages to a
122buffer in memory, which is flushed whenever specific criteria are
123met.
124
125\item \class{HTTPHandler} instances send error messages to an
Fred Drake68e6d572003-01-28 22:02:35 +0000126HTTP server using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000127
128\end{enumerate}
129
130The \class{StreamHandler} and \class{FileHandler} classes are defined
131in the core logging package. The other handlers are defined in a sub-
132module, \module{logging.handlers}. (There is also another sub-module,
133\module{logging.config}, for configuration functionality.)
134
135Logged messages are formatted for presentation through instances of the
136\class{Formatter} class. They are initialized with a format string
137suitable for use with the \% operator and a dictionary.
138
139For formatting multiple messages in a batch, instances of
140\class{BufferingFormatter} can be used. In addition to the format string
141(which is applied to each message in the batch), there is provision for
142header and trailer format strings.
143
144When filtering based on logger level and/or handler level is not enough,
145instances of \class{Filter} can be added to both \class{Logger} and
Fred Drakec23e0192003-01-28 22:09:16 +0000146\class{Handler} instances (through their \method{addFilter()} method).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000147Before deciding to process a message further, both loggers and handlers
148consult all their filters for permission. If any filter returns a false
149value, the message is not processed further.
150
151The basic \class{Filter} functionality allows filtering by specific logger
152name. If this feature is used, messages sent to the named logger and its
153children are allowed through the filter, and all others dropped.
154
155In addition to the classes described above, there are a number of module-
156level functions.
157
158\begin{funcdesc}{getLogger}{\optional{name}}
159Return a logger with the specified name or, if no name is specified, return
Vinay Sajip17952b72004-08-31 10:21:51 +0000160a logger which is the root logger of the hierarchy. If specified, the name
161is typically a dot-separated hierarchical name like \var{"a"}, \var{"a.b"}
162or \var{"a.b.c.d"}. Choice of these names is entirely up to the developer
163who is using logging.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000164
165All calls to this function with a given name return the same logger instance.
166This means that logger instances never need to be passed between different
167parts of an application.
Skip Montanaro649698f2002-11-14 03:57:19 +0000168\end{funcdesc}
169
Vinay Sajipc6646c02004-09-22 12:55:16 +0000170\begin{funcdesc}{getLoggerClass}{}
171Return either the standard \class{Logger} class, or the last class passed to
172\function{setLoggerClass()}. This function may be called from within a new
173class definition, to ensure that installing a customised \class{Logger} class
174will not undo customisations already applied by other code. For example:
175
176\begin{verbatim}
177 class MyLogger(logging.getLoggerClass()):
178 # ... override behaviour here
179\end{verbatim}
180
181\end{funcdesc}
182
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000183\begin{funcdesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
184Logs a message with level \constant{DEBUG} on the root logger.
185The \var{msg} is the message format string, and the \var{args} are the
Vinay Sajipb4549c42006-02-09 08:54:11 +0000186arguments which are merged into \var{msg} using the string formatting
187operator. (Note that this means that you can use keywords in the
188format string, together with a single dictionary argument.)
189
190There are two keyword arguments in \var{kwargs} which are inspected:
191\var{exc_info} which, if it does not evaluate as false, causes exception
192information to be added to the logging message. If an exception tuple (in the
193format returned by \function{sys.exc_info()}) is provided, it is used;
194otherwise, \function{sys.exc_info()} is called to get the exception
195information.
196
197The other optional keyword argument is \var{extra} which can be used to pass
198a dictionary which is used to populate the __dict__ of the LogRecord created
199for the logging event with user-defined attributes. These custom attributes
200can then be used as you like. For example, they could be incorporated into
201logged messages. For example:
202
203\begin{verbatim}
204 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
205 logging.basicConfig(format=FORMAT)
206 dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
207 logging.warning("Protocol problem: %s", "connection reset", extra=d)
208\end{verbatim}
209
210would print something like
211\begin{verbatim}
2122006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
213\end{verbatim}
214
215The keys in the dictionary passed in \var{extra} should not clash with the keys
216used by the logging system. (See the \class{Formatter} documentation for more
217information on which keys are used by the logging system.)
218
219If you choose to use these attributes in logged messages, you need to exercise
220some care. In the above example, for instance, the \class{Formatter} has been
221set up with a format string which expects 'clientip' and 'user' in the
222attribute dictionary of the LogRecord. If these are missing, the message will
223not be logged because a string formatting exception will occur. So in this
224case, you always need to pass the \var{extra} dictionary with these keys.
225
226While this might be annoying, this feature is intended for use in specialized
227circumstances, such as multi-threaded servers where the same code executes
228in many contexts, and interesting conditions which arise are dependent on this
229context (such as remote client IP address and authenticated user name, in the
230above example). In such circumstances, it is likely that specialized
231\class{Formatter}s would be used with particular \class{Handler}s.
Skip Montanaro649698f2002-11-14 03:57:19 +0000232\end{funcdesc}
233
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000234\begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
235Logs a message with level \constant{INFO} on the root logger.
236The arguments are interpreted as for \function{debug()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000237\end{funcdesc}
238
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000239\begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
240Logs a message with level \constant{WARNING} on the root logger.
241The arguments are interpreted as for \function{debug()}.
242\end{funcdesc}
243
244\begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
245Logs a message with level \constant{ERROR} on the root logger.
246The arguments are interpreted as for \function{debug()}.
247\end{funcdesc}
248
249\begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
250Logs a message with level \constant{CRITICAL} on the root logger.
251The arguments are interpreted as for \function{debug()}.
252\end{funcdesc}
253
254\begin{funcdesc}{exception}{msg\optional{, *args}}
255Logs a message with level \constant{ERROR} on the root logger.
256The arguments are interpreted as for \function{debug()}. Exception info
257is added to the logging message. This function should only be called
258from an exception handler.
259\end{funcdesc}
260
Vinay Sajip739d49e2004-09-24 11:46:44 +0000261\begin{funcdesc}{log}{level, msg\optional{, *args\optional{, **kwargs}}}
262Logs a message with level \var{level} on the root logger.
263The other arguments are interpreted as for \function{debug()}.
264\end{funcdesc}
265
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000266\begin{funcdesc}{disable}{lvl}
267Provides an overriding level \var{lvl} for all loggers which takes
268precedence over the logger's own level. When the need arises to
269temporarily throttle logging output down across the whole application,
270this function can be useful.
271\end{funcdesc}
272
273\begin{funcdesc}{addLevelName}{lvl, levelName}
274Associates level \var{lvl} with text \var{levelName} in an internal
275dictionary, which is used to map numeric levels to a textual
276representation, for example when a \class{Formatter} formats a message.
277This function can also be used to define your own levels. The only
278constraints are that all levels used must be registered using this
279function, levels should be positive integers and they should increase
280in increasing order of severity.
281\end{funcdesc}
282
283\begin{funcdesc}{getLevelName}{lvl}
284Returns the textual representation of logging level \var{lvl}. If the
285level is one of the predefined levels \constant{CRITICAL},
286\constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG}
287then you get the corresponding string. If you have associated levels
288with names using \function{addLevelName()} then the name you have associated
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000289with \var{lvl} is returned. If a numeric value corresponding to one of the
290defined levels is passed in, the corresponding string representation is
291returned. Otherwise, the string "Level \%s" \% lvl is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000292\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000293
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000294\begin{funcdesc}{makeLogRecord}{attrdict}
295Creates and returns a new \class{LogRecord} instance whose attributes are
296defined by \var{attrdict}. This function is useful for taking a pickled
297\class{LogRecord} attribute dictionary, sent over a socket, and reconstituting
298it as a \class{LogRecord} instance at the receiving end.
299\end{funcdesc}
300
Vinay Sajipc320c222005-07-29 11:52:19 +0000301\begin{funcdesc}{basicConfig}{\optional{**kwargs}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000302Does basic configuration for the logging system by creating a
303\class{StreamHandler} with a default \class{Formatter} and adding it to
304the root logger. The functions \function{debug()}, \function{info()},
305\function{warning()}, \function{error()} and \function{critical()} will call
306\function{basicConfig()} automatically if no handlers are defined for the
307root logger.
Vinay Sajipc320c222005-07-29 11:52:19 +0000308
309\versionchanged[Formerly, \function{basicConfig} did not take any keyword
310arguments]{2.4}
311
312The following keyword arguments are supported.
313
314\begin{tableii}{l|l}{code}{Format}{Description}
315\lineii{filename}{Specifies that a FileHandler be created, using the
316specified filename, rather than a StreamHandler.}
317\lineii{filemode}{Specifies the mode to open the file, if filename is
318specified (if filemode is unspecified, it defaults to 'a').}
319\lineii{format}{Use the specified format string for the handler.}
320\lineii{datefmt}{Use the specified date/time format.}
321\lineii{level}{Set the root logger level to the specified level.}
322\lineii{stream}{Use the specified stream to initialize the StreamHandler.
323Note that this argument is incompatible with 'filename' - if both
324are present, 'stream' is ignored.}
325\end{tableii}
326
Skip Montanaro649698f2002-11-14 03:57:19 +0000327\end{funcdesc}
328
Skip Montanaro649698f2002-11-14 03:57:19 +0000329\begin{funcdesc}{shutdown}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000330Informs the logging system to perform an orderly shutdown by flushing and
331closing all handlers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000332\end{funcdesc}
333
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000334\begin{funcdesc}{setLoggerClass}{klass}
335Tells the logging system to use the class \var{klass} when instantiating a
336logger. The class should define \method{__init__()} such that only a name
337argument is required, and the \method{__init__()} should call
338\method{Logger.__init__()}. This function is typically called before any
339loggers are instantiated by applications which need to use custom logger
340behavior.
341\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000342
Fred Drake68e6d572003-01-28 22:02:35 +0000343
344\begin{seealso}
345 \seepep{282}{A Logging System}
346 {The proposal which described this feature for inclusion in
347 the Python standard library.}
Fred Drake11514792004-01-08 14:59:02 +0000348 \seelink{http://www.red-dove.com/python_logging.html}
349 {Original Python \module{logging} package}
350 {This is the original source for the \module{logging}
351 package. The version of the package available from this
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000352 site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x,
353 which do not include the \module{logging} package in the standard
Fred Drake11514792004-01-08 14:59:02 +0000354 library.}
Fred Drake68e6d572003-01-28 22:02:35 +0000355\end{seealso}
356
357
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000358\subsection{Logger Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000359
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000360Loggers have the following attributes and methods. Note that Loggers are
361never instantiated directly, but always through the module-level function
362\function{logging.getLogger(name)}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000363
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000364\begin{datadesc}{propagate}
365If this evaluates to false, logging messages are not passed by this
366logger or by child loggers to higher level (ancestor) loggers. The
367constructor sets this attribute to 1.
Skip Montanaro649698f2002-11-14 03:57:19 +0000368\end{datadesc}
369
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000370\begin{methoddesc}{setLevel}{lvl}
371Sets the threshold for this logger to \var{lvl}. Logging messages
372which are less severe than \var{lvl} will be ignored. When a logger is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000373created, the level is set to \constant{NOTSET} (which causes all messages
Vinay Sajipe8fdc452004-12-02 21:27:42 +0000374to be processed when the logger is the root logger, or delegation to the
375parent when the logger is a non-root logger). Note that the root logger
376is created with level \constant{WARNING}.
Vinay Sajipd1c02392005-09-26 00:14:46 +0000377
378The term "delegation to the parent" means that if a logger has a level
379of NOTSET, its chain of ancestor loggers is traversed until either an
380ancestor with a level other than NOTSET is found, or the root is
381reached.
382
383If an ancestor is found with a level other than NOTSET, then that
384ancestor's level is treated as the effective level of the logger where
385the ancestor search began, and is used to determine how a logging
386event is handled.
387
388If the root is reached, and it has a level of NOTSET, then all
389messages will be processed. Otherwise, the root's level will be used
390as the effective level.
Skip Montanaro649698f2002-11-14 03:57:19 +0000391\end{methoddesc}
392
393\begin{methoddesc}{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000394Indicates if a message of severity \var{lvl} would be processed by
395this logger. This method checks first the module-level level set by
396\function{logging.disable(lvl)} and then the logger's effective level as
397determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000398\end{methoddesc}
399
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000400\begin{methoddesc}{getEffectiveLevel}{}
401Indicates the effective level for this logger. If a value other than
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000402\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000403Otherwise, the hierarchy is traversed towards the root until a value
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000404other than \constant{NOTSET} is found, and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000405\end{methoddesc}
406
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000407\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
408Logs a message with level \constant{DEBUG} on this logger.
409The \var{msg} is the message format string, and the \var{args} are the
Vinay Sajipb4549c42006-02-09 08:54:11 +0000410arguments which are merged into \var{msg} using the string formatting
411operator. (Note that this means that you can use keywords in the
412format string, together with a single dictionary argument.)
413
414There are two keyword arguments in \var{kwargs} which are inspected:
415\var{exc_info} which, if it does not evaluate as false, causes exception
416information to be added to the logging message. If an exception tuple (in the
417format returned by \function{sys.exc_info()}) is provided, it is used;
418otherwise, \function{sys.exc_info()} is called to get the exception
419information.
420
421The other optional keyword argument is \var{extra} which can be used to pass
422a dictionary which is used to populate the __dict__ of the LogRecord created
423for the logging event with user-defined attributes. These custom attributes
424can then be used as you like. For example, they could be incorporated into
425logged messages. For example:
426
427\begin{verbatim}
428 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
429 logging.basicConfig(format=FORMAT)
430 dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
431 logger = logging.getLogger("tcpserver")
432 logger.warning("Protocol problem: %s", "connection reset", extra=d)
433\end{verbatim}
434
435would print something like
436\begin{verbatim}
4372006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
438\end{verbatim}
439
440The keys in the dictionary passed in \var{extra} should not clash with the keys
441used by the logging system. (See the \class{Formatter} documentation for more
442information on which keys are used by the logging system.)
443
444If you choose to use these attributes in logged messages, you need to exercise
445some care. In the above example, for instance, the \class{Formatter} has been
446set up with a format string which expects 'clientip' and 'user' in the
447attribute dictionary of the LogRecord. If these are missing, the message will
448not be logged because a string formatting exception will occur. So in this
449case, you always need to pass the \var{extra} dictionary with these keys.
450
451While this might be annoying, this feature is intended for use in specialized
452circumstances, such as multi-threaded servers where the same code executes
453in many contexts, and interesting conditions which arise are dependent on this
454context (such as remote client IP address and authenticated user name, in the
455above example). In such circumstances, it is likely that specialized
456\class{Formatter}s would be used with particular \class{Handler}s.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000457\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000458
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000459\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
460Logs a message with level \constant{INFO} on this logger.
461The arguments are interpreted as for \method{debug()}.
462\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000463
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000464\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
465Logs a message with level \constant{WARNING} on this logger.
466The arguments are interpreted as for \method{debug()}.
467\end{methoddesc}
468
469\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
470Logs a message with level \constant{ERROR} on this logger.
471The arguments are interpreted as for \method{debug()}.
472\end{methoddesc}
473
474\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
475Logs a message with level \constant{CRITICAL} on this logger.
476The arguments are interpreted as for \method{debug()}.
477\end{methoddesc}
478
479\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
Vinay Sajip1cf56d02004-08-04 08:36:44 +0000480Logs a message with integer level \var{lvl} on this logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000481The other arguments are interpreted as for \method{debug()}.
482\end{methoddesc}
483
484\begin{methoddesc}{exception}{msg\optional{, *args}}
485Logs a message with level \constant{ERROR} on this logger.
486The arguments are interpreted as for \method{debug()}. Exception info
487is added to the logging message. This method should only be called
488from an exception handler.
489\end{methoddesc}
490
491\begin{methoddesc}{addFilter}{filt}
492Adds the specified filter \var{filt} to this logger.
493\end{methoddesc}
494
495\begin{methoddesc}{removeFilter}{filt}
496Removes the specified filter \var{filt} from this logger.
497\end{methoddesc}
498
499\begin{methoddesc}{filter}{record}
500Applies this logger's filters to the record and returns a true value if
501the record is to be processed.
502\end{methoddesc}
503
504\begin{methoddesc}{addHandler}{hdlr}
505Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000506\end{methoddesc}
507
508\begin{methoddesc}{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000509Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000510\end{methoddesc}
511
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000512\begin{methoddesc}{findCaller}{}
513Finds the caller's source filename and line number. Returns the filename
514and line number as a 2-element tuple.
Skip Montanaro649698f2002-11-14 03:57:19 +0000515\end{methoddesc}
516
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000517\begin{methoddesc}{handle}{record}
518Handles a record by passing it to all handlers associated with this logger
519and its ancestors (until a false value of \var{propagate} is found).
520This method is used for unpickled records received from a socket, as well
521as those created locally. Logger-level filtering is applied using
522\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000523\end{methoddesc}
524
Vinay Sajipb4549c42006-02-09 08:54:11 +0000525\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info,
526 func, extra}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000527This is a factory method which can be overridden in subclasses to create
528specialized \class{LogRecord} instances.
Skip Montanaro649698f2002-11-14 03:57:19 +0000529\end{methoddesc}
530
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000531\subsection{Basic example \label{minimal-example}}
532
Vinay Sajipc320c222005-07-29 11:52:19 +0000533\versionchanged[formerly \function{basicConfig} did not take any keyword
534arguments]{2.4}
535
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000536The \module{logging} package provides a lot of flexibility, and its
537configuration can appear daunting. This section demonstrates that simple
538use of the logging package is possible.
539
540The simplest example shows logging to the console:
541
542\begin{verbatim}
543import logging
544
545logging.debug('A debug message')
546logging.info('Some information')
547logging.warning('A shot across the bows')
548\end{verbatim}
549
550If you run the above script, you'll see this:
551\begin{verbatim}
552WARNING:root:A shot across the bows
553\end{verbatim}
554
555Because no particular logger was specified, the system used the root logger.
556The debug and info messages didn't appear because by default, the root
557logger is configured to only handle messages with a severity of WARNING
558or above. The message format is also a configuration default, as is the output
559destination of the messages - \code{sys.stderr}. The severity level,
560the message format and destination can be easily changed, as shown in
561the example below:
562
563\begin{verbatim}
564import logging
565
566logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000567 format='%(asctime)s %(levelname)s %(message)s',
568 filename='/tmp/myapp.log',
569 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000570logging.debug('A debug message')
571logging.info('Some information')
572logging.warning('A shot across the bows')
573\end{verbatim}
574
575The \method{basicConfig()} method is used to change the configuration
576defaults, which results in output (written to \code{/tmp/myapp.log})
577which should look something like the following:
578
579\begin{verbatim}
5802004-07-02 13:00:08,743 DEBUG A debug message
5812004-07-02 13:00:08,743 INFO Some information
5822004-07-02 13:00:08,743 WARNING A shot across the bows
583\end{verbatim}
584
585This time, all messages with a severity of DEBUG or above were handled,
586and the format of the messages was also changed, and output went to the
587specified file rather than the console.
588
589Formatting uses standard Python string formatting - see section
590\ref{typesseq-strings}. The format string takes the following
591common specifiers. For a complete list of specifiers, consult the
592\class{Formatter} documentation.
593
594\begin{tableii}{l|l}{code}{Format}{Description}
595\lineii{\%(name)s} {Name of the logger (logging channel).}
596\lineii{\%(levelname)s}{Text logging level for the message
597 (\code{'DEBUG'}, \code{'INFO'},
598 \code{'WARNING'}, \code{'ERROR'},
599 \code{'CRITICAL'}).}
600\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
601 was created. By default this is of the form
602 ``2003-07-08 16:49:45,896'' (the numbers after the
603 comma are millisecond portion of the time).}
604\lineii{\%(message)s} {The logged message.}
605\end{tableii}
606
607To change the date/time format, you can pass an additional keyword parameter,
608\var{datefmt}, as in the following:
609
610\begin{verbatim}
611import logging
612
613logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000614 format='%(asctime)s %(levelname)-8s %(message)s',
615 datefmt='%a, %d %b %Y %H:%M:%S',
616 filename='/temp/myapp.log',
617 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000618logging.debug('A debug message')
619logging.info('Some information')
620logging.warning('A shot across the bows')
621\end{verbatim}
622
623which would result in output like
624
625\begin{verbatim}
626Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
627Fri, 02 Jul 2004 13:06:18 INFO Some information
628Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
629\end{verbatim}
630
631The date format string follows the requirements of \function{strftime()} -
632see the documentation for the \refmodule{time} module.
633
634If, instead of sending logging output to the console or a file, you'd rather
635use a file-like object which you have created separately, you can pass it
636to \function{basicConfig()} using the \var{stream} keyword argument. Note
637that if both \var{stream} and \var{filename} keyword arguments are passed,
638the \var{stream} argument is ignored.
639
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000640Of course, you can put variable information in your output. To do this,
641simply have the message be a format string and pass in additional arguments
642containing the variable information, as in the following example:
643
644\begin{verbatim}
645import logging
646
647logging.basicConfig(level=logging.DEBUG,
648 format='%(asctime)s %(levelname)-8s %(message)s',
649 datefmt='%a, %d %b %Y %H:%M:%S',
650 filename='/temp/myapp.log',
651 filemode='w')
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000652logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000653\end{verbatim}
654
655which would result in
656
657\begin{verbatim}
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000658Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000659\end{verbatim}
660
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000661\subsection{Logging to multiple destinations \label{multiple-destinations}}
662
663Let's say you want to log to console and file with different message formats
664and in differing circumstances. Say you want to log messages with levels
665of DEBUG and higher to file, and those messages at level INFO and higher to
666the console. Let's also assume that the file should contain timestamps, but
667the console messages should not. Here's how you can achieve this:
668
669\begin{verbatim}
670import logging
671
Fred Drake048840c2004-10-29 14:35:42 +0000672# set up logging to file - see previous section for more details
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000673logging.basicConfig(level=logging.DEBUG,
674 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
675 datefmt='%m-%d %H:%M',
676 filename='/temp/myapp.log',
677 filemode='w')
Fred Drake048840c2004-10-29 14:35:42 +0000678# define a Handler which writes INFO messages or higher to the sys.stderr
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000679console = logging.StreamHandler()
680console.setLevel(logging.INFO)
Fred Drake048840c2004-10-29 14:35:42 +0000681# set a format which is simpler for console use
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000682formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Fred Drake048840c2004-10-29 14:35:42 +0000683# tell the handler to use this format
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000684console.setFormatter(formatter)
Fred Drake048840c2004-10-29 14:35:42 +0000685# add the handler to the root logger
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000686logging.getLogger('').addHandler(console)
687
Fred Drake048840c2004-10-29 14:35:42 +0000688# Now, we can log to the root logger, or any other logger. First the root...
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000689logging.info('Jackdaws love my big sphinx of quartz.')
690
Fred Drake048840c2004-10-29 14:35:42 +0000691# Now, define a couple of other loggers which might represent areas in your
692# application:
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000693
694logger1 = logging.getLogger('myapp.area1')
695logger2 = logging.getLogger('myapp.area2')
696
697logger1.debug('Quick zephyrs blow, vexing daft Jim.')
698logger1.info('How quickly daft jumping zebras vex.')
699logger2.warning('Jail zesty vixen who grabbed pay from quack.')
700logger2.error('The five boxing wizards jump quickly.')
701\end{verbatim}
702
703When you run this, on the console you will see
704
705\begin{verbatim}
706root : INFO Jackdaws love my big sphinx of quartz.
707myapp.area1 : INFO How quickly daft jumping zebras vex.
708myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
709myapp.area2 : ERROR The five boxing wizards jump quickly.
710\end{verbatim}
711
712and in the file you will see something like
713
714\begin{verbatim}
71510-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
71610-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
71710-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
71810-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
71910-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
720\end{verbatim}
721
722As you can see, the DEBUG message only shows up in the file. The other
723messages are sent to both destinations.
724
Vinay Sajip006483b2004-10-29 12:30:28 +0000725This example uses console and file handlers, but you can use any number and
726combination of handlers you choose.
727
728\subsection{Sending and receiving logging events across a network
729\label{network-logging}}
730
731Let's say you want to send logging events across a network, and handle them
732at the receiving end. A simple way of doing this is attaching a
733\class{SocketHandler} instance to the root logger at the sending end:
734
735\begin{verbatim}
736import logging, logging.handlers
737
738rootLogger = logging.getLogger('')
739rootLogger.setLevel(logging.DEBUG)
740socketHandler = logging.handlers.SocketHandler('localhost',
741 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
742# don't bother with a formatter, since a socket handler sends the event as
743# an unformatted pickle
744rootLogger.addHandler(socketHandler)
745
Fred Drake048840c2004-10-29 14:35:42 +0000746# Now, we can log to the root logger, or any other logger. First the root...
Vinay Sajip006483b2004-10-29 12:30:28 +0000747logging.info('Jackdaws love my big sphinx of quartz.')
748
Fred Drake048840c2004-10-29 14:35:42 +0000749# Now, define a couple of other loggers which might represent areas in your
750# application:
Vinay Sajip006483b2004-10-29 12:30:28 +0000751
752logger1 = logging.getLogger('myapp.area1')
753logger2 = logging.getLogger('myapp.area2')
754
755logger1.debug('Quick zephyrs blow, vexing daft Jim.')
756logger1.info('How quickly daft jumping zebras vex.')
757logger2.warning('Jail zesty vixen who grabbed pay from quack.')
758logger2.error('The five boxing wizards jump quickly.')
759\end{verbatim}
760
761At the receiving end, you can set up a receiver using the
762\module{SocketServer} module. Here is a basic working example:
763
764\begin{verbatim}
Fred Drake048840c2004-10-29 14:35:42 +0000765import cPickle
766import logging
767import logging.handlers
768import SocketServer
769import struct
Vinay Sajip006483b2004-10-29 12:30:28 +0000770
Vinay Sajip006483b2004-10-29 12:30:28 +0000771
Fred Drake048840c2004-10-29 14:35:42 +0000772class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
773 """Handler for a streaming logging request.
774
775 This basically logs the record using whatever logging policy is
776 configured locally.
Vinay Sajip006483b2004-10-29 12:30:28 +0000777 """
778
779 def handle(self):
780 """
781 Handle multiple requests - each expected to be a 4-byte length,
782 followed by the LogRecord in pickle format. Logs the record
783 according to whatever policy is configured locally.
784 """
785 while 1:
786 chunk = self.connection.recv(4)
787 if len(chunk) < 4:
788 break
789 slen = struct.unpack(">L", chunk)[0]
790 chunk = self.connection.recv(slen)
791 while len(chunk) < slen:
792 chunk = chunk + self.connection.recv(slen - len(chunk))
793 obj = self.unPickle(chunk)
794 record = logging.makeLogRecord(obj)
795 self.handleLogRecord(record)
796
797 def unPickle(self, data):
798 return cPickle.loads(data)
799
800 def handleLogRecord(self, record):
Fred Drake048840c2004-10-29 14:35:42 +0000801 # if a name is specified, we use the named logger rather than the one
802 # implied by the record.
Vinay Sajip006483b2004-10-29 12:30:28 +0000803 if self.server.logname is not None:
804 name = self.server.logname
805 else:
806 name = record.name
807 logger = logging.getLogger(name)
Fred Drake048840c2004-10-29 14:35:42 +0000808 # N.B. EVERY record gets logged. This is because Logger.handle
809 # is normally called AFTER logger-level filtering. If you want
810 # to do filtering, do it at the client end to save wasting
811 # cycles and network bandwidth!
Vinay Sajip006483b2004-10-29 12:30:28 +0000812 logger.handle(record)
813
Fred Drake048840c2004-10-29 14:35:42 +0000814class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
815 """simple TCP socket-based logging receiver suitable for testing.
Vinay Sajip006483b2004-10-29 12:30:28 +0000816 """
817
818 allow_reuse_address = 1
819
820 def __init__(self, host='localhost',
Fred Drake048840c2004-10-29 14:35:42 +0000821 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
822 handler=LogRecordStreamHandler):
823 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
Vinay Sajip006483b2004-10-29 12:30:28 +0000824 self.abort = 0
825 self.timeout = 1
826 self.logname = None
827
828 def serve_until_stopped(self):
829 import select
830 abort = 0
831 while not abort:
832 rd, wr, ex = select.select([self.socket.fileno()],
833 [], [],
834 self.timeout)
835 if rd:
836 self.handle_request()
837 abort = self.abort
838
839def main():
840 logging.basicConfig(
Vinay Sajipedde4922004-11-11 13:54:48 +0000841 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
Vinay Sajip006483b2004-10-29 12:30:28 +0000842 tcpserver = LogRecordSocketReceiver()
843 print "About to start TCP server..."
844 tcpserver.serve_until_stopped()
845
846if __name__ == "__main__":
847 main()
848\end{verbatim}
849
Vinay Sajipedde4922004-11-11 13:54:48 +0000850First run the server, and then the client. On the client side, nothing is
851printed on the console; on the server side, you should see something like:
Vinay Sajip006483b2004-10-29 12:30:28 +0000852
853\begin{verbatim}
854About to start TCP server...
855 59 root INFO Jackdaws love my big sphinx of quartz.
856 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
857 69 myapp.area1 INFO How quickly daft jumping zebras vex.
858 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
859 69 myapp.area2 ERROR The five boxing wizards jump quickly.
860\end{verbatim}
861
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000862\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000863
Fred Drake68e6d572003-01-28 22:02:35 +0000864Handlers have the following attributes and methods. Note that
865\class{Handler} is never instantiated directly; this class acts as a
866base for more useful subclasses. However, the \method{__init__()}
867method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000868
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000869\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000870Initializes the \class{Handler} instance by setting its level, setting
871the list of filters to the empty list and creating a lock (using
Raymond Hettingerc75c3e02003-09-01 22:50:52 +0000872\method{createLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000873\end{methoddesc}
874
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000875\begin{methoddesc}{createLock}{}
876Initializes a thread lock which can be used to serialize access to
877underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000878\end{methoddesc}
879
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000880\begin{methoddesc}{acquire}{}
881Acquires the thread lock created with \method{createLock()}.
882\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000883
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000884\begin{methoddesc}{release}{}
885Releases the thread lock acquired with \method{acquire()}.
886\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000887
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000888\begin{methoddesc}{setLevel}{lvl}
889Sets the threshold for this handler to \var{lvl}. Logging messages which are
890less severe than \var{lvl} will be ignored. When a handler is created, the
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000891level is set to \constant{NOTSET} (which causes all messages to be processed).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000892\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000893
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000894\begin{methoddesc}{setFormatter}{form}
895Sets the \class{Formatter} for this handler to \var{form}.
896\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000897
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000898\begin{methoddesc}{addFilter}{filt}
899Adds the specified filter \var{filt} to this handler.
900\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000901
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000902\begin{methoddesc}{removeFilter}{filt}
903Removes the specified filter \var{filt} from this handler.
904\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000905
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000906\begin{methoddesc}{filter}{record}
907Applies this handler's filters to the record and returns a true value if
908the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000909\end{methoddesc}
910
911\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000912Ensure all logging output has been flushed. This version does
913nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000914\end{methoddesc}
915
Skip Montanaro649698f2002-11-14 03:57:19 +0000916\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000917Tidy up any resources used by the handler. This version does
918nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000919\end{methoddesc}
920
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000921\begin{methoddesc}{handle}{record}
922Conditionally emits the specified logging record, depending on
923filters which may have been added to the handler. Wraps the actual
924emission of the record with acquisition/release of the I/O thread
925lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000926\end{methoddesc}
927
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000928\begin{methoddesc}{handleError}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000929This method should be called from handlers when an exception is
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000930encountered during an \method{emit()} call. By default it does nothing,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000931which means that exceptions get silently ignored. This is what is
932mostly wanted for a logging system - most users will not care
933about errors in the logging system, they are more interested in
934application errors. You could, however, replace this with a custom
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000935handler if you wish. The specified record is the one which was being
936processed when the exception occurred.
Skip Montanaro649698f2002-11-14 03:57:19 +0000937\end{methoddesc}
938
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000939\begin{methoddesc}{format}{record}
940Do formatting for a record - if a formatter is set, use it.
941Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000942\end{methoddesc}
943
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000944\begin{methoddesc}{emit}{record}
945Do whatever it takes to actually log the specified logging record.
946This version is intended to be implemented by subclasses and so
947raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000948\end{methoddesc}
949
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000950\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000951
Vinay Sajip51f52352006-01-22 11:58:39 +0000952The \class{StreamHandler} class, located in the core \module{logging}
953package, sends logging output to streams such as \var{sys.stdout},
954\var{sys.stderr} or any file-like object (or, more precisely, any
955object which supports \method{write()} and \method{flush()} methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000956
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000957\begin{classdesc}{StreamHandler}{\optional{strm}}
958Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
959specified, the instance will use it for logging output; otherwise,
960\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000961\end{classdesc}
962
963\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000964If a formatter is specified, it is used to format the record.
965The record is then written to the stream with a trailing newline.
966If exception information is present, it is formatted using
967\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000968\end{methoddesc}
969
970\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000971Flushes the stream by calling its \method{flush()} method. Note that
972the \method{close()} method is inherited from \class{Handler} and
973so does nothing, so an explicit \method{flush()} call may be needed
974at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000975\end{methoddesc}
976
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000977\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000978
Vinay Sajip51f52352006-01-22 11:58:39 +0000979The \class{FileHandler} class, located in the core \module{logging}
980package, sends logging output to a disk file. It inherits the output
981functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000982
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000983\begin{classdesc}{FileHandler}{filename\optional{, mode}}
984Returns a new instance of the \class{FileHandler} class. The specified
985file is opened and used as the stream for logging. If \var{mode} is
Fred Drake9a5b6a62003-07-08 15:38:40 +0000986not specified, \constant{'a'} is used. By default, the file grows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000987indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000988\end{classdesc}
989
990\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000991Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000992\end{methoddesc}
993
994\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000995Outputs the record to the file.
996\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000997
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000998\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000999
Vinay Sajip51f52352006-01-22 11:58:39 +00001000The \class{RotatingFileHandler} class, located in the \module{logging.handlers}
1001module, supports rotation of disk log files.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001002
Fred Drake9a5b6a62003-07-08 15:38:40 +00001003\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{,
1004 maxBytes\optional{, backupCount}}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001005Returns a new instance of the \class{RotatingFileHandler} class. The
1006specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +00001007\var{mode} is not specified, \code{'a'} is used. By default, the
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001008file grows indefinitely.
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +00001009
1010You can use the \var{maxBytes} and
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001011\var{backupCount} values to allow the file to \dfn{rollover} at a
1012predetermined size. When the size is about to be exceeded, the file is
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +00001013closed and a new file is silently opened for output. Rollover occurs
1014whenever the current log file is nearly \var{maxBytes} in length; if
1015\var{maxBytes} is zero, rollover never occurs. If \var{backupCount}
1016is non-zero, the system will save old log files by appending the
1017extensions ".1", ".2" etc., to the filename. For example, with
1018a \var{backupCount} of 5 and a base file name of
1019\file{app.log}, you would get \file{app.log},
1020\file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being
1021written to is always \file{app.log}. When this file is filled, it is
1022closed and renamed to \file{app.log.1}, and if files \file{app.log.1},
1023\file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2},
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001024\file{app.log.3} etc. respectively.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001025\end{classdesc}
1026
1027\begin{methoddesc}{doRollover}{}
1028Does a rollover, as described above.
1029\end{methoddesc}
1030
1031\begin{methoddesc}{emit}{record}
Johannes Gijsbersf1643222004-11-07 16:11:35 +00001032Outputs the record to the file, catering for rollover as described previously.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001033\end{methoddesc}
1034
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +00001035\subsubsection{TimedRotatingFileHandler}
1036
Vinay Sajip51f52352006-01-22 11:58:39 +00001037The \class{TimedRotatingFileHandler} class, located in the
1038\module{logging.handlers} module, supports rotation of disk log files
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +00001039at certain timed intervals.
1040
1041\begin{classdesc}{TimedRotatingFileHandler}{filename
1042 \optional{,when
1043 \optional{,interval
1044 \optional{,backupCount}}}}
1045
1046Returns a new instance of the \class{TimedRotatingFileHandler} class. The
1047specified file is opened and used as the stream for logging. On rotating
1048it also sets the filename suffix. Rotating happens based on the product
Vinay Sajipedde4922004-11-11 13:54:48 +00001049of \var{when} and \var{interval}.
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +00001050
1051You can use the \var{when} to specify the type of \var{interval}. The
1052list of possible values is, note that they are not case sensitive:
1053
1054\begin{tableii}{l|l}{}{Value}{Type of interval}
1055 \lineii{S}{Seconds}
1056 \lineii{M}{Minutes}
1057 \lineii{H}{Hours}
1058 \lineii{D}{Days}
1059 \lineii{W}{Week day (0=Monday)}
1060 \lineii{midnight}{Roll over at midnight}
1061\end{tableii}
1062
1063If \var{backupCount} is non-zero, the system will save old log files by
1064appending the extensions ".1", ".2" etc., to the filename. For example,
1065with a \var{backupCount} of 5 and a base file name of \file{app.log},
1066you would get \file{app.log}, \file{app.log.1}, \file{app.log.2}, up to
1067\file{app.log.5}. The file being written to is always \file{app.log}.
1068When this file is filled, it is closed and renamed to \file{app.log.1},
1069and if files \file{app.log.1}, \file{app.log.2}, etc. exist, then they
1070are renamed to \file{app.log.2}, \file{app.log.3} etc. respectively.
1071\end{classdesc}
1072
1073\begin{methoddesc}{doRollover}{}
1074Does a rollover, as described above.
1075\end{methoddesc}
1076
1077\begin{methoddesc}{emit}{record}
1078Outputs the record to the file, catering for rollover as described
1079above.
1080\end{methoddesc}
1081
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001082\subsubsection{SocketHandler}
1083
Vinay Sajip51f52352006-01-22 11:58:39 +00001084The \class{SocketHandler} class, located in the
1085\module{logging.handlers} module, sends logging output to a network
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001086socket. The base class uses a TCP socket.
1087
1088\begin{classdesc}{SocketHandler}{host, port}
1089Returns a new instance of the \class{SocketHandler} class intended to
1090communicate with a remote machine whose address is given by \var{host}
1091and \var{port}.
1092\end{classdesc}
1093
1094\begin{methoddesc}{close}{}
1095Closes the socket.
1096\end{methoddesc}
1097
1098\begin{methoddesc}{handleError}{}
1099\end{methoddesc}
1100
1101\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001102Pickles the record's attribute dictionary and writes it to the socket in
1103binary format. If there is an error with the socket, silently drops the
1104packet. If the connection was previously lost, re-establishes the connection.
Fred Drake6b3b0462004-04-09 18:26:40 +00001105To unpickle the record at the receiving end into a \class{LogRecord}, use the
1106\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001107\end{methoddesc}
1108
1109\begin{methoddesc}{handleError}{}
1110Handles an error which has occurred during \method{emit()}. The
1111most likely cause is a lost connection. Closes the socket so that
1112we can retry on the next event.
1113\end{methoddesc}
1114
1115\begin{methoddesc}{makeSocket}{}
1116This is a factory method which allows subclasses to define the precise
1117type of socket they want. The default implementation creates a TCP
1118socket (\constant{socket.SOCK_STREAM}).
1119\end{methoddesc}
1120
1121\begin{methoddesc}{makePickle}{record}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001122Pickles the record's attribute dictionary in binary format with a length
1123prefix, and returns it ready for transmission across the socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001124\end{methoddesc}
1125
1126\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001127Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001128for partial sends which can happen when the network is busy.
1129\end{methoddesc}
1130
1131\subsubsection{DatagramHandler}
1132
Vinay Sajip51f52352006-01-22 11:58:39 +00001133The \class{DatagramHandler} class, located in the
1134\module{logging.handlers} module, inherits from \class{SocketHandler}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001135to support sending logging messages over UDP sockets.
1136
1137\begin{classdesc}{DatagramHandler}{host, port}
1138Returns a new instance of the \class{DatagramHandler} class intended to
1139communicate with a remote machine whose address is given by \var{host}
1140and \var{port}.
1141\end{classdesc}
1142
1143\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001144Pickles the record's attribute dictionary and writes it to the socket in
1145binary format. If there is an error with the socket, silently drops the
1146packet.
Fred Drake6b3b0462004-04-09 18:26:40 +00001147To unpickle the record at the receiving end into a \class{LogRecord}, use the
1148\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001149\end{methoddesc}
1150
1151\begin{methoddesc}{makeSocket}{}
1152The factory method of \class{SocketHandler} is here overridden to create
1153a UDP socket (\constant{socket.SOCK_DGRAM}).
1154\end{methoddesc}
1155
1156\begin{methoddesc}{send}{s}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001157Send a pickled string to a socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001158\end{methoddesc}
1159
1160\subsubsection{SysLogHandler}
1161
Vinay Sajip51f52352006-01-22 11:58:39 +00001162The \class{SysLogHandler} class, located in the
1163\module{logging.handlers} module, supports sending logging messages to
1164a remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001165
1166\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
1167Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +00001168communicate with a remote \UNIX{} machine whose address is given by
1169\var{address} in the form of a \code{(\var{host}, \var{port})}
1170tuple. If \var{address} is not specified, \code{('localhost', 514)} is
1171used. The address is used to open a UDP socket. If \var{facility} is
1172not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001173\end{classdesc}
1174
1175\begin{methoddesc}{close}{}
1176Closes the socket to the remote host.
1177\end{methoddesc}
1178
1179\begin{methoddesc}{emit}{record}
1180The record is formatted, and then sent to the syslog server. If
1181exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +00001182\end{methoddesc}
1183
1184\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001185Encodes the facility and priority into an integer. You can pass in strings
1186or integers - if strings are passed, internal mapping dictionaries are used
1187to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +00001188\end{methoddesc}
1189
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001190\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +00001191
Vinay Sajip51f52352006-01-22 11:58:39 +00001192The \class{NTEventLogHandler} class, located in the
1193\module{logging.handlers} module, supports sending logging messages to
1194a local Windows NT, Windows 2000 or Windows XP event log. Before you
1195can use it, you need Mark Hammond's Win32 extensions for Python
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001196installed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001197
Fred Drake9a5b6a62003-07-08 15:38:40 +00001198\begin{classdesc}{NTEventLogHandler}{appname\optional{,
1199 dllname\optional{, logtype}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001200Returns a new instance of the \class{NTEventLogHandler} class. The
1201\var{appname} is used to define the application name as it appears in the
1202event log. An appropriate registry entry is created using this name.
1203The \var{dllname} should give the fully qualified pathname of a .dll or .exe
1204which contains message definitions to hold in the log (if not specified,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001205\code{'win32service.pyd'} is used - this is installed with the Win32
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001206extensions and contains some basic placeholder message definitions.
1207Note that use of these placeholders will make your event logs big, as the
1208entire message source is held in the log. If you want slimmer logs, you have
1209to pass in the name of your own .dll or .exe which contains the message
1210definitions you want to use in the event log). The \var{logtype} is one of
Fred Drake9a5b6a62003-07-08 15:38:40 +00001211\code{'Application'}, \code{'System'} or \code{'Security'}, and
1212defaults to \code{'Application'}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001213\end{classdesc}
1214
1215\begin{methoddesc}{close}{}
1216At this point, you can remove the application name from the registry as a
1217source of event log entries. However, if you do this, you will not be able
1218to see the events as you intended in the Event Log Viewer - it needs to be
1219able to access the registry to get the .dll name. The current version does
1220not do this (in fact it doesn't do anything).
1221\end{methoddesc}
1222
1223\begin{methoddesc}{emit}{record}
1224Determines the message ID, event category and event type, and then logs the
1225message in the NT event log.
1226\end{methoddesc}
1227
1228\begin{methoddesc}{getEventCategory}{record}
1229Returns the event category for the record. Override this if you
1230want to specify your own categories. This version returns 0.
1231\end{methoddesc}
1232
1233\begin{methoddesc}{getEventType}{record}
1234Returns the event type for the record. Override this if you want
1235to specify your own types. This version does a mapping using the
1236handler's typemap attribute, which is set up in \method{__init__()}
1237to a dictionary which contains mappings for \constant{DEBUG},
1238\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
1239\constant{CRITICAL}. If you are using your own levels, you will either need
1240to override this method or place a suitable dictionary in the
1241handler's \var{typemap} attribute.
1242\end{methoddesc}
1243
1244\begin{methoddesc}{getMessageID}{record}
1245Returns the message ID for the record. If you are using your
1246own messages, you could do this by having the \var{msg} passed to the
1247logger being an ID rather than a format string. Then, in here,
1248you could use a dictionary lookup to get the message ID. This
1249version returns 1, which is the base message ID in
Fred Drake9a5b6a62003-07-08 15:38:40 +00001250\file{win32service.pyd}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001251\end{methoddesc}
1252
1253\subsubsection{SMTPHandler}
1254
Vinay Sajip51f52352006-01-22 11:58:39 +00001255The \class{SMTPHandler} class, located in the
1256\module{logging.handlers} module, supports sending logging messages to
1257an email address via SMTP.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001258
1259\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
1260Returns a new instance of the \class{SMTPHandler} class. The
1261instance is initialized with the from and to addresses and subject
Vinay Sajip84df97f2005-02-18 11:50:11 +00001262line of the email. The \var{toaddrs} should be a list of strings. To specify a
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001263non-standard SMTP port, use the (host, port) tuple format for the
1264\var{mailhost} argument. If you use a string, the standard SMTP port
1265is used.
1266\end{classdesc}
1267
1268\begin{methoddesc}{emit}{record}
1269Formats the record and sends it to the specified addressees.
1270\end{methoddesc}
1271
1272\begin{methoddesc}{getSubject}{record}
1273If you want to specify a subject line which is record-dependent,
1274override this method.
1275\end{methoddesc}
1276
1277\subsubsection{MemoryHandler}
1278
Vinay Sajip51f52352006-01-22 11:58:39 +00001279The \class{MemoryHandler} class, located in the
1280\module{logging.handlers} module, supports buffering of logging
1281records in memory, periodically flushing them to a \dfn{target}
1282handler. Flushing occurs whenever the buffer is full, or when an event
1283of a certain severity or greater is seen.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001284
1285\class{MemoryHandler} is a subclass of the more general
1286\class{BufferingHandler}, which is an abstract class. This buffers logging
1287records in memory. Whenever each record is added to the buffer, a
1288check is made by calling \method{shouldFlush()} to see if the buffer
1289should be flushed. If it should, then \method{flush()} is expected to
1290do the needful.
1291
1292\begin{classdesc}{BufferingHandler}{capacity}
1293Initializes the handler with a buffer of the specified capacity.
1294\end{classdesc}
1295
1296\begin{methoddesc}{emit}{record}
1297Appends the record to the buffer. If \method{shouldFlush()} returns true,
1298calls \method{flush()} to process the buffer.
1299\end{methoddesc}
1300
1301\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001302You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001303just zaps the buffer to empty.
1304\end{methoddesc}
1305
1306\begin{methoddesc}{shouldFlush}{record}
1307Returns true if the buffer is up to capacity. This method can be
1308overridden to implement custom flushing strategies.
1309\end{methoddesc}
1310
1311\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001312\optional{, target}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001313Returns a new instance of the \class{MemoryHandler} class. The
1314instance is initialized with a buffer size of \var{capacity}. If
1315\var{flushLevel} is not specified, \constant{ERROR} is used. If no
1316\var{target} is specified, the target will need to be set using
1317\method{setTarget()} before this handler does anything useful.
1318\end{classdesc}
1319
1320\begin{methoddesc}{close}{}
1321Calls \method{flush()}, sets the target to \constant{None} and
1322clears the buffer.
1323\end{methoddesc}
1324
1325\begin{methoddesc}{flush}{}
1326For a \class{MemoryHandler}, flushing means just sending the buffered
1327records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001328different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001329\end{methoddesc}
1330
1331\begin{methoddesc}{setTarget}{target}
1332Sets the target handler for this handler.
1333\end{methoddesc}
1334
1335\begin{methoddesc}{shouldFlush}{record}
1336Checks for buffer full or a record at the \var{flushLevel} or higher.
1337\end{methoddesc}
1338
1339\subsubsection{HTTPHandler}
1340
Vinay Sajip51f52352006-01-22 11:58:39 +00001341The \class{HTTPHandler} class, located in the
1342\module{logging.handlers} module, supports sending logging messages to
1343a Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001344
1345\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
1346Returns a new instance of the \class{HTTPHandler} class. The
1347instance is initialized with a host address, url and HTTP method.
Vinay Sajip00b5c932005-10-29 00:40:15 +00001348The \var{host} can be of the form \code{host:port}, should you need to
1349use a specific port number. If no \var{method} is specified, \samp{GET}
1350is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001351\end{classdesc}
1352
1353\begin{methoddesc}{emit}{record}
1354Sends the record to the Web server as an URL-encoded dictionary.
1355\end{methoddesc}
1356
1357\subsection{Formatter Objects}
1358
1359\class{Formatter}s have the following attributes and methods. They are
1360responsible for converting a \class{LogRecord} to (usually) a string
1361which can be interpreted by either a human or an external system. The
1362base
1363\class{Formatter} allows a formatting string to be specified. If none is
Fred Drake8efc74d2004-04-15 06:18:48 +00001364supplied, the default value of \code{'\%(message)s'} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001365
1366A Formatter can be initialized with a format string which makes use of
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001367knowledge of the \class{LogRecord} attributes - such as the default value
1368mentioned above making use of the fact that the user's message and
Fred Drake6b3b0462004-04-09 18:26:40 +00001369arguments are pre-formatted into a \class{LogRecord}'s \var{message}
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001370attribute. This format string contains standard python \%-style
1371mapping keys. See section \ref{typesseq-strings}, ``String Formatting
1372Operations,'' for more information on string formatting.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001373
Fred Drake6b3b0462004-04-09 18:26:40 +00001374Currently, the useful mapping keys in a \class{LogRecord} are:
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001375
Fred Drake9a5b6a62003-07-08 15:38:40 +00001376\begin{tableii}{l|l}{code}{Format}{Description}
1377\lineii{\%(name)s} {Name of the logger (logging channel).}
1378\lineii{\%(levelno)s} {Numeric logging level for the message
1379 (\constant{DEBUG}, \constant{INFO},
1380 \constant{WARNING}, \constant{ERROR},
1381 \constant{CRITICAL}).}
1382\lineii{\%(levelname)s}{Text logging level for the message
1383 (\code{'DEBUG'}, \code{'INFO'},
1384 \code{'WARNING'}, \code{'ERROR'},
1385 \code{'CRITICAL'}).}
1386\lineii{\%(pathname)s} {Full pathname of the source file where the logging
1387 call was issued (if available).}
1388\lineii{\%(filename)s} {Filename portion of pathname.}
1389\lineii{\%(module)s} {Module (name portion of filename).}
Vinay Sajipb4549c42006-02-09 08:54:11 +00001390\lineii{\%(funcName)s} {Name of function containing the logging call.}
Fred Drake9a5b6a62003-07-08 15:38:40 +00001391\lineii{\%(lineno)d} {Source line number where the logging call was issued
1392 (if available).}
Fred Drake6b3b0462004-04-09 18:26:40 +00001393\lineii{\%(created)f} {Time when the \class{LogRecord} was created (as
Fred Drake9a5b6a62003-07-08 15:38:40 +00001394 returned by \function{time.time()}).}
Fred Drake6b3b0462004-04-09 18:26:40 +00001395\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
1396 was created. By default this is of the form
Fred Drake9a5b6a62003-07-08 15:38:40 +00001397 ``2003-07-08 16:49:45,896'' (the numbers after the
1398 comma are millisecond portion of the time).}
1399\lineii{\%(msecs)d} {Millisecond portion of the time when the
1400 \class{LogRecord} was created.}
1401\lineii{\%(thread)d} {Thread ID (if available).}
Vinay Sajip99358df2005-03-31 20:18:06 +00001402\lineii{\%(threadName)s} {Thread name (if available).}
Fred Drake9a5b6a62003-07-08 15:38:40 +00001403\lineii{\%(process)d} {Process ID (if available).}
1404\lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001405\end{tableii}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001406
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001407\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
1408Returns a new instance of the \class{Formatter} class. The
1409instance is initialized with a format string for the message as a whole,
1410as well as a format string for the date/time portion of a message. If
Neal Norwitzdd3afa72003-07-08 16:26:34 +00001411no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001412is specified, the ISO8601 date format is used.
1413\end{classdesc}
1414
1415\begin{methoddesc}{format}{record}
1416The record's attribute dictionary is used as the operand to a
1417string formatting operation. Returns the resulting string.
1418Before formatting the dictionary, a couple of preparatory steps
1419are carried out. The \var{message} attribute of the record is computed
1420using \var{msg} \% \var{args}. If the formatting string contains
Fred Drake9a5b6a62003-07-08 15:38:40 +00001421\code{'(asctime)'}, \method{formatTime()} is called to format the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001422event time. If there is exception information, it is formatted using
1423\method{formatException()} and appended to the message.
1424\end{methoddesc}
1425
1426\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
1427This method should be called from \method{format()} by a formatter which
1428wants to make use of a formatted time. This method can be overridden
1429in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001430basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +00001431it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001432record. Otherwise, the ISO8601 format is used. The resulting
1433string is returned.
1434\end{methoddesc}
1435
1436\begin{methoddesc}{formatException}{exc_info}
1437Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +00001438as returned by \function{sys.exc_info()}) as a string. This default
1439implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001440The resulting string is returned.
1441\end{methoddesc}
1442
1443\subsection{Filter Objects}
1444
1445\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
1446more sophisticated filtering than is provided by levels. The base filter
1447class only allows events which are below a certain point in the logger
1448hierarchy. For example, a filter initialized with "A.B" will allow events
1449logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
1450"B.A.B" etc. If initialized with the empty string, all events are passed.
1451
1452\begin{classdesc}{Filter}{\optional{name}}
1453Returns an instance of the \class{Filter} class. If \var{name} is specified,
1454it names a logger which, together with its children, will have its events
1455allowed through the filter. If no name is specified, allows every event.
1456\end{classdesc}
1457
1458\begin{methoddesc}{filter}{record}
1459Is the specified record to be logged? Returns zero for no, nonzero for
1460yes. If deemed appropriate, the record may be modified in-place by this
1461method.
1462\end{methoddesc}
1463
1464\subsection{LogRecord Objects}
1465
Fred Drake6b3b0462004-04-09 18:26:40 +00001466\class{LogRecord} instances are created every time something is logged. They
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001467contain all the information pertinent to the event being logged. The
1468main information passed in is in msg and args, which are combined
1469using msg \% args to create the message field of the record. The record
1470also includes information such as when the record was created, the
1471source line where the logging call was made, and any exception
1472information to be logged.
1473
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001474\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001475 exc_info}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001476Returns an instance of \class{LogRecord} initialized with interesting
1477information. The \var{name} is the logger name; \var{lvl} is the
1478numeric level; \var{pathname} is the absolute pathname of the source
1479file in which the logging call was made; \var{lineno} is the line
1480number in that file where the logging call is found; \var{msg} is the
1481user-supplied message (a format string); \var{args} is the tuple
1482which, together with \var{msg}, makes up the user message; and
1483\var{exc_info} is the exception tuple obtained by calling
1484\function{sys.exc_info() }(or \constant{None}, if no exception information
1485is available).
1486\end{classdesc}
1487
Vinay Sajipe8fdc452004-12-02 21:27:42 +00001488\begin{methoddesc}{getMessage}{}
1489Returns the message for this \class{LogRecord} instance after merging any
1490user-supplied arguments with the message.
1491\end{methoddesc}
1492
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001493\subsection{Thread Safety}
1494
1495The logging module is intended to be thread-safe without any special work
1496needing to be done by its clients. It achieves this though using threading
1497locks; there is one lock to serialize access to the module's shared data,
1498and each handler also creates a lock to serialize access to its underlying
1499I/O.
1500
1501\subsection{Configuration}
1502
1503
Fred Drake94ffbb72004-04-08 19:44:31 +00001504\subsubsection{Configuration functions%
1505 \label{logging-config-api}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001506
Vinay Sajip51f52352006-01-22 11:58:39 +00001507The following functions configure the logging module. They are located in the
1508\module{logging.config} module. Their use is optional --- you can configure
1509the logging module using these functions or by making calls to the
1510main API (defined in \module{logging} itself) and defining handlers
1511which are declared either in \module{logging} or
1512\module{logging.handlers}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001513
1514\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
1515Reads the logging configuration from a ConfigParser-format file named
1516\var{fname}. This function can be called several times from an application,
1517allowing an end user the ability to select from various pre-canned
1518configurations (if the developer provides a mechanism to present the
1519choices and load the chosen configuration). Defaults to be passed to
1520ConfigParser can be specified in the \var{defaults} argument.
1521\end{funcdesc}
1522
1523\begin{funcdesc}{listen}{\optional{port}}
1524Starts up a socket server on the specified port, and listens for new
1525configurations. If no port is specified, the module's default
1526\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
1527will be sent as a file suitable for processing by \function{fileConfig()}.
1528Returns a \class{Thread} instance on which you can call \method{start()}
1529to start the server, and which you can \method{join()} when appropriate.
Vinay Sajip4c1423b2005-06-05 20:39:36 +00001530To stop the server, call \function{stopListening()}. To send a configuration
1531to the socket, read in the configuration file and send it to the socket
1532as a string of bytes preceded by a four-byte length packed in binary using
1533struct.\code{pack(">L", n)}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001534\end{funcdesc}
1535
1536\begin{funcdesc}{stopListening}{}
1537Stops the listening server which was created with a call to
1538\function{listen()}. This is typically called before calling \method{join()}
1539on the return value from \function{listen()}.
1540\end{funcdesc}
1541
Fred Drake94ffbb72004-04-08 19:44:31 +00001542\subsubsection{Configuration file format%
1543 \label{logging-config-fileformat}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001544
Fred Drake6b3b0462004-04-09 18:26:40 +00001545The configuration file format understood by \function{fileConfig()} is
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001546based on ConfigParser functionality. The file must contain sections
1547called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
1548which identify by name the entities of each type which are defined in
1549the file. For each such entity, there is a separate section which
1550identified how that entity is configured. Thus, for a logger named
1551\code{log01} in the \code{[loggers]} section, the relevant
1552configuration details are held in a section
1553\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
1554the \code{[handlers]} section will have its configuration held in a
1555section called \code{[handler_hand01]}, while a formatter called
1556\code{form01} in the \code{[formatters]} section will have its
1557configuration specified in a section called
1558\code{[formatter_form01]}. The root logger configuration must be
1559specified in a section called \code{[logger_root]}.
1560
1561Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001562
1563\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001564[loggers]
1565keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +00001566
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001567[handlers]
1568keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1569
1570[formatters]
1571keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +00001572\end{verbatim}
1573
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001574The root logger must specify a level and a list of handlers. An
1575example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001576
1577\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001578[logger_root]
1579level=NOTSET
1580handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +00001581\end{verbatim}
1582
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001583The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1584ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1585\code{NOTSET} means that all messages will be logged. Level values are
1586\function{eval()}uated in the context of the \code{logging} package's
1587namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +00001588
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001589The \code{handlers} entry is a comma-separated list of handler names,
1590which must appear in the \code{[handlers]} section. These names must
1591appear in the \code{[handlers]} section and have corresponding
1592sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +00001593
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001594For loggers other than the root logger, some additional information is
1595required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +00001596
1597\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001598[logger_parser]
1599level=DEBUG
1600handlers=hand01
1601propagate=1
1602qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001603\end{verbatim}
1604
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001605The \code{level} and \code{handlers} entries are interpreted as for
1606the root logger, except that if a non-root logger's level is specified
1607as \code{NOTSET}, the system consults loggers higher up the hierarchy
1608to determine the effective level of the logger. The \code{propagate}
1609entry is set to 1 to indicate that messages must propagate to handlers
1610higher up the logger hierarchy from this logger, or 0 to indicate that
1611messages are \strong{not} propagated to handlers up the hierarchy. The
1612\code{qualname} entry is the hierarchical channel name of the logger,
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001613that is to say the name used by the application to get the logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001614
1615Sections which specify handler configuration are exemplified by the
1616following.
1617
Skip Montanaro649698f2002-11-14 03:57:19 +00001618\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001619[handler_hand01]
1620class=StreamHandler
1621level=NOTSET
1622formatter=form01
1623args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001624\end{verbatim}
1625
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001626The \code{class} entry indicates the handler's class (as determined by
1627\function{eval()} in the \code{logging} package's namespace). The
1628\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1629to mean "log everything".
1630
1631The \code{formatter} entry indicates the key name of the formatter for
1632this handler. If blank, a default formatter
1633(\code{logging._defaultFormatter}) is used. If a name is specified, it
1634must appear in the \code{[formatters]} section and have a
1635corresponding section in the configuration file.
1636
1637The \code{args} entry, when \function{eval()}uated in the context of
1638the \code{logging} package's namespace, is the list of arguments to
1639the constructor for the handler class. Refer to the constructors for
1640the relevant handlers, or to the examples below, to see how typical
1641entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001642
1643\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001644[handler_hand02]
1645class=FileHandler
1646level=DEBUG
1647formatter=form02
1648args=('python.log', 'w')
1649
1650[handler_hand03]
1651class=handlers.SocketHandler
1652level=INFO
1653formatter=form03
1654args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1655
1656[handler_hand04]
1657class=handlers.DatagramHandler
1658level=WARN
1659formatter=form04
1660args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1661
1662[handler_hand05]
1663class=handlers.SysLogHandler
1664level=ERROR
1665formatter=form05
1666args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1667
1668[handler_hand06]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001669class=handlers.NTEventLogHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001670level=CRITICAL
1671formatter=form06
1672args=('Python Application', '', 'Application')
1673
1674[handler_hand07]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001675class=handlers.SMTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001676level=WARN
1677formatter=form07
1678args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1679
1680[handler_hand08]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001681class=handlers.MemoryHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001682level=NOTSET
1683formatter=form08
1684target=
1685args=(10, ERROR)
1686
1687[handler_hand09]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001688class=handlers.HTTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001689level=NOTSET
1690formatter=form09
1691args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001692\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001693
1694Sections which specify formatter configuration are typified by the following.
1695
1696\begin{verbatim}
1697[formatter_form01]
1698format=F1 %(asctime)s %(levelname)s %(message)s
1699datefmt=
Vinay Sajip51f52352006-01-22 11:58:39 +00001700class=logging.Formatter
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001701\end{verbatim}
1702
1703The \code{format} entry is the overall format string, and the
1704\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1705string. If empty, the package substitutes ISO8601 format date/times, which
1706is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1707The ISO8601 format also specifies milliseconds, which are appended to the
1708result of using the above format string, with a comma separator. An example
1709time in ISO8601 format is \code{2003-01-23 00:29:50,411}.
Vinay Sajip51f52352006-01-22 11:58:39 +00001710
1711The \code{class} entry is optional. It indicates the name of the
1712formatter's class (as a dotted module and class name.) This option is
1713useful for instantiating a \class{Formatter} subclass. Subclasses of
1714\class{Formatter} can present exception tracebacks in an expanded or
1715condensed format.