blob: f2e5ca609ac582f53d774938bef82d04ec3308b4 [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.
62When a logger decides to actually log an event, an \class{LogRecord}
63instance 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
186arguments which are merged into \var{msg}. The only keyword argument in
187\var{kwargs} which is inspected is \var{exc_info} which, if it does not
Vinay Sajip1dc5b1e2004-10-03 19:10:05 +0000188evaluate as false, causes exception information to be added to the logging
189message. If an exception tuple (in the format returned by
190\function{sys.exc_info()}) is provided, it is used; otherwise,
191\function{sys.exc_info()} is called to get the exception information.
Skip Montanaro649698f2002-11-14 03:57:19 +0000192\end{funcdesc}
193
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000194\begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
195Logs a message with level \constant{INFO} on the root logger.
196The arguments are interpreted as for \function{debug()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000197\end{funcdesc}
198
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000199\begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
200Logs a message with level \constant{WARNING} on the root logger.
201The arguments are interpreted as for \function{debug()}.
202\end{funcdesc}
203
204\begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
205Logs a message with level \constant{ERROR} on the root logger.
206The arguments are interpreted as for \function{debug()}.
207\end{funcdesc}
208
209\begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
210Logs a message with level \constant{CRITICAL} on the root logger.
211The arguments are interpreted as for \function{debug()}.
212\end{funcdesc}
213
214\begin{funcdesc}{exception}{msg\optional{, *args}}
215Logs a message with level \constant{ERROR} on the root logger.
216The arguments are interpreted as for \function{debug()}. Exception info
217is added to the logging message. This function should only be called
218from an exception handler.
219\end{funcdesc}
220
Vinay Sajip739d49e2004-09-24 11:46:44 +0000221\begin{funcdesc}{log}{level, msg\optional{, *args\optional{, **kwargs}}}
222Logs a message with level \var{level} on the root logger.
223The other arguments are interpreted as for \function{debug()}.
224\end{funcdesc}
225
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000226\begin{funcdesc}{disable}{lvl}
227Provides an overriding level \var{lvl} for all loggers which takes
228precedence over the logger's own level. When the need arises to
229temporarily throttle logging output down across the whole application,
230this function can be useful.
231\end{funcdesc}
232
233\begin{funcdesc}{addLevelName}{lvl, levelName}
234Associates level \var{lvl} with text \var{levelName} in an internal
235dictionary, which is used to map numeric levels to a textual
236representation, for example when a \class{Formatter} formats a message.
237This function can also be used to define your own levels. The only
238constraints are that all levels used must be registered using this
239function, levels should be positive integers and they should increase
240in increasing order of severity.
241\end{funcdesc}
242
243\begin{funcdesc}{getLevelName}{lvl}
244Returns the textual representation of logging level \var{lvl}. If the
245level is one of the predefined levels \constant{CRITICAL},
246\constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG}
247then you get the corresponding string. If you have associated levels
248with names using \function{addLevelName()} then the name you have associated
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000249with \var{lvl} is returned. If a numeric value corresponding to one of the
250defined levels is passed in, the corresponding string representation is
251returned. Otherwise, the string "Level \%s" \% lvl is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000252\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000253
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000254\begin{funcdesc}{makeLogRecord}{attrdict}
255Creates and returns a new \class{LogRecord} instance whose attributes are
256defined by \var{attrdict}. This function is useful for taking a pickled
257\class{LogRecord} attribute dictionary, sent over a socket, and reconstituting
258it as a \class{LogRecord} instance at the receiving end.
259\end{funcdesc}
260
Vinay Sajipc320c222005-07-29 11:52:19 +0000261\begin{funcdesc}{basicConfig}{\optional{**kwargs}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000262Does basic configuration for the logging system by creating a
263\class{StreamHandler} with a default \class{Formatter} and adding it to
264the root logger. The functions \function{debug()}, \function{info()},
265\function{warning()}, \function{error()} and \function{critical()} will call
266\function{basicConfig()} automatically if no handlers are defined for the
267root logger.
Vinay Sajipc320c222005-07-29 11:52:19 +0000268
269\versionchanged[Formerly, \function{basicConfig} did not take any keyword
270arguments]{2.4}
271
272The following keyword arguments are supported.
273
274\begin{tableii}{l|l}{code}{Format}{Description}
275\lineii{filename}{Specifies that a FileHandler be created, using the
276specified filename, rather than a StreamHandler.}
277\lineii{filemode}{Specifies the mode to open the file, if filename is
278specified (if filemode is unspecified, it defaults to 'a').}
279\lineii{format}{Use the specified format string for the handler.}
280\lineii{datefmt}{Use the specified date/time format.}
281\lineii{level}{Set the root logger level to the specified level.}
282\lineii{stream}{Use the specified stream to initialize the StreamHandler.
283Note that this argument is incompatible with 'filename' - if both
284are present, 'stream' is ignored.}
285\end{tableii}
286
Skip Montanaro649698f2002-11-14 03:57:19 +0000287\end{funcdesc}
288
Skip Montanaro649698f2002-11-14 03:57:19 +0000289\begin{funcdesc}{shutdown}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000290Informs the logging system to perform an orderly shutdown by flushing and
291closing all handlers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000292\end{funcdesc}
293
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000294\begin{funcdesc}{setLoggerClass}{klass}
295Tells the logging system to use the class \var{klass} when instantiating a
296logger. The class should define \method{__init__()} such that only a name
297argument is required, and the \method{__init__()} should call
298\method{Logger.__init__()}. This function is typically called before any
299loggers are instantiated by applications which need to use custom logger
300behavior.
301\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000302
Fred Drake68e6d572003-01-28 22:02:35 +0000303
304\begin{seealso}
305 \seepep{282}{A Logging System}
306 {The proposal which described this feature for inclusion in
307 the Python standard library.}
Fred Drake11514792004-01-08 14:59:02 +0000308 \seelink{http://www.red-dove.com/python_logging.html}
309 {Original Python \module{logging} package}
310 {This is the original source for the \module{logging}
311 package. The version of the package available from this
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000312 site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x,
313 which do not include the \module{logging} package in the standard
Fred Drake11514792004-01-08 14:59:02 +0000314 library.}
Fred Drake68e6d572003-01-28 22:02:35 +0000315\end{seealso}
316
317
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000318\subsection{Logger Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000319
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000320Loggers have the following attributes and methods. Note that Loggers are
321never instantiated directly, but always through the module-level function
322\function{logging.getLogger(name)}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000323
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000324\begin{datadesc}{propagate}
325If this evaluates to false, logging messages are not passed by this
326logger or by child loggers to higher level (ancestor) loggers. The
327constructor sets this attribute to 1.
Skip Montanaro649698f2002-11-14 03:57:19 +0000328\end{datadesc}
329
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000330\begin{methoddesc}{setLevel}{lvl}
331Sets the threshold for this logger to \var{lvl}. Logging messages
332which are less severe than \var{lvl} will be ignored. When a logger is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000333created, the level is set to \constant{NOTSET} (which causes all messages
Vinay Sajipe8fdc452004-12-02 21:27:42 +0000334to be processed when the logger is the root logger, or delegation to the
335parent when the logger is a non-root logger). Note that the root logger
336is created with level \constant{WARNING}.
Vinay Sajipd1c02392005-09-26 00:14:46 +0000337
338The term "delegation to the parent" means that if a logger has a level
339of NOTSET, its chain of ancestor loggers is traversed until either an
340ancestor with a level other than NOTSET is found, or the root is
341reached.
342
343If an ancestor is found with a level other than NOTSET, then that
344ancestor's level is treated as the effective level of the logger where
345the ancestor search began, and is used to determine how a logging
346event is handled.
347
348If the root is reached, and it has a level of NOTSET, then all
349messages will be processed. Otherwise, the root's level will be used
350as the effective level.
Skip Montanaro649698f2002-11-14 03:57:19 +0000351\end{methoddesc}
352
353\begin{methoddesc}{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000354Indicates if a message of severity \var{lvl} would be processed by
355this logger. This method checks first the module-level level set by
356\function{logging.disable(lvl)} and then the logger's effective level as
357determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000358\end{methoddesc}
359
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000360\begin{methoddesc}{getEffectiveLevel}{}
361Indicates the effective level for this logger. If a value other than
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000362\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000363Otherwise, the hierarchy is traversed towards the root until a value
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000364other than \constant{NOTSET} is found, and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000365\end{methoddesc}
366
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000367\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
368Logs a message with level \constant{DEBUG} on this logger.
369The \var{msg} is the message format string, and the \var{args} are the
370arguments which are merged into \var{msg}. The only keyword argument in
371\var{kwargs} which is inspected is \var{exc_info} which, if it does not
Vinay Sajip1dc5b1e2004-10-03 19:10:05 +0000372evaluate as false, causes exception information to be added to the logging
373message. If an exception tuple (as provided by \function{sys.exc_info()})
374is provided, it is used; otherwise, \function{sys.exc_info()} is called
375to get the exception information.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000376\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000377
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000378\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
379Logs a message with level \constant{INFO} on this logger.
380The arguments are interpreted as for \method{debug()}.
381\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000382
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000383\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
384Logs a message with level \constant{WARNING} on this logger.
385The arguments are interpreted as for \method{debug()}.
386\end{methoddesc}
387
388\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
389Logs a message with level \constant{ERROR} on this logger.
390The arguments are interpreted as for \method{debug()}.
391\end{methoddesc}
392
393\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
394Logs a message with level \constant{CRITICAL} on this logger.
395The arguments are interpreted as for \method{debug()}.
396\end{methoddesc}
397
398\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
Vinay Sajip1cf56d02004-08-04 08:36:44 +0000399Logs a message with integer level \var{lvl} on this logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000400The other arguments are interpreted as for \method{debug()}.
401\end{methoddesc}
402
403\begin{methoddesc}{exception}{msg\optional{, *args}}
404Logs a message with level \constant{ERROR} on this logger.
405The arguments are interpreted as for \method{debug()}. Exception info
406is added to the logging message. This method should only be called
407from an exception handler.
408\end{methoddesc}
409
410\begin{methoddesc}{addFilter}{filt}
411Adds the specified filter \var{filt} to this logger.
412\end{methoddesc}
413
414\begin{methoddesc}{removeFilter}{filt}
415Removes the specified filter \var{filt} from this logger.
416\end{methoddesc}
417
418\begin{methoddesc}{filter}{record}
419Applies this logger's filters to the record and returns a true value if
420the record is to be processed.
421\end{methoddesc}
422
423\begin{methoddesc}{addHandler}{hdlr}
424Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000425\end{methoddesc}
426
427\begin{methoddesc}{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000428Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000429\end{methoddesc}
430
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000431\begin{methoddesc}{findCaller}{}
432Finds the caller's source filename and line number. Returns the filename
433and line number as a 2-element tuple.
Skip Montanaro649698f2002-11-14 03:57:19 +0000434\end{methoddesc}
435
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000436\begin{methoddesc}{handle}{record}
437Handles a record by passing it to all handlers associated with this logger
438and its ancestors (until a false value of \var{propagate} is found).
439This method is used for unpickled records received from a socket, as well
440as those created locally. Logger-level filtering is applied using
441\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000442\end{methoddesc}
443
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000444\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info}
445This is a factory method which can be overridden in subclasses to create
446specialized \class{LogRecord} instances.
Skip Montanaro649698f2002-11-14 03:57:19 +0000447\end{methoddesc}
448
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000449\subsection{Basic example \label{minimal-example}}
450
Vinay Sajipc320c222005-07-29 11:52:19 +0000451\versionchanged[formerly \function{basicConfig} did not take any keyword
452arguments]{2.4}
453
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000454The \module{logging} package provides a lot of flexibility, and its
455configuration can appear daunting. This section demonstrates that simple
456use of the logging package is possible.
457
458The simplest example shows logging to the console:
459
460\begin{verbatim}
461import logging
462
463logging.debug('A debug message')
464logging.info('Some information')
465logging.warning('A shot across the bows')
466\end{verbatim}
467
468If you run the above script, you'll see this:
469\begin{verbatim}
470WARNING:root:A shot across the bows
471\end{verbatim}
472
473Because no particular logger was specified, the system used the root logger.
474The debug and info messages didn't appear because by default, the root
475logger is configured to only handle messages with a severity of WARNING
476or above. The message format is also a configuration default, as is the output
477destination of the messages - \code{sys.stderr}. The severity level,
478the message format and destination can be easily changed, as shown in
479the example below:
480
481\begin{verbatim}
482import logging
483
484logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000485 format='%(asctime)s %(levelname)s %(message)s',
486 filename='/tmp/myapp.log',
487 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000488logging.debug('A debug message')
489logging.info('Some information')
490logging.warning('A shot across the bows')
491\end{verbatim}
492
493The \method{basicConfig()} method is used to change the configuration
494defaults, which results in output (written to \code{/tmp/myapp.log})
495which should look something like the following:
496
497\begin{verbatim}
4982004-07-02 13:00:08,743 DEBUG A debug message
4992004-07-02 13:00:08,743 INFO Some information
5002004-07-02 13:00:08,743 WARNING A shot across the bows
501\end{verbatim}
502
503This time, all messages with a severity of DEBUG or above were handled,
504and the format of the messages was also changed, and output went to the
505specified file rather than the console.
506
507Formatting uses standard Python string formatting - see section
508\ref{typesseq-strings}. The format string takes the following
509common specifiers. For a complete list of specifiers, consult the
510\class{Formatter} documentation.
511
512\begin{tableii}{l|l}{code}{Format}{Description}
513\lineii{\%(name)s} {Name of the logger (logging channel).}
514\lineii{\%(levelname)s}{Text logging level for the message
515 (\code{'DEBUG'}, \code{'INFO'},
516 \code{'WARNING'}, \code{'ERROR'},
517 \code{'CRITICAL'}).}
518\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
519 was created. By default this is of the form
520 ``2003-07-08 16:49:45,896'' (the numbers after the
521 comma are millisecond portion of the time).}
522\lineii{\%(message)s} {The logged message.}
523\end{tableii}
524
525To change the date/time format, you can pass an additional keyword parameter,
526\var{datefmt}, as in the following:
527
528\begin{verbatim}
529import logging
530
531logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000532 format='%(asctime)s %(levelname)-8s %(message)s',
533 datefmt='%a, %d %b %Y %H:%M:%S',
534 filename='/temp/myapp.log',
535 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000536logging.debug('A debug message')
537logging.info('Some information')
538logging.warning('A shot across the bows')
539\end{verbatim}
540
541which would result in output like
542
543\begin{verbatim}
544Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
545Fri, 02 Jul 2004 13:06:18 INFO Some information
546Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
547\end{verbatim}
548
549The date format string follows the requirements of \function{strftime()} -
550see the documentation for the \refmodule{time} module.
551
552If, instead of sending logging output to the console or a file, you'd rather
553use a file-like object which you have created separately, you can pass it
554to \function{basicConfig()} using the \var{stream} keyword argument. Note
555that if both \var{stream} and \var{filename} keyword arguments are passed,
556the \var{stream} argument is ignored.
557
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000558Of course, you can put variable information in your output. To do this,
559simply have the message be a format string and pass in additional arguments
560containing the variable information, as in the following example:
561
562\begin{verbatim}
563import logging
564
565logging.basicConfig(level=logging.DEBUG,
566 format='%(asctime)s %(levelname)-8s %(message)s',
567 datefmt='%a, %d %b %Y %H:%M:%S',
568 filename='/temp/myapp.log',
569 filemode='w')
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000570logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000571\end{verbatim}
572
573which would result in
574
575\begin{verbatim}
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000576Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000577\end{verbatim}
578
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000579\subsection{Logging to multiple destinations \label{multiple-destinations}}
580
581Let's say you want to log to console and file with different message formats
582and in differing circumstances. Say you want to log messages with levels
583of DEBUG and higher to file, and those messages at level INFO and higher to
584the console. Let's also assume that the file should contain timestamps, but
585the console messages should not. Here's how you can achieve this:
586
587\begin{verbatim}
588import logging
589
Fred Drake048840c2004-10-29 14:35:42 +0000590# set up logging to file - see previous section for more details
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000591logging.basicConfig(level=logging.DEBUG,
592 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
593 datefmt='%m-%d %H:%M',
594 filename='/temp/myapp.log',
595 filemode='w')
Fred Drake048840c2004-10-29 14:35:42 +0000596# define a Handler which writes INFO messages or higher to the sys.stderr
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000597console = logging.StreamHandler()
598console.setLevel(logging.INFO)
Fred Drake048840c2004-10-29 14:35:42 +0000599# set a format which is simpler for console use
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000600formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Fred Drake048840c2004-10-29 14:35:42 +0000601# tell the handler to use this format
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000602console.setFormatter(formatter)
Fred Drake048840c2004-10-29 14:35:42 +0000603# add the handler to the root logger
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000604logging.getLogger('').addHandler(console)
605
Fred Drake048840c2004-10-29 14:35:42 +0000606# Now, we can log to the root logger, or any other logger. First the root...
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000607logging.info('Jackdaws love my big sphinx of quartz.')
608
Fred Drake048840c2004-10-29 14:35:42 +0000609# Now, define a couple of other loggers which might represent areas in your
610# application:
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000611
612logger1 = logging.getLogger('myapp.area1')
613logger2 = logging.getLogger('myapp.area2')
614
615logger1.debug('Quick zephyrs blow, vexing daft Jim.')
616logger1.info('How quickly daft jumping zebras vex.')
617logger2.warning('Jail zesty vixen who grabbed pay from quack.')
618logger2.error('The five boxing wizards jump quickly.')
619\end{verbatim}
620
621When you run this, on the console you will see
622
623\begin{verbatim}
624root : INFO Jackdaws love my big sphinx of quartz.
625myapp.area1 : INFO How quickly daft jumping zebras vex.
626myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
627myapp.area2 : ERROR The five boxing wizards jump quickly.
628\end{verbatim}
629
630and in the file you will see something like
631
632\begin{verbatim}
63310-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
63410-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
63510-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
63610-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
63710-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
638\end{verbatim}
639
640As you can see, the DEBUG message only shows up in the file. The other
641messages are sent to both destinations.
642
Vinay Sajip006483b2004-10-29 12:30:28 +0000643This example uses console and file handlers, but you can use any number and
644combination of handlers you choose.
645
646\subsection{Sending and receiving logging events across a network
647\label{network-logging}}
648
649Let's say you want to send logging events across a network, and handle them
650at the receiving end. A simple way of doing this is attaching a
651\class{SocketHandler} instance to the root logger at the sending end:
652
653\begin{verbatim}
654import logging, logging.handlers
655
656rootLogger = logging.getLogger('')
657rootLogger.setLevel(logging.DEBUG)
658socketHandler = logging.handlers.SocketHandler('localhost',
659 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
660# don't bother with a formatter, since a socket handler sends the event as
661# an unformatted pickle
662rootLogger.addHandler(socketHandler)
663
Fred Drake048840c2004-10-29 14:35:42 +0000664# Now, we can log to the root logger, or any other logger. First the root...
Vinay Sajip006483b2004-10-29 12:30:28 +0000665logging.info('Jackdaws love my big sphinx of quartz.')
666
Fred Drake048840c2004-10-29 14:35:42 +0000667# Now, define a couple of other loggers which might represent areas in your
668# application:
Vinay Sajip006483b2004-10-29 12:30:28 +0000669
670logger1 = logging.getLogger('myapp.area1')
671logger2 = logging.getLogger('myapp.area2')
672
673logger1.debug('Quick zephyrs blow, vexing daft Jim.')
674logger1.info('How quickly daft jumping zebras vex.')
675logger2.warning('Jail zesty vixen who grabbed pay from quack.')
676logger2.error('The five boxing wizards jump quickly.')
677\end{verbatim}
678
679At the receiving end, you can set up a receiver using the
680\module{SocketServer} module. Here is a basic working example:
681
682\begin{verbatim}
Fred Drake048840c2004-10-29 14:35:42 +0000683import cPickle
684import logging
685import logging.handlers
686import SocketServer
687import struct
Vinay Sajip006483b2004-10-29 12:30:28 +0000688
Vinay Sajip006483b2004-10-29 12:30:28 +0000689
Fred Drake048840c2004-10-29 14:35:42 +0000690class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
691 """Handler for a streaming logging request.
692
693 This basically logs the record using whatever logging policy is
694 configured locally.
Vinay Sajip006483b2004-10-29 12:30:28 +0000695 """
696
697 def handle(self):
698 """
699 Handle multiple requests - each expected to be a 4-byte length,
700 followed by the LogRecord in pickle format. Logs the record
701 according to whatever policy is configured locally.
702 """
703 while 1:
704 chunk = self.connection.recv(4)
705 if len(chunk) < 4:
706 break
707 slen = struct.unpack(">L", chunk)[0]
708 chunk = self.connection.recv(slen)
709 while len(chunk) < slen:
710 chunk = chunk + self.connection.recv(slen - len(chunk))
711 obj = self.unPickle(chunk)
712 record = logging.makeLogRecord(obj)
713 self.handleLogRecord(record)
714
715 def unPickle(self, data):
716 return cPickle.loads(data)
717
718 def handleLogRecord(self, record):
Fred Drake048840c2004-10-29 14:35:42 +0000719 # if a name is specified, we use the named logger rather than the one
720 # implied by the record.
Vinay Sajip006483b2004-10-29 12:30:28 +0000721 if self.server.logname is not None:
722 name = self.server.logname
723 else:
724 name = record.name
725 logger = logging.getLogger(name)
Fred Drake048840c2004-10-29 14:35:42 +0000726 # N.B. EVERY record gets logged. This is because Logger.handle
727 # is normally called AFTER logger-level filtering. If you want
728 # to do filtering, do it at the client end to save wasting
729 # cycles and network bandwidth!
Vinay Sajip006483b2004-10-29 12:30:28 +0000730 logger.handle(record)
731
Fred Drake048840c2004-10-29 14:35:42 +0000732class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
733 """simple TCP socket-based logging receiver suitable for testing.
Vinay Sajip006483b2004-10-29 12:30:28 +0000734 """
735
736 allow_reuse_address = 1
737
738 def __init__(self, host='localhost',
Fred Drake048840c2004-10-29 14:35:42 +0000739 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
740 handler=LogRecordStreamHandler):
741 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
Vinay Sajip006483b2004-10-29 12:30:28 +0000742 self.abort = 0
743 self.timeout = 1
744 self.logname = None
745
746 def serve_until_stopped(self):
747 import select
748 abort = 0
749 while not abort:
750 rd, wr, ex = select.select([self.socket.fileno()],
751 [], [],
752 self.timeout)
753 if rd:
754 self.handle_request()
755 abort = self.abort
756
757def main():
758 logging.basicConfig(
Vinay Sajipedde4922004-11-11 13:54:48 +0000759 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
Vinay Sajip006483b2004-10-29 12:30:28 +0000760 tcpserver = LogRecordSocketReceiver()
761 print "About to start TCP server..."
762 tcpserver.serve_until_stopped()
763
764if __name__ == "__main__":
765 main()
766\end{verbatim}
767
Vinay Sajipedde4922004-11-11 13:54:48 +0000768First run the server, and then the client. On the client side, nothing is
769printed on the console; on the server side, you should see something like:
Vinay Sajip006483b2004-10-29 12:30:28 +0000770
771\begin{verbatim}
772About to start TCP server...
773 59 root INFO Jackdaws love my big sphinx of quartz.
774 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
775 69 myapp.area1 INFO How quickly daft jumping zebras vex.
776 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
777 69 myapp.area2 ERROR The five boxing wizards jump quickly.
778\end{verbatim}
779
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000780\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000781
Fred Drake68e6d572003-01-28 22:02:35 +0000782Handlers have the following attributes and methods. Note that
783\class{Handler} is never instantiated directly; this class acts as a
784base for more useful subclasses. However, the \method{__init__()}
785method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000786
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000787\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000788Initializes the \class{Handler} instance by setting its level, setting
789the list of filters to the empty list and creating a lock (using
Raymond Hettingerc75c3e02003-09-01 22:50:52 +0000790\method{createLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000791\end{methoddesc}
792
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000793\begin{methoddesc}{createLock}{}
794Initializes a thread lock which can be used to serialize access to
795underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000796\end{methoddesc}
797
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000798\begin{methoddesc}{acquire}{}
799Acquires the thread lock created with \method{createLock()}.
800\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000801
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000802\begin{methoddesc}{release}{}
803Releases the thread lock acquired with \method{acquire()}.
804\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000805
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000806\begin{methoddesc}{setLevel}{lvl}
807Sets the threshold for this handler to \var{lvl}. Logging messages which are
808less severe than \var{lvl} will be ignored. When a handler is created, the
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000809level is set to \constant{NOTSET} (which causes all messages to be processed).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000810\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000811
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000812\begin{methoddesc}{setFormatter}{form}
813Sets the \class{Formatter} for this handler to \var{form}.
814\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000815
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000816\begin{methoddesc}{addFilter}{filt}
817Adds the specified filter \var{filt} to this handler.
818\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000819
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000820\begin{methoddesc}{removeFilter}{filt}
821Removes the specified filter \var{filt} from this handler.
822\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000823
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000824\begin{methoddesc}{filter}{record}
825Applies this handler's filters to the record and returns a true value if
826the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000827\end{methoddesc}
828
829\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000830Ensure all logging output has been flushed. This version does
831nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000832\end{methoddesc}
833
Skip Montanaro649698f2002-11-14 03:57:19 +0000834\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000835Tidy up any resources used by the handler. This version does
836nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000837\end{methoddesc}
838
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000839\begin{methoddesc}{handle}{record}
840Conditionally emits the specified logging record, depending on
841filters which may have been added to the handler. Wraps the actual
842emission of the record with acquisition/release of the I/O thread
843lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000844\end{methoddesc}
845
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000846\begin{methoddesc}{handleError}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000847This method should be called from handlers when an exception is
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000848encountered during an \method{emit()} call. By default it does nothing,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000849which means that exceptions get silently ignored. This is what is
850mostly wanted for a logging system - most users will not care
851about errors in the logging system, they are more interested in
852application errors. You could, however, replace this with a custom
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000853handler if you wish. The specified record is the one which was being
854processed when the exception occurred.
Skip Montanaro649698f2002-11-14 03:57:19 +0000855\end{methoddesc}
856
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000857\begin{methoddesc}{format}{record}
858Do formatting for a record - if a formatter is set, use it.
859Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000860\end{methoddesc}
861
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000862\begin{methoddesc}{emit}{record}
863Do whatever it takes to actually log the specified logging record.
864This version is intended to be implemented by subclasses and so
865raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000866\end{methoddesc}
867
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000868\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000869
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000870The \class{StreamHandler} class sends logging output to streams such as
871\var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more
872precisely, any object which supports \method{write()} and \method{flush()}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000873methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000874
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000875\begin{classdesc}{StreamHandler}{\optional{strm}}
876Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
877specified, the instance will use it for logging output; otherwise,
878\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000879\end{classdesc}
880
881\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000882If a formatter is specified, it is used to format the record.
883The record is then written to the stream with a trailing newline.
884If exception information is present, it is formatted using
885\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000886\end{methoddesc}
887
888\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000889Flushes the stream by calling its \method{flush()} method. Note that
890the \method{close()} method is inherited from \class{Handler} and
891so does nothing, so an explicit \method{flush()} call may be needed
892at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000893\end{methoddesc}
894
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000895\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000896
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000897The \class{FileHandler} class sends logging output to a disk file.
Fred Drake68e6d572003-01-28 22:02:35 +0000898It inherits the output functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000899
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000900\begin{classdesc}{FileHandler}{filename\optional{, mode}}
901Returns a new instance of the \class{FileHandler} class. The specified
902file is opened and used as the stream for logging. If \var{mode} is
Fred Drake9a5b6a62003-07-08 15:38:40 +0000903not specified, \constant{'a'} is used. By default, the file grows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000904indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000905\end{classdesc}
906
907\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000908Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000909\end{methoddesc}
910
911\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000912Outputs the record to the file.
913\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000914
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000915\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000916
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000917The \class{RotatingFileHandler} class supports rotation of disk log files.
918
Fred Drake9a5b6a62003-07-08 15:38:40 +0000919\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{,
920 maxBytes\optional{, backupCount}}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000921Returns a new instance of the \class{RotatingFileHandler} class. The
922specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +0000923\var{mode} is not specified, \code{'a'} is used. By default, the
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000924file grows indefinitely.
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000925
926You can use the \var{maxBytes} and
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000927\var{backupCount} values to allow the file to \dfn{rollover} at a
928predetermined size. When the size is about to be exceeded, the file is
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000929closed and a new file is silently opened for output. Rollover occurs
930whenever the current log file is nearly \var{maxBytes} in length; if
931\var{maxBytes} is zero, rollover never occurs. If \var{backupCount}
932is non-zero, the system will save old log files by appending the
933extensions ".1", ".2" etc., to the filename. For example, with
934a \var{backupCount} of 5 and a base file name of
935\file{app.log}, you would get \file{app.log},
936\file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being
937written to is always \file{app.log}. When this file is filled, it is
938closed and renamed to \file{app.log.1}, and if files \file{app.log.1},
939\file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2},
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000940\file{app.log.3} etc. respectively.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000941\end{classdesc}
942
943\begin{methoddesc}{doRollover}{}
944Does a rollover, as described above.
945\end{methoddesc}
946
947\begin{methoddesc}{emit}{record}
Johannes Gijsbersf1643222004-11-07 16:11:35 +0000948Outputs the record to the file, catering for rollover as described previously.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000949\end{methoddesc}
950
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +0000951\subsubsection{TimedRotatingFileHandler}
952
953The \class{TimedRotatingFileHandler} class supports rotation of disk log files
954at certain timed intervals.
955
956\begin{classdesc}{TimedRotatingFileHandler}{filename
957 \optional{,when
958 \optional{,interval
959 \optional{,backupCount}}}}
960
961Returns a new instance of the \class{TimedRotatingFileHandler} class. The
962specified file is opened and used as the stream for logging. On rotating
963it also sets the filename suffix. Rotating happens based on the product
Vinay Sajipedde4922004-11-11 13:54:48 +0000964of \var{when} and \var{interval}.
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +0000965
966You can use the \var{when} to specify the type of \var{interval}. The
967list of possible values is, note that they are not case sensitive:
968
969\begin{tableii}{l|l}{}{Value}{Type of interval}
970 \lineii{S}{Seconds}
971 \lineii{M}{Minutes}
972 \lineii{H}{Hours}
973 \lineii{D}{Days}
974 \lineii{W}{Week day (0=Monday)}
975 \lineii{midnight}{Roll over at midnight}
976\end{tableii}
977
978If \var{backupCount} is non-zero, the system will save old log files by
979appending the extensions ".1", ".2" etc., to the filename. For example,
980with a \var{backupCount} of 5 and a base file name of \file{app.log},
981you would get \file{app.log}, \file{app.log.1}, \file{app.log.2}, up to
982\file{app.log.5}. The file being written to is always \file{app.log}.
983When this file is filled, it is closed and renamed to \file{app.log.1},
984and if files \file{app.log.1}, \file{app.log.2}, etc. exist, then they
985are renamed to \file{app.log.2}, \file{app.log.3} etc. respectively.
986\end{classdesc}
987
988\begin{methoddesc}{doRollover}{}
989Does a rollover, as described above.
990\end{methoddesc}
991
992\begin{methoddesc}{emit}{record}
993Outputs the record to the file, catering for rollover as described
994above.
995\end{methoddesc}
996
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000997\subsubsection{SocketHandler}
998
999The \class{SocketHandler} class sends logging output to a network
1000socket. The base class uses a TCP socket.
1001
1002\begin{classdesc}{SocketHandler}{host, port}
1003Returns a new instance of the \class{SocketHandler} class intended to
1004communicate with a remote machine whose address is given by \var{host}
1005and \var{port}.
1006\end{classdesc}
1007
1008\begin{methoddesc}{close}{}
1009Closes the socket.
1010\end{methoddesc}
1011
1012\begin{methoddesc}{handleError}{}
1013\end{methoddesc}
1014
1015\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001016Pickles the record's attribute dictionary and writes it to the socket in
1017binary format. If there is an error with the socket, silently drops the
1018packet. If the connection was previously lost, re-establishes the connection.
Fred Drake6b3b0462004-04-09 18:26:40 +00001019To unpickle the record at the receiving end into a \class{LogRecord}, use the
1020\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001021\end{methoddesc}
1022
1023\begin{methoddesc}{handleError}{}
1024Handles an error which has occurred during \method{emit()}. The
1025most likely cause is a lost connection. Closes the socket so that
1026we can retry on the next event.
1027\end{methoddesc}
1028
1029\begin{methoddesc}{makeSocket}{}
1030This is a factory method which allows subclasses to define the precise
1031type of socket they want. The default implementation creates a TCP
1032socket (\constant{socket.SOCK_STREAM}).
1033\end{methoddesc}
1034
1035\begin{methoddesc}{makePickle}{record}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001036Pickles the record's attribute dictionary in binary format with a length
1037prefix, and returns it ready for transmission across the socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001038\end{methoddesc}
1039
1040\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001041Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001042for partial sends which can happen when the network is busy.
1043\end{methoddesc}
1044
1045\subsubsection{DatagramHandler}
1046
1047The \class{DatagramHandler} class inherits from \class{SocketHandler}
1048to support sending logging messages over UDP sockets.
1049
1050\begin{classdesc}{DatagramHandler}{host, port}
1051Returns a new instance of the \class{DatagramHandler} class intended to
1052communicate with a remote machine whose address is given by \var{host}
1053and \var{port}.
1054\end{classdesc}
1055
1056\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001057Pickles the record's attribute dictionary and writes it to the socket in
1058binary format. If there is an error with the socket, silently drops the
1059packet.
Fred Drake6b3b0462004-04-09 18:26:40 +00001060To unpickle the record at the receiving end into a \class{LogRecord}, use the
1061\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001062\end{methoddesc}
1063
1064\begin{methoddesc}{makeSocket}{}
1065The factory method of \class{SocketHandler} is here overridden to create
1066a UDP socket (\constant{socket.SOCK_DGRAM}).
1067\end{methoddesc}
1068
1069\begin{methoddesc}{send}{s}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001070Send a pickled string to a socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001071\end{methoddesc}
1072
1073\subsubsection{SysLogHandler}
1074
1075The \class{SysLogHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +00001076remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001077
1078\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
1079Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +00001080communicate with a remote \UNIX{} machine whose address is given by
1081\var{address} in the form of a \code{(\var{host}, \var{port})}
1082tuple. If \var{address} is not specified, \code{('localhost', 514)} is
1083used. The address is used to open a UDP socket. If \var{facility} is
1084not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001085\end{classdesc}
1086
1087\begin{methoddesc}{close}{}
1088Closes the socket to the remote host.
1089\end{methoddesc}
1090
1091\begin{methoddesc}{emit}{record}
1092The record is formatted, and then sent to the syslog server. If
1093exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +00001094\end{methoddesc}
1095
1096\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001097Encodes the facility and priority into an integer. You can pass in strings
1098or integers - if strings are passed, internal mapping dictionaries are used
1099to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +00001100\end{methoddesc}
1101
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001102\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +00001103
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001104The \class{NTEventLogHandler} class supports sending logging messages
1105to a local Windows NT, Windows 2000 or Windows XP event log. Before
1106you can use it, you need Mark Hammond's Win32 extensions for Python
1107installed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001108
Fred Drake9a5b6a62003-07-08 15:38:40 +00001109\begin{classdesc}{NTEventLogHandler}{appname\optional{,
1110 dllname\optional{, logtype}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001111Returns a new instance of the \class{NTEventLogHandler} class. The
1112\var{appname} is used to define the application name as it appears in the
1113event log. An appropriate registry entry is created using this name.
1114The \var{dllname} should give the fully qualified pathname of a .dll or .exe
1115which contains message definitions to hold in the log (if not specified,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001116\code{'win32service.pyd'} is used - this is installed with the Win32
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001117extensions and contains some basic placeholder message definitions.
1118Note that use of these placeholders will make your event logs big, as the
1119entire message source is held in the log. If you want slimmer logs, you have
1120to pass in the name of your own .dll or .exe which contains the message
1121definitions you want to use in the event log). The \var{logtype} is one of
Fred Drake9a5b6a62003-07-08 15:38:40 +00001122\code{'Application'}, \code{'System'} or \code{'Security'}, and
1123defaults to \code{'Application'}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001124\end{classdesc}
1125
1126\begin{methoddesc}{close}{}
1127At this point, you can remove the application name from the registry as a
1128source of event log entries. However, if you do this, you will not be able
1129to see the events as you intended in the Event Log Viewer - it needs to be
1130able to access the registry to get the .dll name. The current version does
1131not do this (in fact it doesn't do anything).
1132\end{methoddesc}
1133
1134\begin{methoddesc}{emit}{record}
1135Determines the message ID, event category and event type, and then logs the
1136message in the NT event log.
1137\end{methoddesc}
1138
1139\begin{methoddesc}{getEventCategory}{record}
1140Returns the event category for the record. Override this if you
1141want to specify your own categories. This version returns 0.
1142\end{methoddesc}
1143
1144\begin{methoddesc}{getEventType}{record}
1145Returns the event type for the record. Override this if you want
1146to specify your own types. This version does a mapping using the
1147handler's typemap attribute, which is set up in \method{__init__()}
1148to a dictionary which contains mappings for \constant{DEBUG},
1149\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
1150\constant{CRITICAL}. If you are using your own levels, you will either need
1151to override this method or place a suitable dictionary in the
1152handler's \var{typemap} attribute.
1153\end{methoddesc}
1154
1155\begin{methoddesc}{getMessageID}{record}
1156Returns the message ID for the record. If you are using your
1157own messages, you could do this by having the \var{msg} passed to the
1158logger being an ID rather than a format string. Then, in here,
1159you could use a dictionary lookup to get the message ID. This
1160version returns 1, which is the base message ID in
Fred Drake9a5b6a62003-07-08 15:38:40 +00001161\file{win32service.pyd}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001162\end{methoddesc}
1163
1164\subsubsection{SMTPHandler}
1165
1166The \class{SMTPHandler} class supports sending logging messages to an email
1167address via SMTP.
1168
1169\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
1170Returns a new instance of the \class{SMTPHandler} class. The
1171instance is initialized with the from and to addresses and subject
Vinay Sajip84df97f2005-02-18 11:50:11 +00001172line of the email. The \var{toaddrs} should be a list of strings. To specify a
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001173non-standard SMTP port, use the (host, port) tuple format for the
1174\var{mailhost} argument. If you use a string, the standard SMTP port
1175is used.
1176\end{classdesc}
1177
1178\begin{methoddesc}{emit}{record}
1179Formats the record and sends it to the specified addressees.
1180\end{methoddesc}
1181
1182\begin{methoddesc}{getSubject}{record}
1183If you want to specify a subject line which is record-dependent,
1184override this method.
1185\end{methoddesc}
1186
1187\subsubsection{MemoryHandler}
1188
1189The \class{MemoryHandler} supports buffering of logging records in memory,
1190periodically flushing them to a \dfn{target} handler. Flushing occurs
1191whenever the buffer is full, or when an event of a certain severity or
1192greater is seen.
1193
1194\class{MemoryHandler} is a subclass of the more general
1195\class{BufferingHandler}, which is an abstract class. This buffers logging
1196records in memory. Whenever each record is added to the buffer, a
1197check is made by calling \method{shouldFlush()} to see if the buffer
1198should be flushed. If it should, then \method{flush()} is expected to
1199do the needful.
1200
1201\begin{classdesc}{BufferingHandler}{capacity}
1202Initializes the handler with a buffer of the specified capacity.
1203\end{classdesc}
1204
1205\begin{methoddesc}{emit}{record}
1206Appends the record to the buffer. If \method{shouldFlush()} returns true,
1207calls \method{flush()} to process the buffer.
1208\end{methoddesc}
1209
1210\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001211You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001212just zaps the buffer to empty.
1213\end{methoddesc}
1214
1215\begin{methoddesc}{shouldFlush}{record}
1216Returns true if the buffer is up to capacity. This method can be
1217overridden to implement custom flushing strategies.
1218\end{methoddesc}
1219
1220\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001221\optional{, target}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001222Returns a new instance of the \class{MemoryHandler} class. The
1223instance is initialized with a buffer size of \var{capacity}. If
1224\var{flushLevel} is not specified, \constant{ERROR} is used. If no
1225\var{target} is specified, the target will need to be set using
1226\method{setTarget()} before this handler does anything useful.
1227\end{classdesc}
1228
1229\begin{methoddesc}{close}{}
1230Calls \method{flush()}, sets the target to \constant{None} and
1231clears the buffer.
1232\end{methoddesc}
1233
1234\begin{methoddesc}{flush}{}
1235For a \class{MemoryHandler}, flushing means just sending the buffered
1236records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001237different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001238\end{methoddesc}
1239
1240\begin{methoddesc}{setTarget}{target}
1241Sets the target handler for this handler.
1242\end{methoddesc}
1243
1244\begin{methoddesc}{shouldFlush}{record}
1245Checks for buffer full or a record at the \var{flushLevel} or higher.
1246\end{methoddesc}
1247
1248\subsubsection{HTTPHandler}
1249
1250The \class{HTTPHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +00001251Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001252
1253\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
1254Returns a new instance of the \class{HTTPHandler} class. The
1255instance is initialized with a host address, url and HTTP method.
Vinay Sajip00b5c932005-10-29 00:40:15 +00001256The \var{host} can be of the form \code{host:port}, should you need to
1257use a specific port number. If no \var{method} is specified, \samp{GET}
1258is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001259\end{classdesc}
1260
1261\begin{methoddesc}{emit}{record}
1262Sends the record to the Web server as an URL-encoded dictionary.
1263\end{methoddesc}
1264
1265\subsection{Formatter Objects}
1266
1267\class{Formatter}s have the following attributes and methods. They are
1268responsible for converting a \class{LogRecord} to (usually) a string
1269which can be interpreted by either a human or an external system. The
1270base
1271\class{Formatter} allows a formatting string to be specified. If none is
Fred Drake8efc74d2004-04-15 06:18:48 +00001272supplied, the default value of \code{'\%(message)s'} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001273
1274A Formatter can be initialized with a format string which makes use of
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001275knowledge of the \class{LogRecord} attributes - such as the default value
1276mentioned above making use of the fact that the user's message and
Fred Drake6b3b0462004-04-09 18:26:40 +00001277arguments are pre-formatted into a \class{LogRecord}'s \var{message}
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001278attribute. This format string contains standard python \%-style
1279mapping keys. See section \ref{typesseq-strings}, ``String Formatting
1280Operations,'' for more information on string formatting.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001281
Fred Drake6b3b0462004-04-09 18:26:40 +00001282Currently, the useful mapping keys in a \class{LogRecord} are:
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001283
Fred Drake9a5b6a62003-07-08 15:38:40 +00001284\begin{tableii}{l|l}{code}{Format}{Description}
1285\lineii{\%(name)s} {Name of the logger (logging channel).}
1286\lineii{\%(levelno)s} {Numeric logging level for the message
1287 (\constant{DEBUG}, \constant{INFO},
1288 \constant{WARNING}, \constant{ERROR},
1289 \constant{CRITICAL}).}
1290\lineii{\%(levelname)s}{Text logging level for the message
1291 (\code{'DEBUG'}, \code{'INFO'},
1292 \code{'WARNING'}, \code{'ERROR'},
1293 \code{'CRITICAL'}).}
1294\lineii{\%(pathname)s} {Full pathname of the source file where the logging
1295 call was issued (if available).}
1296\lineii{\%(filename)s} {Filename portion of pathname.}
1297\lineii{\%(module)s} {Module (name portion of filename).}
1298\lineii{\%(lineno)d} {Source line number where the logging call was issued
1299 (if available).}
Fred Drake6b3b0462004-04-09 18:26:40 +00001300\lineii{\%(created)f} {Time when the \class{LogRecord} was created (as
Fred Drake9a5b6a62003-07-08 15:38:40 +00001301 returned by \function{time.time()}).}
Fred Drake6b3b0462004-04-09 18:26:40 +00001302\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
1303 was created. By default this is of the form
Fred Drake9a5b6a62003-07-08 15:38:40 +00001304 ``2003-07-08 16:49:45,896'' (the numbers after the
1305 comma are millisecond portion of the time).}
1306\lineii{\%(msecs)d} {Millisecond portion of the time when the
1307 \class{LogRecord} was created.}
1308\lineii{\%(thread)d} {Thread ID (if available).}
Vinay Sajip99358df2005-03-31 20:18:06 +00001309\lineii{\%(threadName)s} {Thread name (if available).}
Fred Drake9a5b6a62003-07-08 15:38:40 +00001310\lineii{\%(process)d} {Process ID (if available).}
1311\lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001312\end{tableii}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001313
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001314\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
1315Returns a new instance of the \class{Formatter} class. The
1316instance is initialized with a format string for the message as a whole,
1317as well as a format string for the date/time portion of a message. If
Neal Norwitzdd3afa72003-07-08 16:26:34 +00001318no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001319is specified, the ISO8601 date format is used.
1320\end{classdesc}
1321
1322\begin{methoddesc}{format}{record}
1323The record's attribute dictionary is used as the operand to a
1324string formatting operation. Returns the resulting string.
1325Before formatting the dictionary, a couple of preparatory steps
1326are carried out. The \var{message} attribute of the record is computed
1327using \var{msg} \% \var{args}. If the formatting string contains
Fred Drake9a5b6a62003-07-08 15:38:40 +00001328\code{'(asctime)'}, \method{formatTime()} is called to format the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001329event time. If there is exception information, it is formatted using
1330\method{formatException()} and appended to the message.
1331\end{methoddesc}
1332
1333\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
1334This method should be called from \method{format()} by a formatter which
1335wants to make use of a formatted time. This method can be overridden
1336in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001337basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +00001338it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001339record. Otherwise, the ISO8601 format is used. The resulting
1340string is returned.
1341\end{methoddesc}
1342
1343\begin{methoddesc}{formatException}{exc_info}
1344Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +00001345as returned by \function{sys.exc_info()}) as a string. This default
1346implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001347The resulting string is returned.
1348\end{methoddesc}
1349
1350\subsection{Filter Objects}
1351
1352\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
1353more sophisticated filtering than is provided by levels. The base filter
1354class only allows events which are below a certain point in the logger
1355hierarchy. For example, a filter initialized with "A.B" will allow events
1356logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
1357"B.A.B" etc. If initialized with the empty string, all events are passed.
1358
1359\begin{classdesc}{Filter}{\optional{name}}
1360Returns an instance of the \class{Filter} class. If \var{name} is specified,
1361it names a logger which, together with its children, will have its events
1362allowed through the filter. If no name is specified, allows every event.
1363\end{classdesc}
1364
1365\begin{methoddesc}{filter}{record}
1366Is the specified record to be logged? Returns zero for no, nonzero for
1367yes. If deemed appropriate, the record may be modified in-place by this
1368method.
1369\end{methoddesc}
1370
1371\subsection{LogRecord Objects}
1372
Fred Drake6b3b0462004-04-09 18:26:40 +00001373\class{LogRecord} instances are created every time something is logged. They
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001374contain all the information pertinent to the event being logged. The
1375main information passed in is in msg and args, which are combined
1376using msg \% args to create the message field of the record. The record
1377also includes information such as when the record was created, the
1378source line where the logging call was made, and any exception
1379information to be logged.
1380
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001381\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001382 exc_info}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001383Returns an instance of \class{LogRecord} initialized with interesting
1384information. The \var{name} is the logger name; \var{lvl} is the
1385numeric level; \var{pathname} is the absolute pathname of the source
1386file in which the logging call was made; \var{lineno} is the line
1387number in that file where the logging call is found; \var{msg} is the
1388user-supplied message (a format string); \var{args} is the tuple
1389which, together with \var{msg}, makes up the user message; and
1390\var{exc_info} is the exception tuple obtained by calling
1391\function{sys.exc_info() }(or \constant{None}, if no exception information
1392is available).
1393\end{classdesc}
1394
Vinay Sajipe8fdc452004-12-02 21:27:42 +00001395\begin{methoddesc}{getMessage}{}
1396Returns the message for this \class{LogRecord} instance after merging any
1397user-supplied arguments with the message.
1398\end{methoddesc}
1399
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001400\subsection{Thread Safety}
1401
1402The logging module is intended to be thread-safe without any special work
1403needing to be done by its clients. It achieves this though using threading
1404locks; there is one lock to serialize access to the module's shared data,
1405and each handler also creates a lock to serialize access to its underlying
1406I/O.
1407
1408\subsection{Configuration}
1409
1410
Fred Drake94ffbb72004-04-08 19:44:31 +00001411\subsubsection{Configuration functions%
1412 \label{logging-config-api}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001413
Fred Drake9a5b6a62003-07-08 15:38:40 +00001414The following functions allow the logging module to be
1415configured. Before they can be used, you must import
1416\module{logging.config}. Their use is optional --- you can configure
1417the logging module entirely by making calls to the main API (defined
1418in \module{logging} itself) and defining handlers which are declared
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001419either in \module{logging} or \module{logging.handlers}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001420
1421\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
1422Reads the logging configuration from a ConfigParser-format file named
1423\var{fname}. This function can be called several times from an application,
1424allowing an end user the ability to select from various pre-canned
1425configurations (if the developer provides a mechanism to present the
1426choices and load the chosen configuration). Defaults to be passed to
1427ConfigParser can be specified in the \var{defaults} argument.
1428\end{funcdesc}
1429
1430\begin{funcdesc}{listen}{\optional{port}}
1431Starts up a socket server on the specified port, and listens for new
1432configurations. If no port is specified, the module's default
1433\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
1434will be sent as a file suitable for processing by \function{fileConfig()}.
1435Returns a \class{Thread} instance on which you can call \method{start()}
1436to start the server, and which you can \method{join()} when appropriate.
Vinay Sajip4c1423b2005-06-05 20:39:36 +00001437To stop the server, call \function{stopListening()}. To send a configuration
1438to the socket, read in the configuration file and send it to the socket
1439as a string of bytes preceded by a four-byte length packed in binary using
1440struct.\code{pack(">L", n)}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001441\end{funcdesc}
1442
1443\begin{funcdesc}{stopListening}{}
1444Stops the listening server which was created with a call to
1445\function{listen()}. This is typically called before calling \method{join()}
1446on the return value from \function{listen()}.
1447\end{funcdesc}
1448
Fred Drake94ffbb72004-04-08 19:44:31 +00001449\subsubsection{Configuration file format%
1450 \label{logging-config-fileformat}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001451
Fred Drake6b3b0462004-04-09 18:26:40 +00001452The configuration file format understood by \function{fileConfig()} is
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001453based on ConfigParser functionality. The file must contain sections
1454called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
1455which identify by name the entities of each type which are defined in
1456the file. For each such entity, there is a separate section which
1457identified how that entity is configured. Thus, for a logger named
1458\code{log01} in the \code{[loggers]} section, the relevant
1459configuration details are held in a section
1460\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
1461the \code{[handlers]} section will have its configuration held in a
1462section called \code{[handler_hand01]}, while a formatter called
1463\code{form01} in the \code{[formatters]} section will have its
1464configuration specified in a section called
1465\code{[formatter_form01]}. The root logger configuration must be
1466specified in a section called \code{[logger_root]}.
1467
1468Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001469
1470\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001471[loggers]
1472keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +00001473
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001474[handlers]
1475keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1476
1477[formatters]
1478keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +00001479\end{verbatim}
1480
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001481The root logger must specify a level and a list of handlers. An
1482example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001483
1484\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001485[logger_root]
1486level=NOTSET
1487handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +00001488\end{verbatim}
1489
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001490The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1491ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1492\code{NOTSET} means that all messages will be logged. Level values are
1493\function{eval()}uated in the context of the \code{logging} package's
1494namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +00001495
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001496The \code{handlers} entry is a comma-separated list of handler names,
1497which must appear in the \code{[handlers]} section. These names must
1498appear in the \code{[handlers]} section and have corresponding
1499sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +00001500
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001501For loggers other than the root logger, some additional information is
1502required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +00001503
1504\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001505[logger_parser]
1506level=DEBUG
1507handlers=hand01
1508propagate=1
1509qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001510\end{verbatim}
1511
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001512The \code{level} and \code{handlers} entries are interpreted as for
1513the root logger, except that if a non-root logger's level is specified
1514as \code{NOTSET}, the system consults loggers higher up the hierarchy
1515to determine the effective level of the logger. The \code{propagate}
1516entry is set to 1 to indicate that messages must propagate to handlers
1517higher up the logger hierarchy from this logger, or 0 to indicate that
1518messages are \strong{not} propagated to handlers up the hierarchy. The
1519\code{qualname} entry is the hierarchical channel name of the logger,
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001520that is to say the name used by the application to get the logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001521
1522Sections which specify handler configuration are exemplified by the
1523following.
1524
Skip Montanaro649698f2002-11-14 03:57:19 +00001525\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001526[handler_hand01]
1527class=StreamHandler
1528level=NOTSET
1529formatter=form01
1530args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001531\end{verbatim}
1532
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001533The \code{class} entry indicates the handler's class (as determined by
1534\function{eval()} in the \code{logging} package's namespace). The
1535\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1536to mean "log everything".
1537
1538The \code{formatter} entry indicates the key name of the formatter for
1539this handler. If blank, a default formatter
1540(\code{logging._defaultFormatter}) is used. If a name is specified, it
1541must appear in the \code{[formatters]} section and have a
1542corresponding section in the configuration file.
1543
1544The \code{args} entry, when \function{eval()}uated in the context of
1545the \code{logging} package's namespace, is the list of arguments to
1546the constructor for the handler class. Refer to the constructors for
1547the relevant handlers, or to the examples below, to see how typical
1548entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001549
1550\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001551[handler_hand02]
1552class=FileHandler
1553level=DEBUG
1554formatter=form02
1555args=('python.log', 'w')
1556
1557[handler_hand03]
1558class=handlers.SocketHandler
1559level=INFO
1560formatter=form03
1561args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1562
1563[handler_hand04]
1564class=handlers.DatagramHandler
1565level=WARN
1566formatter=form04
1567args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1568
1569[handler_hand05]
1570class=handlers.SysLogHandler
1571level=ERROR
1572formatter=form05
1573args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1574
1575[handler_hand06]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001576class=handlers.NTEventLogHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001577level=CRITICAL
1578formatter=form06
1579args=('Python Application', '', 'Application')
1580
1581[handler_hand07]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001582class=handlers.SMTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001583level=WARN
1584formatter=form07
1585args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1586
1587[handler_hand08]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001588class=handlers.MemoryHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001589level=NOTSET
1590formatter=form08
1591target=
1592args=(10, ERROR)
1593
1594[handler_hand09]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001595class=handlers.HTTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001596level=NOTSET
1597formatter=form09
1598args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001599\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001600
1601Sections which specify formatter configuration are typified by the following.
1602
1603\begin{verbatim}
1604[formatter_form01]
1605format=F1 %(asctime)s %(levelname)s %(message)s
1606datefmt=
1607\end{verbatim}
1608
1609The \code{format} entry is the overall format string, and the
1610\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1611string. If empty, the package substitutes ISO8601 format date/times, which
1612is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1613The ISO8601 format also specifies milliseconds, which are appended to the
1614result of using the above format string, with a comma separator. An example
1615time in ISO8601 format is \code{2003-01-23 00:29:50,411}.