blob: f450c078ba353a61cc37bd459973046fb3a788b9 [file] [log] [blame]
Skip Montanaro649698f2002-11-14 03:57:19 +00001\section{\module{logging} ---
2 Logging facility for Python}
3
4\declaremodule{standard}{logging} % standard library, in Python
5
6% These apply to all modules, and may be given more than once:
7
8\moduleauthor{Vinay Sajip}{vinay_sajip@red-dove.com}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00009\sectionauthor{Vinay Sajip}{vinay_sajip@red-dove.com}
Skip Montanaro649698f2002-11-14 03:57:19 +000010
Fred Drake68e6d572003-01-28 22:02:35 +000011\modulesynopsis{Logging module for Python based on \pep{282}.}
Skip Montanaro649698f2002-11-14 03:57:19 +000012
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000013\indexii{Errors}{logging}
Skip Montanaro649698f2002-11-14 03:57:19 +000014
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000015\versionadded{2.3}
16This module defines functions and classes which implement a flexible
17error logging system for applications.
Skip Montanaro649698f2002-11-14 03:57:19 +000018
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000019Logging is performed by calling methods on instances of the
20\class{Logger} class (hereafter called \dfn{loggers}). Each instance has a
21name, and they are conceptually arranged in a name space hierarchy
22using dots (periods) as separators. For example, a logger named
23"scan" is the parent of loggers "scan.text", "scan.html" and "scan.pdf".
24Logger names can be anything you want, and indicate the area of an
25application in which a logged message originates.
Skip Montanaro649698f2002-11-14 03:57:19 +000026
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000027Logged messages also have levels of importance associated with them.
28The default levels provided are \constant{DEBUG}, \constant{INFO},
29\constant{WARNING}, \constant{ERROR} and \constant{CRITICAL}. As a
30convenience, you indicate the importance of a logged message by calling
31an appropriate method of \class{Logger}. The methods are
Fred Drakec23e0192003-01-28 22:09:16 +000032\method{debug()}, \method{info()}, \method{warning()}, \method{error()} and
33\method{critical()}, which mirror the default levels. You are not
34constrained to use these levels: you can specify your own and use a
35more general \class{Logger} method, \method{log()}, which takes an
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000036explicit level argument.
Skip Montanaro649698f2002-11-14 03:57:19 +000037
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000038Levels can also be associated with loggers, being set either by the
39developer or through loading a saved logging configuration. When a
40logging method is called on a logger, the logger compares its own
41level with the level associated with the method call. If the logger's
42level is higher than the method call's, no logging message is actually
43generated. This is the basic mechanism controlling the verbosity of
44logging output.
Skip Montanaro649698f2002-11-14 03:57:19 +000045
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000046Logging messages are encoded as instances of the \class{LogRecord} class.
47When a logger decides to actually log an event, an \class{LogRecord}
48instance is created from the logging message.
Skip Montanaro649698f2002-11-14 03:57:19 +000049
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000050Logging messages are subjected to a dispatch mechanism through the
51use of \dfn{handlers}, which are instances of subclasses of the
52\class{Handler} class. Handlers are responsible for ensuring that a logged
53message (in the form of a \class{LogRecord}) ends up in a particular
54location (or set of locations) which is useful for the target audience for
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +000055that message (such as end users, support desk staff, system administrators,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000056developers). Handlers are passed \class{LogRecord} instances intended for
57particular destinations. Each logger can have zero, one or more handlers
58associated with it (via the \method{addHandler} method of \class{Logger}).
59In addition to any handlers directly associated with a logger,
Fred Drakec23e0192003-01-28 22:09:16 +000060\emph{all handlers associated with all ancestors of the logger} are
61called to dispatch the message.
Skip Montanaro649698f2002-11-14 03:57:19 +000062
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000063Just as for loggers, handlers can have levels associated with them.
64A handler's level acts as a filter in the same way as a logger's level does.
Fred Drakec23e0192003-01-28 22:09:16 +000065If a handler decides to actually dispatch an event, the \method{emit()} method
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000066is used to send the message to its destination. Most user-defined subclasses
Fred Drakec23e0192003-01-28 22:09:16 +000067of \class{Handler} will need to override this \method{emit()}.
Skip Montanaro649698f2002-11-14 03:57:19 +000068
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000069In addition to the base \class{Handler} class, many useful subclasses
70are provided:
Skip Montanaro649698f2002-11-14 03:57:19 +000071
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000072\begin{enumerate}
Skip Montanaro649698f2002-11-14 03:57:19 +000073
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000074\item \class{StreamHandler} instances send error messages to
75streams (file-like objects).
Skip Montanaro649698f2002-11-14 03:57:19 +000076
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000077\item \class{FileHandler} instances send error messages to disk
78files.
79
80\item \class{RotatingFileHandler} instances send error messages to disk
81files, with support for maximum log file sizes and log file rotation.
82
83\item \class{SocketHandler} instances send error messages to
84TCP/IP sockets.
85
86\item \class{DatagramHandler} instances send error messages to UDP
87sockets.
88
89\item \class{SMTPHandler} instances send error messages to a
90designated email address.
91
92\item \class{SysLogHandler} instances send error messages to a
Fred Drake68e6d572003-01-28 22:02:35 +000093\UNIX{} syslog daemon, possibly on a remote machine.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000094
95\item \class{NTEventLogHandler} instances send error messages to a
96Windows NT/2000/XP event log.
97
98\item \class{MemoryHandler} instances send error messages to a
99buffer in memory, which is flushed whenever specific criteria are
100met.
101
102\item \class{HTTPHandler} instances send error messages to an
Fred Drake68e6d572003-01-28 22:02:35 +0000103HTTP server using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000104
105\end{enumerate}
106
107The \class{StreamHandler} and \class{FileHandler} classes are defined
108in the core logging package. The other handlers are defined in a sub-
109module, \module{logging.handlers}. (There is also another sub-module,
110\module{logging.config}, for configuration functionality.)
111
112Logged messages are formatted for presentation through instances of the
113\class{Formatter} class. They are initialized with a format string
114suitable for use with the \% operator and a dictionary.
115
116For formatting multiple messages in a batch, instances of
117\class{BufferingFormatter} can be used. In addition to the format string
118(which is applied to each message in the batch), there is provision for
119header and trailer format strings.
120
121When filtering based on logger level and/or handler level is not enough,
122instances of \class{Filter} can be added to both \class{Logger} and
Fred Drakec23e0192003-01-28 22:09:16 +0000123\class{Handler} instances (through their \method{addFilter()} method).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000124Before deciding to process a message further, both loggers and handlers
125consult all their filters for permission. If any filter returns a false
126value, the message is not processed further.
127
128The basic \class{Filter} functionality allows filtering by specific logger
129name. If this feature is used, messages sent to the named logger and its
130children are allowed through the filter, and all others dropped.
131
132In addition to the classes described above, there are a number of module-
133level functions.
134
135\begin{funcdesc}{getLogger}{\optional{name}}
136Return a logger with the specified name or, if no name is specified, return
137a logger which is the root logger of the hierarchy.
138
139All calls to this function with a given name return the same logger instance.
140This means that logger instances never need to be passed between different
141parts of an application.
Skip Montanaro649698f2002-11-14 03:57:19 +0000142\end{funcdesc}
143
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000144\begin{funcdesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
145Logs a message with level \constant{DEBUG} on the root logger.
146The \var{msg} is the message format string, and the \var{args} are the
147arguments which are merged into \var{msg}. The only keyword argument in
148\var{kwargs} which is inspected is \var{exc_info} which, if it does not
149evaluate as false, causes exception information (via a call to
Fred Drakec23e0192003-01-28 22:09:16 +0000150\function{sys.exc_info()}) to be added to the logging message.
Skip Montanaro649698f2002-11-14 03:57:19 +0000151\end{funcdesc}
152
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000153\begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
154Logs a message with level \constant{INFO} on the root logger.
155The arguments are interpreted as for \function{debug()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000156\end{funcdesc}
157
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000158\begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
159Logs a message with level \constant{WARNING} on the root logger.
160The arguments are interpreted as for \function{debug()}.
161\end{funcdesc}
162
163\begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
164Logs a message with level \constant{ERROR} on the root logger.
165The arguments are interpreted as for \function{debug()}.
166\end{funcdesc}
167
168\begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
169Logs a message with level \constant{CRITICAL} on the root logger.
170The arguments are interpreted as for \function{debug()}.
171\end{funcdesc}
172
173\begin{funcdesc}{exception}{msg\optional{, *args}}
174Logs a message with level \constant{ERROR} on the root logger.
175The arguments are interpreted as for \function{debug()}. Exception info
176is added to the logging message. This function should only be called
177from an exception handler.
178\end{funcdesc}
179
180\begin{funcdesc}{disable}{lvl}
181Provides an overriding level \var{lvl} for all loggers which takes
182precedence over the logger's own level. When the need arises to
183temporarily throttle logging output down across the whole application,
184this function can be useful.
185\end{funcdesc}
186
187\begin{funcdesc}{addLevelName}{lvl, levelName}
188Associates level \var{lvl} with text \var{levelName} in an internal
189dictionary, which is used to map numeric levels to a textual
190representation, for example when a \class{Formatter} formats a message.
191This function can also be used to define your own levels. The only
192constraints are that all levels used must be registered using this
193function, levels should be positive integers and they should increase
194in increasing order of severity.
195\end{funcdesc}
196
197\begin{funcdesc}{getLevelName}{lvl}
198Returns the textual representation of logging level \var{lvl}. If the
199level is one of the predefined levels \constant{CRITICAL},
200\constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG}
201then you get the corresponding string. If you have associated levels
202with names using \function{addLevelName()} then the name you have associated
203with \var{lvl} is returned. Otherwise, the string "Level \%s" \% lvl is
204returned.
205\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000206
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000207\begin{funcdesc}{makeLogRecord}{attrdict}
208Creates and returns a new \class{LogRecord} instance whose attributes are
209defined by \var{attrdict}. This function is useful for taking a pickled
210\class{LogRecord} attribute dictionary, sent over a socket, and reconstituting
211it as a \class{LogRecord} instance at the receiving end.
212\end{funcdesc}
213
Skip Montanaro649698f2002-11-14 03:57:19 +0000214\begin{funcdesc}{basicConfig}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000215Does basic configuration for the logging system by creating a
216\class{StreamHandler} with a default \class{Formatter} and adding it to
217the root logger. The functions \function{debug()}, \function{info()},
218\function{warning()}, \function{error()} and \function{critical()} will call
219\function{basicConfig()} automatically if no handlers are defined for the
220root logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000221\end{funcdesc}
222
Skip Montanaro649698f2002-11-14 03:57:19 +0000223\begin{funcdesc}{shutdown}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000224Informs the logging system to perform an orderly shutdown by flushing and
225closing all handlers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000226\end{funcdesc}
227
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000228\begin{funcdesc}{setLoggerClass}{klass}
229Tells the logging system to use the class \var{klass} when instantiating a
230logger. The class should define \method{__init__()} such that only a name
231argument is required, and the \method{__init__()} should call
232\method{Logger.__init__()}. This function is typically called before any
233loggers are instantiated by applications which need to use custom logger
234behavior.
235\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000236
Fred Drake68e6d572003-01-28 22:02:35 +0000237
238\begin{seealso}
239 \seepep{282}{A Logging System}
240 {The proposal which described this feature for inclusion in
241 the Python standard library.}
242\end{seealso}
243
244
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000245\subsection{Logger Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000246
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000247Loggers have the following attributes and methods. Note that Loggers are
248never instantiated directly, but always through the module-level function
249\function{logging.getLogger(name)}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000250
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000251\begin{datadesc}{propagate}
252If this evaluates to false, logging messages are not passed by this
253logger or by child loggers to higher level (ancestor) loggers. The
254constructor sets this attribute to 1.
Skip Montanaro649698f2002-11-14 03:57:19 +0000255\end{datadesc}
256
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000257\begin{methoddesc}{setLevel}{lvl}
258Sets the threshold for this logger to \var{lvl}. Logging messages
259which are less severe than \var{lvl} will be ignored. When a logger is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000260created, the level is set to \constant{NOTSET} (which causes all messages
261to be processed in the root logger, or delegation to the parent in non-root
262loggers).
Skip Montanaro649698f2002-11-14 03:57:19 +0000263\end{methoddesc}
264
265\begin{methoddesc}{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000266Indicates if a message of severity \var{lvl} would be processed by
267this logger. This method checks first the module-level level set by
268\function{logging.disable(lvl)} and then the logger's effective level as
269determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000270\end{methoddesc}
271
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000272\begin{methoddesc}{getEffectiveLevel}{}
273Indicates the effective level for this logger. If a value other than
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000274\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000275Otherwise, the hierarchy is traversed towards the root until a value
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000276other than \constant{NOTSET} is found, and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000277\end{methoddesc}
278
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000279\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
280Logs a message with level \constant{DEBUG} on this logger.
281The \var{msg} is the message format string, and the \var{args} are the
282arguments which are merged into \var{msg}. The only keyword argument in
283\var{kwargs} which is inspected is \var{exc_info} which, if it does not
284evaluate as false, causes exception information (via a call to
Fred Drakec23e0192003-01-28 22:09:16 +0000285\function{sys.exc_info()}) to be added to the logging message.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000286\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000287
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000288\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
289Logs a message with level \constant{INFO} on this logger.
290The arguments are interpreted as for \method{debug()}.
291\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000292
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000293\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
294Logs a message with level \constant{WARNING} on this logger.
295The arguments are interpreted as for \method{debug()}.
296\end{methoddesc}
297
298\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
299Logs a message with level \constant{ERROR} on this logger.
300The arguments are interpreted as for \method{debug()}.
301\end{methoddesc}
302
303\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
304Logs a message with level \constant{CRITICAL} on this logger.
305The arguments are interpreted as for \method{debug()}.
306\end{methoddesc}
307
308\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
309Logs a message with level \var{lvl} on this logger.
310The other arguments are interpreted as for \method{debug()}.
311\end{methoddesc}
312
313\begin{methoddesc}{exception}{msg\optional{, *args}}
314Logs a message with level \constant{ERROR} on this logger.
315The arguments are interpreted as for \method{debug()}. Exception info
316is added to the logging message. This method should only be called
317from an exception handler.
318\end{methoddesc}
319
320\begin{methoddesc}{addFilter}{filt}
321Adds the specified filter \var{filt} to this logger.
322\end{methoddesc}
323
324\begin{methoddesc}{removeFilter}{filt}
325Removes the specified filter \var{filt} from this logger.
326\end{methoddesc}
327
328\begin{methoddesc}{filter}{record}
329Applies this logger's filters to the record and returns a true value if
330the record is to be processed.
331\end{methoddesc}
332
333\begin{methoddesc}{addHandler}{hdlr}
334Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000335\end{methoddesc}
336
337\begin{methoddesc}{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000338Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000339\end{methoddesc}
340
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000341\begin{methoddesc}{findCaller}{}
342Finds the caller's source filename and line number. Returns the filename
343and line number as a 2-element tuple.
Skip Montanaro649698f2002-11-14 03:57:19 +0000344\end{methoddesc}
345
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000346\begin{methoddesc}{handle}{record}
347Handles a record by passing it to all handlers associated with this logger
348and its ancestors (until a false value of \var{propagate} is found).
349This method is used for unpickled records received from a socket, as well
350as those created locally. Logger-level filtering is applied using
351\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000352\end{methoddesc}
353
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000354\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info}
355This is a factory method which can be overridden in subclasses to create
356specialized \class{LogRecord} instances.
Skip Montanaro649698f2002-11-14 03:57:19 +0000357\end{methoddesc}
358
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000359\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000360
Fred Drake68e6d572003-01-28 22:02:35 +0000361Handlers have the following attributes and methods. Note that
362\class{Handler} is never instantiated directly; this class acts as a
363base for more useful subclasses. However, the \method{__init__()}
364method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000365
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000366\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000367Initializes the \class{Handler} instance by setting its level, setting
368the list of filters to the empty list and creating a lock (using
369\method{getLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000370\end{methoddesc}
371
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000372\begin{methoddesc}{createLock}{}
373Initializes a thread lock which can be used to serialize access to
374underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000375\end{methoddesc}
376
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000377\begin{methoddesc}{acquire}{}
378Acquires the thread lock created with \method{createLock()}.
379\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000380
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000381\begin{methoddesc}{release}{}
382Releases the thread lock acquired with \method{acquire()}.
383\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000384
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000385\begin{methoddesc}{setLevel}{lvl}
386Sets the threshold for this handler to \var{lvl}. Logging messages which are
387less severe than \var{lvl} will be ignored. When a handler is created, the
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000388level is set to \constant{NOTSET} (which causes all messages to be processed).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000389\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000390
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000391\begin{methoddesc}{setFormatter}{form}
392Sets the \class{Formatter} for this handler to \var{form}.
393\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000394
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000395\begin{methoddesc}{addFilter}{filt}
396Adds the specified filter \var{filt} to this handler.
397\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000398
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000399\begin{methoddesc}{removeFilter}{filt}
400Removes the specified filter \var{filt} from this handler.
401\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000402
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000403\begin{methoddesc}{filter}{record}
404Applies this handler's filters to the record and returns a true value if
405the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000406\end{methoddesc}
407
408\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000409Ensure all logging output has been flushed. This version does
410nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000411\end{methoddesc}
412
Skip Montanaro649698f2002-11-14 03:57:19 +0000413\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000414Tidy up any resources used by the handler. This version does
415nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000416\end{methoddesc}
417
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000418\begin{methoddesc}{handle}{record}
419Conditionally emits the specified logging record, depending on
420filters which may have been added to the handler. Wraps the actual
421emission of the record with acquisition/release of the I/O thread
422lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000423\end{methoddesc}
424
425\begin{methoddesc}{handleError}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000426This method should be called from handlers when an exception is
427encountered during an emit() call. By default it does nothing,
428which means that exceptions get silently ignored. This is what is
429mostly wanted for a logging system - most users will not care
430about errors in the logging system, they are more interested in
431application errors. You could, however, replace this with a custom
432handler if you wish.
Skip Montanaro649698f2002-11-14 03:57:19 +0000433\end{methoddesc}
434
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000435\begin{methoddesc}{format}{record}
436Do formatting for a record - if a formatter is set, use it.
437Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000438\end{methoddesc}
439
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000440\begin{methoddesc}{emit}{record}
441Do whatever it takes to actually log the specified logging record.
442This version is intended to be implemented by subclasses and so
443raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000444\end{methoddesc}
445
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000446\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000447
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000448The \class{StreamHandler} class sends logging output to streams such as
449\var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more
450precisely, any object which supports \method{write()} and \method{flush()}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000451methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000452
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000453\begin{classdesc}{StreamHandler}{\optional{strm}}
454Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
455specified, the instance will use it for logging output; otherwise,
456\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000457\end{classdesc}
458
459\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000460If a formatter is specified, it is used to format the record.
461The record is then written to the stream with a trailing newline.
462If exception information is present, it is formatted using
463\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000464\end{methoddesc}
465
466\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000467Flushes the stream by calling its \method{flush()} method. Note that
468the \method{close()} method is inherited from \class{Handler} and
469so does nothing, so an explicit \method{flush()} call may be needed
470at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000471\end{methoddesc}
472
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000473\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000474
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000475The \class{FileHandler} class sends logging output to a disk file.
Fred Drake68e6d572003-01-28 22:02:35 +0000476It inherits the output functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000477
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000478\begin{classdesc}{FileHandler}{filename\optional{, mode}}
479Returns a new instance of the \class{FileHandler} class. The specified
480file is opened and used as the stream for logging. If \var{mode} is
481not specified, \constant{"a"} is used. By default, the file grows
482indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000483\end{classdesc}
484
485\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000486Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000487\end{methoddesc}
488
489\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000490Outputs the record to the file.
491\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000492
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000493\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000494
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000495The \class{RotatingFileHandler} class supports rotation of disk log files.
496
497\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode, maxBytes,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000498 backupCount}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000499Returns a new instance of the \class{RotatingFileHandler} class. The
500specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +0000501\var{mode} is not specified, \code{'a'} is used. By default, the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000502file grows indefinitely. You can use the \var{maxBytes} and
503\var{backupCount} values to allow the file to \dfn{rollover} at a
504predetermined size. When the size is about to be exceeded, the file is
505closed and a new file opened for output, transparently to the
506caller. Rollover occurs whenever the current log file is nearly
507\var{maxBytes} in length. If \var{backupCount} is >= 1, the system
508will successively create new files with the same pathname as the base
509file, but with extensions ".1", ".2" etc. appended to it. For example,
510with a backupCount of 5 and a base file name of "app.log", you would
511get "app.log", "app.log.1", "app.log.2", ... through to
512"app.log.5". When the last file reaches its size limit, the logging
513reverts to "app.log" which is truncated to zero length. If
514\var{maxBytes} is zero, rollover never occurs.
515\end{classdesc}
516
517\begin{methoddesc}{doRollover}{}
518Does a rollover, as described above.
519\end{methoddesc}
520
521\begin{methoddesc}{emit}{record}
522Outputs the record to the file, catering for rollover as described
523in \method{setRollover()}.
524\end{methoddesc}
525
526\subsubsection{SocketHandler}
527
528The \class{SocketHandler} class sends logging output to a network
529socket. The base class uses a TCP socket.
530
531\begin{classdesc}{SocketHandler}{host, port}
532Returns a new instance of the \class{SocketHandler} class intended to
533communicate with a remote machine whose address is given by \var{host}
534and \var{port}.
535\end{classdesc}
536
537\begin{methoddesc}{close}{}
538Closes the socket.
539\end{methoddesc}
540
541\begin{methoddesc}{handleError}{}
542\end{methoddesc}
543
544\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000545Pickles the record's attribute dictionary and writes it to the socket in
546binary format. If there is an error with the socket, silently drops the
547packet. If the connection was previously lost, re-establishes the connection.
548To unpickle the record at the receiving end into a LogRecord, use the
549\function{makeLogRecord} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000550\end{methoddesc}
551
552\begin{methoddesc}{handleError}{}
553Handles an error which has occurred during \method{emit()}. The
554most likely cause is a lost connection. Closes the socket so that
555we can retry on the next event.
556\end{methoddesc}
557
558\begin{methoddesc}{makeSocket}{}
559This is a factory method which allows subclasses to define the precise
560type of socket they want. The default implementation creates a TCP
561socket (\constant{socket.SOCK_STREAM}).
562\end{methoddesc}
563
564\begin{methoddesc}{makePickle}{record}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000565Pickles the record's attribute dictionary in binary format with a length
566prefix, and returns it ready for transmission across the socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000567\end{methoddesc}
568
569\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000570Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000571for partial sends which can happen when the network is busy.
572\end{methoddesc}
573
574\subsubsection{DatagramHandler}
575
576The \class{DatagramHandler} class inherits from \class{SocketHandler}
577to support sending logging messages over UDP sockets.
578
579\begin{classdesc}{DatagramHandler}{host, port}
580Returns a new instance of the \class{DatagramHandler} class intended to
581communicate with a remote machine whose address is given by \var{host}
582and \var{port}.
583\end{classdesc}
584
585\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000586Pickles the record's attribute dictionary and writes it to the socket in
587binary format. If there is an error with the socket, silently drops the
588packet.
589To unpickle the record at the receiving end into a LogRecord, use the
590\function{makeLogRecord} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000591\end{methoddesc}
592
593\begin{methoddesc}{makeSocket}{}
594The factory method of \class{SocketHandler} is here overridden to create
595a UDP socket (\constant{socket.SOCK_DGRAM}).
596\end{methoddesc}
597
598\begin{methoddesc}{send}{s}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000599Send a pickled string to a socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000600\end{methoddesc}
601
602\subsubsection{SysLogHandler}
603
604The \class{SysLogHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000605remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000606
607\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
608Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +0000609communicate with a remote \UNIX{} machine whose address is given by
610\var{address} in the form of a \code{(\var{host}, \var{port})}
611tuple. If \var{address} is not specified, \code{('localhost', 514)} is
612used. The address is used to open a UDP socket. If \var{facility} is
613not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000614\end{classdesc}
615
616\begin{methoddesc}{close}{}
617Closes the socket to the remote host.
618\end{methoddesc}
619
620\begin{methoddesc}{emit}{record}
621The record is formatted, and then sent to the syslog server. If
622exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +0000623\end{methoddesc}
624
625\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000626Encodes the facility and priority into an integer. You can pass in strings
627or integers - if strings are passed, internal mapping dictionaries are used
628to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000629\end{methoddesc}
630
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000631\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000632
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000633The \class{NTEventLogHandler} class supports sending logging messages
634to a local Windows NT, Windows 2000 or Windows XP event log. Before
635you can use it, you need Mark Hammond's Win32 extensions for Python
636installed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000637
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000638\begin{classdesc}{NTEventLogHandler}{appname
639 \optional{, dllname\optional{, logtype}}}
640Returns a new instance of the \class{NTEventLogHandler} class. The
641\var{appname} is used to define the application name as it appears in the
642event log. An appropriate registry entry is created using this name.
643The \var{dllname} should give the fully qualified pathname of a .dll or .exe
644which contains message definitions to hold in the log (if not specified,
645\constant{"win32service.pyd"} is used - this is installed with the Win32
646extensions and contains some basic placeholder message definitions.
647Note that use of these placeholders will make your event logs big, as the
648entire message source is held in the log. If you want slimmer logs, you have
649to pass in the name of your own .dll or .exe which contains the message
650definitions you want to use in the event log). The \var{logtype} is one of
651\constant{"Application"}, \constant{"System"} or \constant{"Security"}, and
652defaults to \constant{"Application"}.
653\end{classdesc}
654
655\begin{methoddesc}{close}{}
656At this point, you can remove the application name from the registry as a
657source of event log entries. However, if you do this, you will not be able
658to see the events as you intended in the Event Log Viewer - it needs to be
659able to access the registry to get the .dll name. The current version does
660not do this (in fact it doesn't do anything).
661\end{methoddesc}
662
663\begin{methoddesc}{emit}{record}
664Determines the message ID, event category and event type, and then logs the
665message in the NT event log.
666\end{methoddesc}
667
668\begin{methoddesc}{getEventCategory}{record}
669Returns the event category for the record. Override this if you
670want to specify your own categories. This version returns 0.
671\end{methoddesc}
672
673\begin{methoddesc}{getEventType}{record}
674Returns the event type for the record. Override this if you want
675to specify your own types. This version does a mapping using the
676handler's typemap attribute, which is set up in \method{__init__()}
677to a dictionary which contains mappings for \constant{DEBUG},
678\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
679\constant{CRITICAL}. If you are using your own levels, you will either need
680to override this method or place a suitable dictionary in the
681handler's \var{typemap} attribute.
682\end{methoddesc}
683
684\begin{methoddesc}{getMessageID}{record}
685Returns the message ID for the record. If you are using your
686own messages, you could do this by having the \var{msg} passed to the
687logger being an ID rather than a format string. Then, in here,
688you could use a dictionary lookup to get the message ID. This
689version returns 1, which is the base message ID in
690\constant{win32service.pyd}.
691\end{methoddesc}
692
693\subsubsection{SMTPHandler}
694
695The \class{SMTPHandler} class supports sending logging messages to an email
696address via SMTP.
697
698\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
699Returns a new instance of the \class{SMTPHandler} class. The
700instance is initialized with the from and to addresses and subject
701line of the email. The \var{toaddrs} should be a list of strings without
702domain names (That's what the \var{mailhost} is for). To specify a
703non-standard SMTP port, use the (host, port) tuple format for the
704\var{mailhost} argument. If you use a string, the standard SMTP port
705is used.
706\end{classdesc}
707
708\begin{methoddesc}{emit}{record}
709Formats the record and sends it to the specified addressees.
710\end{methoddesc}
711
712\begin{methoddesc}{getSubject}{record}
713If you want to specify a subject line which is record-dependent,
714override this method.
715\end{methoddesc}
716
717\subsubsection{MemoryHandler}
718
719The \class{MemoryHandler} supports buffering of logging records in memory,
720periodically flushing them to a \dfn{target} handler. Flushing occurs
721whenever the buffer is full, or when an event of a certain severity or
722greater is seen.
723
724\class{MemoryHandler} is a subclass of the more general
725\class{BufferingHandler}, which is an abstract class. This buffers logging
726records in memory. Whenever each record is added to the buffer, a
727check is made by calling \method{shouldFlush()} to see if the buffer
728should be flushed. If it should, then \method{flush()} is expected to
729do the needful.
730
731\begin{classdesc}{BufferingHandler}{capacity}
732Initializes the handler with a buffer of the specified capacity.
733\end{classdesc}
734
735\begin{methoddesc}{emit}{record}
736Appends the record to the buffer. If \method{shouldFlush()} returns true,
737calls \method{flush()} to process the buffer.
738\end{methoddesc}
739
740\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000741You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000742just zaps the buffer to empty.
743\end{methoddesc}
744
745\begin{methoddesc}{shouldFlush}{record}
746Returns true if the buffer is up to capacity. This method can be
747overridden to implement custom flushing strategies.
748\end{methoddesc}
749
750\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000751\optional{, target}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000752Returns a new instance of the \class{MemoryHandler} class. The
753instance is initialized with a buffer size of \var{capacity}. If
754\var{flushLevel} is not specified, \constant{ERROR} is used. If no
755\var{target} is specified, the target will need to be set using
756\method{setTarget()} before this handler does anything useful.
757\end{classdesc}
758
759\begin{methoddesc}{close}{}
760Calls \method{flush()}, sets the target to \constant{None} and
761clears the buffer.
762\end{methoddesc}
763
764\begin{methoddesc}{flush}{}
765For a \class{MemoryHandler}, flushing means just sending the buffered
766records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000767different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000768\end{methoddesc}
769
770\begin{methoddesc}{setTarget}{target}
771Sets the target handler for this handler.
772\end{methoddesc}
773
774\begin{methoddesc}{shouldFlush}{record}
775Checks for buffer full or a record at the \var{flushLevel} or higher.
776\end{methoddesc}
777
778\subsubsection{HTTPHandler}
779
780The \class{HTTPHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000781Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000782
783\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
784Returns a new instance of the \class{HTTPHandler} class. The
785instance is initialized with a host address, url and HTTP method.
Fred Drake68e6d572003-01-28 22:02:35 +0000786If no \var{method} is specified, \samp{GET} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000787\end{classdesc}
788
789\begin{methoddesc}{emit}{record}
790Sends the record to the Web server as an URL-encoded dictionary.
791\end{methoddesc}
792
793\subsection{Formatter Objects}
794
795\class{Formatter}s have the following attributes and methods. They are
796responsible for converting a \class{LogRecord} to (usually) a string
797which can be interpreted by either a human or an external system. The
798base
799\class{Formatter} allows a formatting string to be specified. If none is
800supplied, the default value of "\%s(message)\\n" is used.
801
802A Formatter can be initialized with a format string which makes use of
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000803knowledge of the \class{LogRecord} attributes - such as the default value
804mentioned above making use of the fact that the user's message and
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000805arguments are pre- formatted into a LogRecord's \var{message}
806attribute. Currently, the useful attributes in a LogRecord are
807described by:
808
809\%(name)s Name of the logger (logging channel)
810\%(levelno)s Numeric logging level for the message (DEBUG, INFO,
811 WARNING, ERROR, CRITICAL)
812\%(levelname)s Text logging level for the message ("DEBUG", "INFO",
813 "WARNING", "ERROR", "CRITICAL")
814\%(pathname)s Full pathname of the source file where the logging
815 call was issued (if available)
816\%(filename)s Filename portion of pathname
817\%(module)s Module (name portion of filename)
818\%(lineno)d Source line number where the logging call was issued
819 (if available)
820\%(created)f Time when the LogRecord was created (time.time()
821 return value)
822\%(asctime)s Textual time when the LogRecord was created
823\%(msecs)d Millisecond portion of the creation time
824\%(relativeCreated)d Time in milliseconds when the LogRecord was created,
825 relative to the time the logging module was loaded
826 (typically at application startup time)
827\%(thread)d Thread ID (if available)
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000828\%(process)d Process ID (if available)
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000829\%(message)s The result of msg \% args, computed just as the
830 record is emitted
831
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000832\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
833Returns a new instance of the \class{Formatter} class. The
834instance is initialized with a format string for the message as a whole,
835as well as a format string for the date/time portion of a message. If
836no \var{fmt} is specified, "\%(message)s" is used. If no \var{datefmt}
837is specified, the ISO8601 date format is used.
838\end{classdesc}
839
840\begin{methoddesc}{format}{record}
841The record's attribute dictionary is used as the operand to a
842string formatting operation. Returns the resulting string.
843Before formatting the dictionary, a couple of preparatory steps
844are carried out. The \var{message} attribute of the record is computed
845using \var{msg} \% \var{args}. If the formatting string contains
846\constant{"(asctime)"}, \method{formatTime()} is called to format the
847event time. If there is exception information, it is formatted using
848\method{formatException()} and appended to the message.
849\end{methoddesc}
850
851\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
852This method should be called from \method{format()} by a formatter which
853wants to make use of a formatted time. This method can be overridden
854in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000855basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +0000856it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000857record. Otherwise, the ISO8601 format is used. The resulting
858string is returned.
859\end{methoddesc}
860
861\begin{methoddesc}{formatException}{exc_info}
862Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +0000863as returned by \function{sys.exc_info()}) as a string. This default
864implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000865The resulting string is returned.
866\end{methoddesc}
867
868\subsection{Filter Objects}
869
870\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
871more sophisticated filtering than is provided by levels. The base filter
872class only allows events which are below a certain point in the logger
873hierarchy. For example, a filter initialized with "A.B" will allow events
874logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
875"B.A.B" etc. If initialized with the empty string, all events are passed.
876
877\begin{classdesc}{Filter}{\optional{name}}
878Returns an instance of the \class{Filter} class. If \var{name} is specified,
879it names a logger which, together with its children, will have its events
880allowed through the filter. If no name is specified, allows every event.
881\end{classdesc}
882
883\begin{methoddesc}{filter}{record}
884Is the specified record to be logged? Returns zero for no, nonzero for
885yes. If deemed appropriate, the record may be modified in-place by this
886method.
887\end{methoddesc}
888
889\subsection{LogRecord Objects}
890
891LogRecord instances are created every time something is logged. They
892contain all the information pertinent to the event being logged. The
893main information passed in is in msg and args, which are combined
894using msg \% args to create the message field of the record. The record
895also includes information such as when the record was created, the
896source line where the logging call was made, and any exception
897information to be logged.
898
899LogRecord has no methods; it's just a repository for information about the
900logging event. The only reason it's a class rather than a dictionary is to
901facilitate extension.
902
903\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000904 exc_info}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000905Returns an instance of \class{LogRecord} initialized with interesting
906information. The \var{name} is the logger name; \var{lvl} is the
907numeric level; \var{pathname} is the absolute pathname of the source
908file in which the logging call was made; \var{lineno} is the line
909number in that file where the logging call is found; \var{msg} is the
910user-supplied message (a format string); \var{args} is the tuple
911which, together with \var{msg}, makes up the user message; and
912\var{exc_info} is the exception tuple obtained by calling
913\function{sys.exc_info() }(or \constant{None}, if no exception information
914is available).
915\end{classdesc}
916
917\subsection{Thread Safety}
918
919The logging module is intended to be thread-safe without any special work
920needing to be done by its clients. It achieves this though using threading
921locks; there is one lock to serialize access to the module's shared data,
922and each handler also creates a lock to serialize access to its underlying
923I/O.
924
925\subsection{Configuration}
926
927
928\subsubsection{Configuration functions}
929
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000930The following functions allow the logging module to be configured. Before
931they can be used, you must import \module{logging.config}. Their use is optional -
932you can configure the logging module entirely by making calls to the main
933API (defined in \module{logging} itself) and defining handlers which are declared
934either in \module{logging} or \module{logging.handlers}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000935
936\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
937Reads the logging configuration from a ConfigParser-format file named
938\var{fname}. This function can be called several times from an application,
939allowing an end user the ability to select from various pre-canned
940configurations (if the developer provides a mechanism to present the
941choices and load the chosen configuration). Defaults to be passed to
942ConfigParser can be specified in the \var{defaults} argument.
943\end{funcdesc}
944
945\begin{funcdesc}{listen}{\optional{port}}
946Starts up a socket server on the specified port, and listens for new
947configurations. If no port is specified, the module's default
948\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
949will be sent as a file suitable for processing by \function{fileConfig()}.
950Returns a \class{Thread} instance on which you can call \method{start()}
951to start the server, and which you can \method{join()} when appropriate.
952To stop the server, call \function{stopListening()}.
953\end{funcdesc}
954
955\begin{funcdesc}{stopListening}{}
956Stops the listening server which was created with a call to
957\function{listen()}. This is typically called before calling \method{join()}
958on the return value from \function{listen()}.
959\end{funcdesc}
960
961\subsubsection{Configuration file format}
962
963The configuration file format understood by \function{fileConfig} is
964based on ConfigParser functionality. The file must contain sections
965called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
966which identify by name the entities of each type which are defined in
967the file. For each such entity, there is a separate section which
968identified how that entity is configured. Thus, for a logger named
969\code{log01} in the \code{[loggers]} section, the relevant
970configuration details are held in a section
971\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
972the \code{[handlers]} section will have its configuration held in a
973section called \code{[handler_hand01]}, while a formatter called
974\code{form01} in the \code{[formatters]} section will have its
975configuration specified in a section called
976\code{[formatter_form01]}. The root logger configuration must be
977specified in a section called \code{[logger_root]}.
978
979Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +0000980
981\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000982[loggers]
983keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +0000984
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000985[handlers]
986keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
987
988[formatters]
989keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +0000990\end{verbatim}
991
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000992The root logger must specify a level and a list of handlers. An
993example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +0000994
995\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000996[logger_root]
997level=NOTSET
998handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +0000999\end{verbatim}
1000
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001001The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1002ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1003\code{NOTSET} means that all messages will be logged. Level values are
1004\function{eval()}uated in the context of the \code{logging} package's
1005namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +00001006
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001007The \code{handlers} entry is a comma-separated list of handler names,
1008which must appear in the \code{[handlers]} section. These names must
1009appear in the \code{[handlers]} section and have corresponding
1010sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +00001011
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001012For loggers other than the root logger, some additional information is
1013required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +00001014
1015\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001016[logger_parser]
1017level=DEBUG
1018handlers=hand01
1019propagate=1
1020qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001021\end{verbatim}
1022
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001023The \code{level} and \code{handlers} entries are interpreted as for
1024the root logger, except that if a non-root logger's level is specified
1025as \code{NOTSET}, the system consults loggers higher up the hierarchy
1026to determine the effective level of the logger. The \code{propagate}
1027entry is set to 1 to indicate that messages must propagate to handlers
1028higher up the logger hierarchy from this logger, or 0 to indicate that
1029messages are \strong{not} propagated to handlers up the hierarchy. The
1030\code{qualname} entry is the hierarchical channel name of the logger,
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001031for example, the name used by the application to get the logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001032
1033Sections which specify handler configuration are exemplified by the
1034following.
1035
Skip Montanaro649698f2002-11-14 03:57:19 +00001036\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001037[handler_hand01]
1038class=StreamHandler
1039level=NOTSET
1040formatter=form01
1041args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001042\end{verbatim}
1043
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001044The \code{class} entry indicates the handler's class (as determined by
1045\function{eval()} in the \code{logging} package's namespace). The
1046\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1047to mean "log everything".
1048
1049The \code{formatter} entry indicates the key name of the formatter for
1050this handler. If blank, a default formatter
1051(\code{logging._defaultFormatter}) is used. If a name is specified, it
1052must appear in the \code{[formatters]} section and have a
1053corresponding section in the configuration file.
1054
1055The \code{args} entry, when \function{eval()}uated in the context of
1056the \code{logging} package's namespace, is the list of arguments to
1057the constructor for the handler class. Refer to the constructors for
1058the relevant handlers, or to the examples below, to see how typical
1059entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001060
1061\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001062[handler_hand02]
1063class=FileHandler
1064level=DEBUG
1065formatter=form02
1066args=('python.log', 'w')
1067
1068[handler_hand03]
1069class=handlers.SocketHandler
1070level=INFO
1071formatter=form03
1072args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1073
1074[handler_hand04]
1075class=handlers.DatagramHandler
1076level=WARN
1077formatter=form04
1078args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1079
1080[handler_hand05]
1081class=handlers.SysLogHandler
1082level=ERROR
1083formatter=form05
1084args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1085
1086[handler_hand06]
1087class=NTEventLogHandler
1088level=CRITICAL
1089formatter=form06
1090args=('Python Application', '', 'Application')
1091
1092[handler_hand07]
1093class=SMTPHandler
1094level=WARN
1095formatter=form07
1096args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1097
1098[handler_hand08]
1099class=MemoryHandler
1100level=NOTSET
1101formatter=form08
1102target=
1103args=(10, ERROR)
1104
1105[handler_hand09]
1106class=HTTPHandler
1107level=NOTSET
1108formatter=form09
1109args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001110\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001111
1112Sections which specify formatter configuration are typified by the following.
1113
1114\begin{verbatim}
1115[formatter_form01]
1116format=F1 %(asctime)s %(levelname)s %(message)s
1117datefmt=
1118\end{verbatim}
1119
1120The \code{format} entry is the overall format string, and the
1121\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1122string. If empty, the package substitutes ISO8601 format date/times, which
1123is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1124The ISO8601 format also specifies milliseconds, which are appended to the
1125result of using the above format string, with a comma separator. An example
1126time in ISO8601 format is \code{2003-01-23 00:29:50,411}.