blob: 45a59e4057c9bea1129b29fb6eb7db55f29c43b9 [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.
Neal Norwitzc16dd482006-02-13 02:04:37 +0000529\versionchanged[\var{func} and \var{extra} were added]{2.5}
Skip Montanaro649698f2002-11-14 03:57:19 +0000530\end{methoddesc}
531
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000532\subsection{Basic example \label{minimal-example}}
533
Vinay Sajipc320c222005-07-29 11:52:19 +0000534\versionchanged[formerly \function{basicConfig} did not take any keyword
535arguments]{2.4}
536
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000537The \module{logging} package provides a lot of flexibility, and its
538configuration can appear daunting. This section demonstrates that simple
539use of the logging package is possible.
540
541The simplest example shows logging to the console:
542
543\begin{verbatim}
544import logging
545
546logging.debug('A debug message')
547logging.info('Some information')
548logging.warning('A shot across the bows')
549\end{verbatim}
550
551If you run the above script, you'll see this:
552\begin{verbatim}
553WARNING:root:A shot across the bows
554\end{verbatim}
555
556Because no particular logger was specified, the system used the root logger.
557The debug and info messages didn't appear because by default, the root
558logger is configured to only handle messages with a severity of WARNING
559or above. The message format is also a configuration default, as is the output
560destination of the messages - \code{sys.stderr}. The severity level,
561the message format and destination can be easily changed, as shown in
562the example below:
563
564\begin{verbatim}
565import logging
566
567logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000568 format='%(asctime)s %(levelname)s %(message)s',
569 filename='/tmp/myapp.log',
570 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000571logging.debug('A debug message')
572logging.info('Some information')
573logging.warning('A shot across the bows')
574\end{verbatim}
575
576The \method{basicConfig()} method is used to change the configuration
577defaults, which results in output (written to \code{/tmp/myapp.log})
578which should look something like the following:
579
580\begin{verbatim}
5812004-07-02 13:00:08,743 DEBUG A debug message
5822004-07-02 13:00:08,743 INFO Some information
5832004-07-02 13:00:08,743 WARNING A shot across the bows
584\end{verbatim}
585
586This time, all messages with a severity of DEBUG or above were handled,
587and the format of the messages was also changed, and output went to the
588specified file rather than the console.
589
590Formatting uses standard Python string formatting - see section
591\ref{typesseq-strings}. The format string takes the following
592common specifiers. For a complete list of specifiers, consult the
593\class{Formatter} documentation.
594
595\begin{tableii}{l|l}{code}{Format}{Description}
596\lineii{\%(name)s} {Name of the logger (logging channel).}
597\lineii{\%(levelname)s}{Text logging level for the message
598 (\code{'DEBUG'}, \code{'INFO'},
599 \code{'WARNING'}, \code{'ERROR'},
600 \code{'CRITICAL'}).}
601\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
602 was created. By default this is of the form
603 ``2003-07-08 16:49:45,896'' (the numbers after the
604 comma are millisecond portion of the time).}
605\lineii{\%(message)s} {The logged message.}
606\end{tableii}
607
608To change the date/time format, you can pass an additional keyword parameter,
609\var{datefmt}, as in the following:
610
611\begin{verbatim}
612import logging
613
614logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000615 format='%(asctime)s %(levelname)-8s %(message)s',
616 datefmt='%a, %d %b %Y %H:%M:%S',
617 filename='/temp/myapp.log',
618 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000619logging.debug('A debug message')
620logging.info('Some information')
621logging.warning('A shot across the bows')
622\end{verbatim}
623
624which would result in output like
625
626\begin{verbatim}
627Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
628Fri, 02 Jul 2004 13:06:18 INFO Some information
629Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
630\end{verbatim}
631
632The date format string follows the requirements of \function{strftime()} -
633see the documentation for the \refmodule{time} module.
634
635If, instead of sending logging output to the console or a file, you'd rather
636use a file-like object which you have created separately, you can pass it
637to \function{basicConfig()} using the \var{stream} keyword argument. Note
638that if both \var{stream} and \var{filename} keyword arguments are passed,
639the \var{stream} argument is ignored.
640
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000641Of course, you can put variable information in your output. To do this,
642simply have the message be a format string and pass in additional arguments
643containing the variable information, as in the following example:
644
645\begin{verbatim}
646import logging
647
648logging.basicConfig(level=logging.DEBUG,
649 format='%(asctime)s %(levelname)-8s %(message)s',
650 datefmt='%a, %d %b %Y %H:%M:%S',
651 filename='/temp/myapp.log',
652 filemode='w')
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000653logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000654\end{verbatim}
655
656which would result in
657
658\begin{verbatim}
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000659Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000660\end{verbatim}
661
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000662\subsection{Logging to multiple destinations \label{multiple-destinations}}
663
664Let's say you want to log to console and file with different message formats
665and in differing circumstances. Say you want to log messages with levels
666of DEBUG and higher to file, and those messages at level INFO and higher to
667the console. Let's also assume that the file should contain timestamps, but
668the console messages should not. Here's how you can achieve this:
669
670\begin{verbatim}
671import logging
672
Fred Drake048840c2004-10-29 14:35:42 +0000673# set up logging to file - see previous section for more details
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000674logging.basicConfig(level=logging.DEBUG,
675 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
676 datefmt='%m-%d %H:%M',
677 filename='/temp/myapp.log',
678 filemode='w')
Fred Drake048840c2004-10-29 14:35:42 +0000679# define a Handler which writes INFO messages or higher to the sys.stderr
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000680console = logging.StreamHandler()
681console.setLevel(logging.INFO)
Fred Drake048840c2004-10-29 14:35:42 +0000682# set a format which is simpler for console use
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000683formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Fred Drake048840c2004-10-29 14:35:42 +0000684# tell the handler to use this format
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000685console.setFormatter(formatter)
Fred Drake048840c2004-10-29 14:35:42 +0000686# add the handler to the root logger
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000687logging.getLogger('').addHandler(console)
688
Fred Drake048840c2004-10-29 14:35:42 +0000689# Now, we can log to the root logger, or any other logger. First the root...
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000690logging.info('Jackdaws love my big sphinx of quartz.')
691
Fred Drake048840c2004-10-29 14:35:42 +0000692# Now, define a couple of other loggers which might represent areas in your
693# application:
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000694
695logger1 = logging.getLogger('myapp.area1')
696logger2 = logging.getLogger('myapp.area2')
697
698logger1.debug('Quick zephyrs blow, vexing daft Jim.')
699logger1.info('How quickly daft jumping zebras vex.')
700logger2.warning('Jail zesty vixen who grabbed pay from quack.')
701logger2.error('The five boxing wizards jump quickly.')
702\end{verbatim}
703
704When you run this, on the console you will see
705
706\begin{verbatim}
707root : INFO Jackdaws love my big sphinx of quartz.
708myapp.area1 : INFO How quickly daft jumping zebras vex.
709myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
710myapp.area2 : ERROR The five boxing wizards jump quickly.
711\end{verbatim}
712
713and in the file you will see something like
714
715\begin{verbatim}
71610-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
71710-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
71810-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
71910-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
72010-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
721\end{verbatim}
722
723As you can see, the DEBUG message only shows up in the file. The other
724messages are sent to both destinations.
725
Vinay Sajip006483b2004-10-29 12:30:28 +0000726This example uses console and file handlers, but you can use any number and
727combination of handlers you choose.
728
729\subsection{Sending and receiving logging events across a network
730\label{network-logging}}
731
732Let's say you want to send logging events across a network, and handle them
733at the receiving end. A simple way of doing this is attaching a
734\class{SocketHandler} instance to the root logger at the sending end:
735
736\begin{verbatim}
737import logging, logging.handlers
738
739rootLogger = logging.getLogger('')
740rootLogger.setLevel(logging.DEBUG)
741socketHandler = logging.handlers.SocketHandler('localhost',
742 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
743# don't bother with a formatter, since a socket handler sends the event as
744# an unformatted pickle
745rootLogger.addHandler(socketHandler)
746
Fred Drake048840c2004-10-29 14:35:42 +0000747# Now, we can log to the root logger, or any other logger. First the root...
Vinay Sajip006483b2004-10-29 12:30:28 +0000748logging.info('Jackdaws love my big sphinx of quartz.')
749
Fred Drake048840c2004-10-29 14:35:42 +0000750# Now, define a couple of other loggers which might represent areas in your
751# application:
Vinay Sajip006483b2004-10-29 12:30:28 +0000752
753logger1 = logging.getLogger('myapp.area1')
754logger2 = logging.getLogger('myapp.area2')
755
756logger1.debug('Quick zephyrs blow, vexing daft Jim.')
757logger1.info('How quickly daft jumping zebras vex.')
758logger2.warning('Jail zesty vixen who grabbed pay from quack.')
759logger2.error('The five boxing wizards jump quickly.')
760\end{verbatim}
761
762At the receiving end, you can set up a receiver using the
763\module{SocketServer} module. Here is a basic working example:
764
765\begin{verbatim}
Fred Drake048840c2004-10-29 14:35:42 +0000766import cPickle
767import logging
768import logging.handlers
769import SocketServer
770import struct
Vinay Sajip006483b2004-10-29 12:30:28 +0000771
Vinay Sajip006483b2004-10-29 12:30:28 +0000772
Fred Drake048840c2004-10-29 14:35:42 +0000773class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
774 """Handler for a streaming logging request.
775
776 This basically logs the record using whatever logging policy is
777 configured locally.
Vinay Sajip006483b2004-10-29 12:30:28 +0000778 """
779
780 def handle(self):
781 """
782 Handle multiple requests - each expected to be a 4-byte length,
783 followed by the LogRecord in pickle format. Logs the record
784 according to whatever policy is configured locally.
785 """
786 while 1:
787 chunk = self.connection.recv(4)
788 if len(chunk) < 4:
789 break
790 slen = struct.unpack(">L", chunk)[0]
791 chunk = self.connection.recv(slen)
792 while len(chunk) < slen:
793 chunk = chunk + self.connection.recv(slen - len(chunk))
794 obj = self.unPickle(chunk)
795 record = logging.makeLogRecord(obj)
796 self.handleLogRecord(record)
797
798 def unPickle(self, data):
799 return cPickle.loads(data)
800
801 def handleLogRecord(self, record):
Fred Drake048840c2004-10-29 14:35:42 +0000802 # if a name is specified, we use the named logger rather than the one
803 # implied by the record.
Vinay Sajip006483b2004-10-29 12:30:28 +0000804 if self.server.logname is not None:
805 name = self.server.logname
806 else:
807 name = record.name
808 logger = logging.getLogger(name)
Fred Drake048840c2004-10-29 14:35:42 +0000809 # N.B. EVERY record gets logged. This is because Logger.handle
810 # is normally called AFTER logger-level filtering. If you want
811 # to do filtering, do it at the client end to save wasting
812 # cycles and network bandwidth!
Vinay Sajip006483b2004-10-29 12:30:28 +0000813 logger.handle(record)
814
Fred Drake048840c2004-10-29 14:35:42 +0000815class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
816 """simple TCP socket-based logging receiver suitable for testing.
Vinay Sajip006483b2004-10-29 12:30:28 +0000817 """
818
819 allow_reuse_address = 1
820
821 def __init__(self, host='localhost',
Fred Drake048840c2004-10-29 14:35:42 +0000822 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
823 handler=LogRecordStreamHandler):
824 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
Vinay Sajip006483b2004-10-29 12:30:28 +0000825 self.abort = 0
826 self.timeout = 1
827 self.logname = None
828
829 def serve_until_stopped(self):
830 import select
831 abort = 0
832 while not abort:
833 rd, wr, ex = select.select([self.socket.fileno()],
834 [], [],
835 self.timeout)
836 if rd:
837 self.handle_request()
838 abort = self.abort
839
840def main():
841 logging.basicConfig(
Vinay Sajipedde4922004-11-11 13:54:48 +0000842 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
Vinay Sajip006483b2004-10-29 12:30:28 +0000843 tcpserver = LogRecordSocketReceiver()
844 print "About to start TCP server..."
845 tcpserver.serve_until_stopped()
846
847if __name__ == "__main__":
848 main()
849\end{verbatim}
850
Vinay Sajipedde4922004-11-11 13:54:48 +0000851First run the server, and then the client. On the client side, nothing is
852printed on the console; on the server side, you should see something like:
Vinay Sajip006483b2004-10-29 12:30:28 +0000853
854\begin{verbatim}
855About to start TCP server...
856 59 root INFO Jackdaws love my big sphinx of quartz.
857 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
858 69 myapp.area1 INFO How quickly daft jumping zebras vex.
859 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
860 69 myapp.area2 ERROR The five boxing wizards jump quickly.
861\end{verbatim}
862
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000863\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000864
Fred Drake68e6d572003-01-28 22:02:35 +0000865Handlers have the following attributes and methods. Note that
866\class{Handler} is never instantiated directly; this class acts as a
867base for more useful subclasses. However, the \method{__init__()}
868method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000869
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000870\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000871Initializes the \class{Handler} instance by setting its level, setting
872the list of filters to the empty list and creating a lock (using
Raymond Hettingerc75c3e02003-09-01 22:50:52 +0000873\method{createLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000874\end{methoddesc}
875
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000876\begin{methoddesc}{createLock}{}
877Initializes a thread lock which can be used to serialize access to
878underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000879\end{methoddesc}
880
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000881\begin{methoddesc}{acquire}{}
882Acquires the thread lock created with \method{createLock()}.
883\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000884
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000885\begin{methoddesc}{release}{}
886Releases the thread lock acquired with \method{acquire()}.
887\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000888
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000889\begin{methoddesc}{setLevel}{lvl}
890Sets the threshold for this handler to \var{lvl}. Logging messages which are
891less severe than \var{lvl} will be ignored. When a handler is created, the
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000892level is set to \constant{NOTSET} (which causes all messages to be processed).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000893\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000894
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000895\begin{methoddesc}{setFormatter}{form}
896Sets the \class{Formatter} for this handler to \var{form}.
897\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000898
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000899\begin{methoddesc}{addFilter}{filt}
900Adds the specified filter \var{filt} to this handler.
901\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000902
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000903\begin{methoddesc}{removeFilter}{filt}
904Removes the specified filter \var{filt} from this handler.
905\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000906
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000907\begin{methoddesc}{filter}{record}
908Applies this handler's filters to the record and returns a true value if
909the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000910\end{methoddesc}
911
912\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000913Ensure all logging output has been flushed. This version does
914nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000915\end{methoddesc}
916
Skip Montanaro649698f2002-11-14 03:57:19 +0000917\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000918Tidy up any resources used by the handler. This version does
919nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000920\end{methoddesc}
921
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000922\begin{methoddesc}{handle}{record}
923Conditionally emits the specified logging record, depending on
924filters which may have been added to the handler. Wraps the actual
925emission of the record with acquisition/release of the I/O thread
926lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000927\end{methoddesc}
928
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000929\begin{methoddesc}{handleError}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000930This method should be called from handlers when an exception is
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000931encountered during an \method{emit()} call. By default it does nothing,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000932which means that exceptions get silently ignored. This is what is
933mostly wanted for a logging system - most users will not care
934about errors in the logging system, they are more interested in
935application errors. You could, however, replace this with a custom
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000936handler if you wish. The specified record is the one which was being
937processed when the exception occurred.
Skip Montanaro649698f2002-11-14 03:57:19 +0000938\end{methoddesc}
939
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000940\begin{methoddesc}{format}{record}
941Do formatting for a record - if a formatter is set, use it.
942Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000943\end{methoddesc}
944
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000945\begin{methoddesc}{emit}{record}
946Do whatever it takes to actually log the specified logging record.
947This version is intended to be implemented by subclasses and so
948raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000949\end{methoddesc}
950
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000951\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000952
Vinay Sajip51f52352006-01-22 11:58:39 +0000953The \class{StreamHandler} class, located in the core \module{logging}
954package, sends logging output to streams such as \var{sys.stdout},
955\var{sys.stderr} or any file-like object (or, more precisely, any
956object which supports \method{write()} and \method{flush()} methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000957
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000958\begin{classdesc}{StreamHandler}{\optional{strm}}
959Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
960specified, the instance will use it for logging output; otherwise,
961\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000962\end{classdesc}
963
964\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000965If a formatter is specified, it is used to format the record.
966The record is then written to the stream with a trailing newline.
967If exception information is present, it is formatted using
968\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000969\end{methoddesc}
970
971\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000972Flushes the stream by calling its \method{flush()} method. Note that
973the \method{close()} method is inherited from \class{Handler} and
974so does nothing, so an explicit \method{flush()} call may be needed
975at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000976\end{methoddesc}
977
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000978\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000979
Vinay Sajip51f52352006-01-22 11:58:39 +0000980The \class{FileHandler} class, located in the core \module{logging}
981package, sends logging output to a disk file. It inherits the output
982functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000983
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000984\begin{classdesc}{FileHandler}{filename\optional{, mode}}
985Returns a new instance of the \class{FileHandler} class. The specified
986file is opened and used as the stream for logging. If \var{mode} is
Fred Drake9a5b6a62003-07-08 15:38:40 +0000987not specified, \constant{'a'} is used. By default, the file grows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000988indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000989\end{classdesc}
990
991\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000992Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000993\end{methoddesc}
994
995\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000996Outputs the record to the file.
997\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000998
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000999\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +00001000
Vinay Sajip51f52352006-01-22 11:58:39 +00001001The \class{RotatingFileHandler} class, located in the \module{logging.handlers}
1002module, supports rotation of disk log files.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001003
Fred Drake9a5b6a62003-07-08 15:38:40 +00001004\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{,
1005 maxBytes\optional{, backupCount}}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001006Returns a new instance of the \class{RotatingFileHandler} class. The
1007specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +00001008\var{mode} is not specified, \code{'a'} is used. By default, the
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001009file grows indefinitely.
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +00001010
1011You can use the \var{maxBytes} and
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001012\var{backupCount} values to allow the file to \dfn{rollover} at a
1013predetermined size. When the size is about to be exceeded, the file is
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +00001014closed and a new file is silently opened for output. Rollover occurs
1015whenever the current log file is nearly \var{maxBytes} in length; if
1016\var{maxBytes} is zero, rollover never occurs. If \var{backupCount}
1017is non-zero, the system will save old log files by appending the
1018extensions ".1", ".2" etc., to the filename. For example, with
1019a \var{backupCount} of 5 and a base file name of
1020\file{app.log}, you would get \file{app.log},
1021\file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being
1022written to is always \file{app.log}. When this file is filled, it is
1023closed and renamed to \file{app.log.1}, and if files \file{app.log.1},
1024\file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2},
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001025\file{app.log.3} etc. respectively.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001026\end{classdesc}
1027
1028\begin{methoddesc}{doRollover}{}
1029Does a rollover, as described above.
1030\end{methoddesc}
1031
1032\begin{methoddesc}{emit}{record}
Johannes Gijsbersf1643222004-11-07 16:11:35 +00001033Outputs the record to the file, catering for rollover as described previously.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001034\end{methoddesc}
1035
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +00001036\subsubsection{TimedRotatingFileHandler}
1037
Vinay Sajip51f52352006-01-22 11:58:39 +00001038The \class{TimedRotatingFileHandler} class, located in the
1039\module{logging.handlers} module, supports rotation of disk log files
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +00001040at certain timed intervals.
1041
1042\begin{classdesc}{TimedRotatingFileHandler}{filename
1043 \optional{,when
1044 \optional{,interval
1045 \optional{,backupCount}}}}
1046
1047Returns a new instance of the \class{TimedRotatingFileHandler} class. The
1048specified file is opened and used as the stream for logging. On rotating
1049it also sets the filename suffix. Rotating happens based on the product
Vinay Sajipedde4922004-11-11 13:54:48 +00001050of \var{when} and \var{interval}.
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +00001051
1052You can use the \var{when} to specify the type of \var{interval}. The
1053list of possible values is, note that they are not case sensitive:
1054
1055\begin{tableii}{l|l}{}{Value}{Type of interval}
1056 \lineii{S}{Seconds}
1057 \lineii{M}{Minutes}
1058 \lineii{H}{Hours}
1059 \lineii{D}{Days}
1060 \lineii{W}{Week day (0=Monday)}
1061 \lineii{midnight}{Roll over at midnight}
1062\end{tableii}
1063
1064If \var{backupCount} is non-zero, the system will save old log files by
1065appending the extensions ".1", ".2" etc., to the filename. For example,
1066with a \var{backupCount} of 5 and a base file name of \file{app.log},
1067you would get \file{app.log}, \file{app.log.1}, \file{app.log.2}, up to
1068\file{app.log.5}. The file being written to is always \file{app.log}.
1069When this file is filled, it is closed and renamed to \file{app.log.1},
1070and if files \file{app.log.1}, \file{app.log.2}, etc. exist, then they
1071are renamed to \file{app.log.2}, \file{app.log.3} etc. respectively.
1072\end{classdesc}
1073
1074\begin{methoddesc}{doRollover}{}
1075Does a rollover, as described above.
1076\end{methoddesc}
1077
1078\begin{methoddesc}{emit}{record}
1079Outputs the record to the file, catering for rollover as described
1080above.
1081\end{methoddesc}
1082
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001083\subsubsection{SocketHandler}
1084
Vinay Sajip51f52352006-01-22 11:58:39 +00001085The \class{SocketHandler} class, located in the
1086\module{logging.handlers} module, sends logging output to a network
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001087socket. The base class uses a TCP socket.
1088
1089\begin{classdesc}{SocketHandler}{host, port}
1090Returns a new instance of the \class{SocketHandler} class intended to
1091communicate with a remote machine whose address is given by \var{host}
1092and \var{port}.
1093\end{classdesc}
1094
1095\begin{methoddesc}{close}{}
1096Closes the socket.
1097\end{methoddesc}
1098
1099\begin{methoddesc}{handleError}{}
1100\end{methoddesc}
1101
1102\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001103Pickles the record's attribute dictionary and writes it to the socket in
1104binary format. If there is an error with the socket, silently drops the
1105packet. If the connection was previously lost, re-establishes the connection.
Fred Drake6b3b0462004-04-09 18:26:40 +00001106To unpickle the record at the receiving end into a \class{LogRecord}, use the
1107\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001108\end{methoddesc}
1109
1110\begin{methoddesc}{handleError}{}
1111Handles an error which has occurred during \method{emit()}. The
1112most likely cause is a lost connection. Closes the socket so that
1113we can retry on the next event.
1114\end{methoddesc}
1115
1116\begin{methoddesc}{makeSocket}{}
1117This is a factory method which allows subclasses to define the precise
1118type of socket they want. The default implementation creates a TCP
1119socket (\constant{socket.SOCK_STREAM}).
1120\end{methoddesc}
1121
1122\begin{methoddesc}{makePickle}{record}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001123Pickles the record's attribute dictionary in binary format with a length
1124prefix, and returns it ready for transmission across the socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001125\end{methoddesc}
1126
1127\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001128Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001129for partial sends which can happen when the network is busy.
1130\end{methoddesc}
1131
1132\subsubsection{DatagramHandler}
1133
Vinay Sajip51f52352006-01-22 11:58:39 +00001134The \class{DatagramHandler} class, located in the
1135\module{logging.handlers} module, inherits from \class{SocketHandler}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001136to support sending logging messages over UDP sockets.
1137
1138\begin{classdesc}{DatagramHandler}{host, port}
1139Returns a new instance of the \class{DatagramHandler} class intended to
1140communicate with a remote machine whose address is given by \var{host}
1141and \var{port}.
1142\end{classdesc}
1143
1144\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001145Pickles the record's attribute dictionary and writes it to the socket in
1146binary format. If there is an error with the socket, silently drops the
1147packet.
Fred Drake6b3b0462004-04-09 18:26:40 +00001148To unpickle the record at the receiving end into a \class{LogRecord}, use the
1149\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001150\end{methoddesc}
1151
1152\begin{methoddesc}{makeSocket}{}
1153The factory method of \class{SocketHandler} is here overridden to create
1154a UDP socket (\constant{socket.SOCK_DGRAM}).
1155\end{methoddesc}
1156
1157\begin{methoddesc}{send}{s}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001158Send a pickled string to a socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001159\end{methoddesc}
1160
1161\subsubsection{SysLogHandler}
1162
Vinay Sajip51f52352006-01-22 11:58:39 +00001163The \class{SysLogHandler} class, located in the
1164\module{logging.handlers} module, supports sending logging messages to
1165a remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001166
1167\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
1168Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +00001169communicate with a remote \UNIX{} machine whose address is given by
1170\var{address} in the form of a \code{(\var{host}, \var{port})}
1171tuple. If \var{address} is not specified, \code{('localhost', 514)} is
1172used. The address is used to open a UDP socket. If \var{facility} is
1173not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001174\end{classdesc}
1175
1176\begin{methoddesc}{close}{}
1177Closes the socket to the remote host.
1178\end{methoddesc}
1179
1180\begin{methoddesc}{emit}{record}
1181The record is formatted, and then sent to the syslog server. If
1182exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +00001183\end{methoddesc}
1184
1185\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001186Encodes the facility and priority into an integer. You can pass in strings
1187or integers - if strings are passed, internal mapping dictionaries are used
1188to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +00001189\end{methoddesc}
1190
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001191\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +00001192
Vinay Sajip51f52352006-01-22 11:58:39 +00001193The \class{NTEventLogHandler} class, located in the
1194\module{logging.handlers} module, supports sending logging messages to
1195a local Windows NT, Windows 2000 or Windows XP event log. Before you
1196can use it, you need Mark Hammond's Win32 extensions for Python
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001197installed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001198
Fred Drake9a5b6a62003-07-08 15:38:40 +00001199\begin{classdesc}{NTEventLogHandler}{appname\optional{,
1200 dllname\optional{, logtype}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001201Returns a new instance of the \class{NTEventLogHandler} class. The
1202\var{appname} is used to define the application name as it appears in the
1203event log. An appropriate registry entry is created using this name.
1204The \var{dllname} should give the fully qualified pathname of a .dll or .exe
1205which contains message definitions to hold in the log (if not specified,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001206\code{'win32service.pyd'} is used - this is installed with the Win32
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001207extensions and contains some basic placeholder message definitions.
1208Note that use of these placeholders will make your event logs big, as the
1209entire message source is held in the log. If you want slimmer logs, you have
1210to pass in the name of your own .dll or .exe which contains the message
1211definitions you want to use in the event log). The \var{logtype} is one of
Fred Drake9a5b6a62003-07-08 15:38:40 +00001212\code{'Application'}, \code{'System'} or \code{'Security'}, and
1213defaults to \code{'Application'}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001214\end{classdesc}
1215
1216\begin{methoddesc}{close}{}
1217At this point, you can remove the application name from the registry as a
1218source of event log entries. However, if you do this, you will not be able
1219to see the events as you intended in the Event Log Viewer - it needs to be
1220able to access the registry to get the .dll name. The current version does
1221not do this (in fact it doesn't do anything).
1222\end{methoddesc}
1223
1224\begin{methoddesc}{emit}{record}
1225Determines the message ID, event category and event type, and then logs the
1226message in the NT event log.
1227\end{methoddesc}
1228
1229\begin{methoddesc}{getEventCategory}{record}
1230Returns the event category for the record. Override this if you
1231want to specify your own categories. This version returns 0.
1232\end{methoddesc}
1233
1234\begin{methoddesc}{getEventType}{record}
1235Returns the event type for the record. Override this if you want
1236to specify your own types. This version does a mapping using the
1237handler's typemap attribute, which is set up in \method{__init__()}
1238to a dictionary which contains mappings for \constant{DEBUG},
1239\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
1240\constant{CRITICAL}. If you are using your own levels, you will either need
1241to override this method or place a suitable dictionary in the
1242handler's \var{typemap} attribute.
1243\end{methoddesc}
1244
1245\begin{methoddesc}{getMessageID}{record}
1246Returns the message ID for the record. If you are using your
1247own messages, you could do this by having the \var{msg} passed to the
1248logger being an ID rather than a format string. Then, in here,
1249you could use a dictionary lookup to get the message ID. This
1250version returns 1, which is the base message ID in
Fred Drake9a5b6a62003-07-08 15:38:40 +00001251\file{win32service.pyd}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001252\end{methoddesc}
1253
1254\subsubsection{SMTPHandler}
1255
Vinay Sajip51f52352006-01-22 11:58:39 +00001256The \class{SMTPHandler} class, located in the
1257\module{logging.handlers} module, supports sending logging messages to
1258an email address via SMTP.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001259
1260\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
1261Returns a new instance of the \class{SMTPHandler} class. The
1262instance is initialized with the from and to addresses and subject
Vinay Sajip84df97f2005-02-18 11:50:11 +00001263line of the email. The \var{toaddrs} should be a list of strings. To specify a
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001264non-standard SMTP port, use the (host, port) tuple format for the
1265\var{mailhost} argument. If you use a string, the standard SMTP port
1266is used.
1267\end{classdesc}
1268
1269\begin{methoddesc}{emit}{record}
1270Formats the record and sends it to the specified addressees.
1271\end{methoddesc}
1272
1273\begin{methoddesc}{getSubject}{record}
1274If you want to specify a subject line which is record-dependent,
1275override this method.
1276\end{methoddesc}
1277
1278\subsubsection{MemoryHandler}
1279
Vinay Sajip51f52352006-01-22 11:58:39 +00001280The \class{MemoryHandler} class, located in the
1281\module{logging.handlers} module, supports buffering of logging
1282records in memory, periodically flushing them to a \dfn{target}
1283handler. Flushing occurs whenever the buffer is full, or when an event
1284of a certain severity or greater is seen.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001285
1286\class{MemoryHandler} is a subclass of the more general
1287\class{BufferingHandler}, which is an abstract class. This buffers logging
1288records in memory. Whenever each record is added to the buffer, a
1289check is made by calling \method{shouldFlush()} to see if the buffer
1290should be flushed. If it should, then \method{flush()} is expected to
1291do the needful.
1292
1293\begin{classdesc}{BufferingHandler}{capacity}
1294Initializes the handler with a buffer of the specified capacity.
1295\end{classdesc}
1296
1297\begin{methoddesc}{emit}{record}
1298Appends the record to the buffer. If \method{shouldFlush()} returns true,
1299calls \method{flush()} to process the buffer.
1300\end{methoddesc}
1301
1302\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001303You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001304just zaps the buffer to empty.
1305\end{methoddesc}
1306
1307\begin{methoddesc}{shouldFlush}{record}
1308Returns true if the buffer is up to capacity. This method can be
1309overridden to implement custom flushing strategies.
1310\end{methoddesc}
1311
1312\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001313\optional{, target}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001314Returns a new instance of the \class{MemoryHandler} class. The
1315instance is initialized with a buffer size of \var{capacity}. If
1316\var{flushLevel} is not specified, \constant{ERROR} is used. If no
1317\var{target} is specified, the target will need to be set using
1318\method{setTarget()} before this handler does anything useful.
1319\end{classdesc}
1320
1321\begin{methoddesc}{close}{}
1322Calls \method{flush()}, sets the target to \constant{None} and
1323clears the buffer.
1324\end{methoddesc}
1325
1326\begin{methoddesc}{flush}{}
1327For a \class{MemoryHandler}, flushing means just sending the buffered
1328records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001329different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001330\end{methoddesc}
1331
1332\begin{methoddesc}{setTarget}{target}
1333Sets the target handler for this handler.
1334\end{methoddesc}
1335
1336\begin{methoddesc}{shouldFlush}{record}
1337Checks for buffer full or a record at the \var{flushLevel} or higher.
1338\end{methoddesc}
1339
1340\subsubsection{HTTPHandler}
1341
Vinay Sajip51f52352006-01-22 11:58:39 +00001342The \class{HTTPHandler} class, located in the
1343\module{logging.handlers} module, supports sending logging messages to
1344a Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001345
1346\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
1347Returns a new instance of the \class{HTTPHandler} class. The
1348instance is initialized with a host address, url and HTTP method.
Vinay Sajip00b5c932005-10-29 00:40:15 +00001349The \var{host} can be of the form \code{host:port}, should you need to
1350use a specific port number. If no \var{method} is specified, \samp{GET}
1351is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001352\end{classdesc}
1353
1354\begin{methoddesc}{emit}{record}
1355Sends the record to the Web server as an URL-encoded dictionary.
1356\end{methoddesc}
1357
1358\subsection{Formatter Objects}
1359
1360\class{Formatter}s have the following attributes and methods. They are
1361responsible for converting a \class{LogRecord} to (usually) a string
1362which can be interpreted by either a human or an external system. The
1363base
1364\class{Formatter} allows a formatting string to be specified. If none is
Fred Drake8efc74d2004-04-15 06:18:48 +00001365supplied, the default value of \code{'\%(message)s'} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001366
1367A Formatter can be initialized with a format string which makes use of
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001368knowledge of the \class{LogRecord} attributes - such as the default value
1369mentioned above making use of the fact that the user's message and
Fred Drake6b3b0462004-04-09 18:26:40 +00001370arguments are pre-formatted into a \class{LogRecord}'s \var{message}
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001371attribute. This format string contains standard python \%-style
1372mapping keys. See section \ref{typesseq-strings}, ``String Formatting
1373Operations,'' for more information on string formatting.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001374
Fred Drake6b3b0462004-04-09 18:26:40 +00001375Currently, the useful mapping keys in a \class{LogRecord} are:
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001376
Fred Drake9a5b6a62003-07-08 15:38:40 +00001377\begin{tableii}{l|l}{code}{Format}{Description}
1378\lineii{\%(name)s} {Name of the logger (logging channel).}
1379\lineii{\%(levelno)s} {Numeric logging level for the message
1380 (\constant{DEBUG}, \constant{INFO},
1381 \constant{WARNING}, \constant{ERROR},
1382 \constant{CRITICAL}).}
1383\lineii{\%(levelname)s}{Text logging level for the message
1384 (\code{'DEBUG'}, \code{'INFO'},
1385 \code{'WARNING'}, \code{'ERROR'},
1386 \code{'CRITICAL'}).}
1387\lineii{\%(pathname)s} {Full pathname of the source file where the logging
1388 call was issued (if available).}
1389\lineii{\%(filename)s} {Filename portion of pathname.}
1390\lineii{\%(module)s} {Module (name portion of filename).}
Neal Norwitzc16dd482006-02-13 02:04:37 +00001391\lineii{\%(funcName)s} {Name of function containing the logging call.}
Fred Drake9a5b6a62003-07-08 15:38:40 +00001392\lineii{\%(lineno)d} {Source line number where the logging call was issued
1393 (if available).}
Fred Drake6b3b0462004-04-09 18:26:40 +00001394\lineii{\%(created)f} {Time when the \class{LogRecord} was created (as
Fred Drake9a5b6a62003-07-08 15:38:40 +00001395 returned by \function{time.time()}).}
Fred Drake6b3b0462004-04-09 18:26:40 +00001396\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
1397 was created. By default this is of the form
Fred Drake9a5b6a62003-07-08 15:38:40 +00001398 ``2003-07-08 16:49:45,896'' (the numbers after the
1399 comma are millisecond portion of the time).}
1400\lineii{\%(msecs)d} {Millisecond portion of the time when the
1401 \class{LogRecord} was created.}
1402\lineii{\%(thread)d} {Thread ID (if available).}
Vinay Sajip99358df2005-03-31 20:18:06 +00001403\lineii{\%(threadName)s} {Thread name (if available).}
Fred Drake9a5b6a62003-07-08 15:38:40 +00001404\lineii{\%(process)d} {Process ID (if available).}
1405\lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001406\end{tableii}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001407
Neal Norwitzc16dd482006-02-13 02:04:37 +00001408\versionchanged[\var{funcName} was added]{2.5}
1409
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001410\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
1411Returns a new instance of the \class{Formatter} class. The
1412instance is initialized with a format string for the message as a whole,
1413as well as a format string for the date/time portion of a message. If
Neal Norwitzdd3afa72003-07-08 16:26:34 +00001414no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001415is specified, the ISO8601 date format is used.
1416\end{classdesc}
1417
1418\begin{methoddesc}{format}{record}
1419The record's attribute dictionary is used as the operand to a
1420string formatting operation. Returns the resulting string.
1421Before formatting the dictionary, a couple of preparatory steps
1422are carried out. The \var{message} attribute of the record is computed
1423using \var{msg} \% \var{args}. If the formatting string contains
Fred Drake9a5b6a62003-07-08 15:38:40 +00001424\code{'(asctime)'}, \method{formatTime()} is called to format the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001425event time. If there is exception information, it is formatted using
1426\method{formatException()} and appended to the message.
1427\end{methoddesc}
1428
1429\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
1430This method should be called from \method{format()} by a formatter which
1431wants to make use of a formatted time. This method can be overridden
1432in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001433basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +00001434it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001435record. Otherwise, the ISO8601 format is used. The resulting
1436string is returned.
1437\end{methoddesc}
1438
1439\begin{methoddesc}{formatException}{exc_info}
1440Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +00001441as returned by \function{sys.exc_info()}) as a string. This default
1442implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001443The resulting string is returned.
1444\end{methoddesc}
1445
1446\subsection{Filter Objects}
1447
1448\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
1449more sophisticated filtering than is provided by levels. The base filter
1450class only allows events which are below a certain point in the logger
1451hierarchy. For example, a filter initialized with "A.B" will allow events
1452logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
1453"B.A.B" etc. If initialized with the empty string, all events are passed.
1454
1455\begin{classdesc}{Filter}{\optional{name}}
1456Returns an instance of the \class{Filter} class. If \var{name} is specified,
1457it names a logger which, together with its children, will have its events
1458allowed through the filter. If no name is specified, allows every event.
1459\end{classdesc}
1460
1461\begin{methoddesc}{filter}{record}
1462Is the specified record to be logged? Returns zero for no, nonzero for
1463yes. If deemed appropriate, the record may be modified in-place by this
1464method.
1465\end{methoddesc}
1466
1467\subsection{LogRecord Objects}
1468
Fred Drake6b3b0462004-04-09 18:26:40 +00001469\class{LogRecord} instances are created every time something is logged. They
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001470contain all the information pertinent to the event being logged. The
1471main information passed in is in msg and args, which are combined
1472using msg \% args to create the message field of the record. The record
1473also includes information such as when the record was created, the
1474source line where the logging call was made, and any exception
1475information to be logged.
1476
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001477\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001478 exc_info}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001479Returns an instance of \class{LogRecord} initialized with interesting
1480information. The \var{name} is the logger name; \var{lvl} is the
1481numeric level; \var{pathname} is the absolute pathname of the source
1482file in which the logging call was made; \var{lineno} is the line
1483number in that file where the logging call is found; \var{msg} is the
1484user-supplied message (a format string); \var{args} is the tuple
1485which, together with \var{msg}, makes up the user message; and
1486\var{exc_info} is the exception tuple obtained by calling
1487\function{sys.exc_info() }(or \constant{None}, if no exception information
1488is available).
1489\end{classdesc}
1490
Vinay Sajipe8fdc452004-12-02 21:27:42 +00001491\begin{methoddesc}{getMessage}{}
1492Returns the message for this \class{LogRecord} instance after merging any
1493user-supplied arguments with the message.
1494\end{methoddesc}
1495
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001496\subsection{Thread Safety}
1497
1498The logging module is intended to be thread-safe without any special work
1499needing to be done by its clients. It achieves this though using threading
1500locks; there is one lock to serialize access to the module's shared data,
1501and each handler also creates a lock to serialize access to its underlying
1502I/O.
1503
1504\subsection{Configuration}
1505
1506
Fred Drake94ffbb72004-04-08 19:44:31 +00001507\subsubsection{Configuration functions%
1508 \label{logging-config-api}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001509
Vinay Sajip51f52352006-01-22 11:58:39 +00001510The following functions configure the logging module. They are located in the
1511\module{logging.config} module. Their use is optional --- you can configure
1512the logging module using these functions or by making calls to the
1513main API (defined in \module{logging} itself) and defining handlers
1514which are declared either in \module{logging} or
1515\module{logging.handlers}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001516
1517\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
1518Reads the logging configuration from a ConfigParser-format file named
1519\var{fname}. This function can be called several times from an application,
1520allowing an end user the ability to select from various pre-canned
1521configurations (if the developer provides a mechanism to present the
1522choices and load the chosen configuration). Defaults to be passed to
1523ConfigParser can be specified in the \var{defaults} argument.
1524\end{funcdesc}
1525
1526\begin{funcdesc}{listen}{\optional{port}}
1527Starts up a socket server on the specified port, and listens for new
1528configurations. If no port is specified, the module's default
1529\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
1530will be sent as a file suitable for processing by \function{fileConfig()}.
1531Returns a \class{Thread} instance on which you can call \method{start()}
1532to start the server, and which you can \method{join()} when appropriate.
Vinay Sajip4c1423b2005-06-05 20:39:36 +00001533To stop the server, call \function{stopListening()}. To send a configuration
1534to the socket, read in the configuration file and send it to the socket
1535as a string of bytes preceded by a four-byte length packed in binary using
1536struct.\code{pack(">L", n)}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001537\end{funcdesc}
1538
1539\begin{funcdesc}{stopListening}{}
1540Stops the listening server which was created with a call to
1541\function{listen()}. This is typically called before calling \method{join()}
1542on the return value from \function{listen()}.
1543\end{funcdesc}
1544
Fred Drake94ffbb72004-04-08 19:44:31 +00001545\subsubsection{Configuration file format%
1546 \label{logging-config-fileformat}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001547
Fred Drake6b3b0462004-04-09 18:26:40 +00001548The configuration file format understood by \function{fileConfig()} is
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001549based on ConfigParser functionality. The file must contain sections
1550called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
1551which identify by name the entities of each type which are defined in
1552the file. For each such entity, there is a separate section which
1553identified how that entity is configured. Thus, for a logger named
1554\code{log01} in the \code{[loggers]} section, the relevant
1555configuration details are held in a section
1556\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
1557the \code{[handlers]} section will have its configuration held in a
1558section called \code{[handler_hand01]}, while a formatter called
1559\code{form01} in the \code{[formatters]} section will have its
1560configuration specified in a section called
1561\code{[formatter_form01]}. The root logger configuration must be
1562specified in a section called \code{[logger_root]}.
1563
1564Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001565
1566\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001567[loggers]
1568keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +00001569
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001570[handlers]
1571keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1572
1573[formatters]
1574keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +00001575\end{verbatim}
1576
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001577The root logger must specify a level and a list of handlers. An
1578example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001579
1580\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001581[logger_root]
1582level=NOTSET
1583handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +00001584\end{verbatim}
1585
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001586The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1587ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1588\code{NOTSET} means that all messages will be logged. Level values are
1589\function{eval()}uated in the context of the \code{logging} package's
1590namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +00001591
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001592The \code{handlers} entry is a comma-separated list of handler names,
1593which must appear in the \code{[handlers]} section. These names must
1594appear in the \code{[handlers]} section and have corresponding
1595sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +00001596
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001597For loggers other than the root logger, some additional information is
1598required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +00001599
1600\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001601[logger_parser]
1602level=DEBUG
1603handlers=hand01
1604propagate=1
1605qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001606\end{verbatim}
1607
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001608The \code{level} and \code{handlers} entries are interpreted as for
1609the root logger, except that if a non-root logger's level is specified
1610as \code{NOTSET}, the system consults loggers higher up the hierarchy
1611to determine the effective level of the logger. The \code{propagate}
1612entry is set to 1 to indicate that messages must propagate to handlers
1613higher up the logger hierarchy from this logger, or 0 to indicate that
1614messages are \strong{not} propagated to handlers up the hierarchy. The
1615\code{qualname} entry is the hierarchical channel name of the logger,
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001616that is to say the name used by the application to get the logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001617
1618Sections which specify handler configuration are exemplified by the
1619following.
1620
Skip Montanaro649698f2002-11-14 03:57:19 +00001621\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001622[handler_hand01]
1623class=StreamHandler
1624level=NOTSET
1625formatter=form01
1626args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001627\end{verbatim}
1628
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001629The \code{class} entry indicates the handler's class (as determined by
1630\function{eval()} in the \code{logging} package's namespace). The
1631\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1632to mean "log everything".
1633
1634The \code{formatter} entry indicates the key name of the formatter for
1635this handler. If blank, a default formatter
1636(\code{logging._defaultFormatter}) is used. If a name is specified, it
1637must appear in the \code{[formatters]} section and have a
1638corresponding section in the configuration file.
1639
1640The \code{args} entry, when \function{eval()}uated in the context of
1641the \code{logging} package's namespace, is the list of arguments to
1642the constructor for the handler class. Refer to the constructors for
1643the relevant handlers, or to the examples below, to see how typical
1644entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001645
1646\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001647[handler_hand02]
1648class=FileHandler
1649level=DEBUG
1650formatter=form02
1651args=('python.log', 'w')
1652
1653[handler_hand03]
1654class=handlers.SocketHandler
1655level=INFO
1656formatter=form03
1657args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1658
1659[handler_hand04]
1660class=handlers.DatagramHandler
1661level=WARN
1662formatter=form04
1663args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1664
1665[handler_hand05]
1666class=handlers.SysLogHandler
1667level=ERROR
1668formatter=form05
1669args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1670
1671[handler_hand06]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001672class=handlers.NTEventLogHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001673level=CRITICAL
1674formatter=form06
1675args=('Python Application', '', 'Application')
1676
1677[handler_hand07]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001678class=handlers.SMTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001679level=WARN
1680formatter=form07
1681args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1682
1683[handler_hand08]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001684class=handlers.MemoryHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001685level=NOTSET
1686formatter=form08
1687target=
1688args=(10, ERROR)
1689
1690[handler_hand09]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001691class=handlers.HTTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001692level=NOTSET
1693formatter=form09
1694args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001695\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001696
1697Sections which specify formatter configuration are typified by the following.
1698
1699\begin{verbatim}
1700[formatter_form01]
1701format=F1 %(asctime)s %(levelname)s %(message)s
1702datefmt=
Vinay Sajip51f52352006-01-22 11:58:39 +00001703class=logging.Formatter
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001704\end{verbatim}
1705
1706The \code{format} entry is the overall format string, and the
1707\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1708string. If empty, the package substitutes ISO8601 format date/times, which
1709is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1710The ISO8601 format also specifies milliseconds, which are appended to the
1711result of using the above format string, with a comma separator. An example
1712time in ISO8601 format is \code{2003-01-23 00:29:50,411}.
Vinay Sajip51f52352006-01-22 11:58:39 +00001713
1714The \code{class} entry is optional. It indicates the name of the
1715formatter's class (as a dotted module and class name.) This option is
1716useful for instantiating a \class{Formatter} subclass. Subclasses of
1717\class{Formatter} can present exception tracebacks in an expanded or
1718condensed format.