blob: dd65f3b6c8b1c30474d68dcae6a8de2da1e39266 [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
55that message (e.g. end users, support desk staff, system administrators,
56developers). 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
207\begin{funcdesc}{basicConfig}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000208Does basic configuration for the logging system by creating a
209\class{StreamHandler} with a default \class{Formatter} and adding it to
210the root logger. The functions \function{debug()}, \function{info()},
211\function{warning()}, \function{error()} and \function{critical()} will call
212\function{basicConfig()} automatically if no handlers are defined for the
213root logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000214\end{funcdesc}
215
Skip Montanaro649698f2002-11-14 03:57:19 +0000216\begin{funcdesc}{shutdown}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000217Informs the logging system to perform an orderly shutdown by flushing and
218closing all handlers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000219\end{funcdesc}
220
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000221\begin{funcdesc}{setLoggerClass}{klass}
222Tells the logging system to use the class \var{klass} when instantiating a
223logger. The class should define \method{__init__()} such that only a name
224argument is required, and the \method{__init__()} should call
225\method{Logger.__init__()}. This function is typically called before any
226loggers are instantiated by applications which need to use custom logger
227behavior.
228\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000229
Fred Drake68e6d572003-01-28 22:02:35 +0000230
231\begin{seealso}
232 \seepep{282}{A Logging System}
233 {The proposal which described this feature for inclusion in
234 the Python standard library.}
235\end{seealso}
236
237
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000238\subsection{Logger Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000239
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000240Loggers have the following attributes and methods. Note that Loggers are
241never instantiated directly, but always through the module-level function
242\function{logging.getLogger(name)}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000243
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000244\begin{datadesc}{propagate}
245If this evaluates to false, logging messages are not passed by this
246logger or by child loggers to higher level (ancestor) loggers. The
247constructor sets this attribute to 1.
Skip Montanaro649698f2002-11-14 03:57:19 +0000248\end{datadesc}
249
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000250\begin{methoddesc}{setLevel}{lvl}
251Sets the threshold for this logger to \var{lvl}. Logging messages
252which are less severe than \var{lvl} will be ignored. When a logger is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000253created, the level is set to \constant{NOTSET} (which causes all messages
254to be processed in the root logger, or delegation to the parent in non-root
255loggers).
Skip Montanaro649698f2002-11-14 03:57:19 +0000256\end{methoddesc}
257
258\begin{methoddesc}{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000259Indicates if a message of severity \var{lvl} would be processed by
260this logger. This method checks first the module-level level set by
261\function{logging.disable(lvl)} and then the logger's effective level as
262determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000263\end{methoddesc}
264
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000265\begin{methoddesc}{getEffectiveLevel}{}
266Indicates the effective level for this logger. If a value other than
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000267\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000268Otherwise, the hierarchy is traversed towards the root until a value
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000269other than \constant{NOTSET} is found,and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000270\end{methoddesc}
271
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000272\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
273Logs a message with level \constant{DEBUG} on this logger.
274The \var{msg} is the message format string, and the \var{args} are the
275arguments which are merged into \var{msg}. The only keyword argument in
276\var{kwargs} which is inspected is \var{exc_info} which, if it does not
277evaluate as false, causes exception information (via a call to
Fred Drakec23e0192003-01-28 22:09:16 +0000278\function{sys.exc_info()}) to be added to the logging message.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000279\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000280
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000281\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
282Logs a message with level \constant{INFO} on this logger.
283The arguments are interpreted as for \method{debug()}.
284\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000285
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000286\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
287Logs a message with level \constant{WARNING} on this logger.
288The arguments are interpreted as for \method{debug()}.
289\end{methoddesc}
290
291\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
292Logs a message with level \constant{ERROR} on this logger.
293The arguments are interpreted as for \method{debug()}.
294\end{methoddesc}
295
296\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
297Logs a message with level \constant{CRITICAL} on this logger.
298The arguments are interpreted as for \method{debug()}.
299\end{methoddesc}
300
301\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
302Logs a message with level \var{lvl} on this logger.
303The other arguments are interpreted as for \method{debug()}.
304\end{methoddesc}
305
306\begin{methoddesc}{exception}{msg\optional{, *args}}
307Logs a message with level \constant{ERROR} on this logger.
308The arguments are interpreted as for \method{debug()}. Exception info
309is added to the logging message. This method should only be called
310from an exception handler.
311\end{methoddesc}
312
313\begin{methoddesc}{addFilter}{filt}
314Adds the specified filter \var{filt} to this logger.
315\end{methoddesc}
316
317\begin{methoddesc}{removeFilter}{filt}
318Removes the specified filter \var{filt} from this logger.
319\end{methoddesc}
320
321\begin{methoddesc}{filter}{record}
322Applies this logger's filters to the record and returns a true value if
323the record is to be processed.
324\end{methoddesc}
325
326\begin{methoddesc}{addHandler}{hdlr}
327Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000328\end{methoddesc}
329
330\begin{methoddesc}{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000331Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000332\end{methoddesc}
333
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000334\begin{methoddesc}{findCaller}{}
335Finds the caller's source filename and line number. Returns the filename
336and line number as a 2-element tuple.
Skip Montanaro649698f2002-11-14 03:57:19 +0000337\end{methoddesc}
338
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000339\begin{methoddesc}{handle}{record}
340Handles a record by passing it to all handlers associated with this logger
341and its ancestors (until a false value of \var{propagate} is found).
342This method is used for unpickled records received from a socket, as well
343as those created locally. Logger-level filtering is applied using
344\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000345\end{methoddesc}
346
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000347\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info}
348This is a factory method which can be overridden in subclasses to create
349specialized \class{LogRecord} instances.
Skip Montanaro649698f2002-11-14 03:57:19 +0000350\end{methoddesc}
351
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000352\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000353
Fred Drake68e6d572003-01-28 22:02:35 +0000354Handlers have the following attributes and methods. Note that
355\class{Handler} is never instantiated directly; this class acts as a
356base for more useful subclasses. However, the \method{__init__()}
357method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000358
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000359\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000360Initializes the \class{Handler} instance by setting its level, setting
361the list of filters to the empty list and creating a lock (using
362\method{getLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000363\end{methoddesc}
364
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000365\begin{methoddesc}{createLock}{}
366Initializes a thread lock which can be used to serialize access to
367underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000368\end{methoddesc}
369
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000370\begin{methoddesc}{acquire}{}
371Acquires the thread lock created with \method{createLock()}.
372\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000373
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000374\begin{methoddesc}{release}{}
375Releases the thread lock acquired with \method{acquire()}.
376\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000377
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000378\begin{methoddesc}{setLevel}{lvl}
379Sets the threshold for this handler to \var{lvl}. Logging messages which are
380less severe than \var{lvl} will be ignored. When a handler is created, the
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000381level is set to \constant{NOTSET} (which causes all messages to be processed).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000382\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000383
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000384\begin{methoddesc}{setFormatter}{form}
385Sets the \class{Formatter} for this handler to \var{form}.
386\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000387
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000388\begin{methoddesc}{addFilter}{filt}
389Adds the specified filter \var{filt} to this handler.
390\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000391
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000392\begin{methoddesc}{removeFilter}{filt}
393Removes the specified filter \var{filt} from this handler.
394\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000395
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000396\begin{methoddesc}{filter}{record}
397Applies this handler's filters to the record and returns a true value if
398the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000399\end{methoddesc}
400
401\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000402Ensure all logging output has been flushed. This version does
403nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000404\end{methoddesc}
405
Skip Montanaro649698f2002-11-14 03:57:19 +0000406\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000407Tidy up any resources used by the handler. This version does
408nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000409\end{methoddesc}
410
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000411\begin{methoddesc}{handle}{record}
412Conditionally emits the specified logging record, depending on
413filters which may have been added to the handler. Wraps the actual
414emission of the record with acquisition/release of the I/O thread
415lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000416\end{methoddesc}
417
418\begin{methoddesc}{handleError}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000419This method should be called from handlers when an exception is
420encountered during an emit() call. By default it does nothing,
421which means that exceptions get silently ignored. This is what is
422mostly wanted for a logging system - most users will not care
423about errors in the logging system, they are more interested in
424application errors. You could, however, replace this with a custom
425handler if you wish.
Skip Montanaro649698f2002-11-14 03:57:19 +0000426\end{methoddesc}
427
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000428\begin{methoddesc}{format}{record}
429Do formatting for a record - if a formatter is set, use it.
430Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000431\end{methoddesc}
432
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000433\begin{methoddesc}{emit}{record}
434Do whatever it takes to actually log the specified logging record.
435This version is intended to be implemented by subclasses and so
436raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000437\end{methoddesc}
438
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000439\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000440
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000441The \class{StreamHandler} class sends logging output to streams such as
442\var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more
443precisely, any object which supports \method{write()} and \method{flush()}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000444methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000445
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000446\begin{classdesc}{StreamHandler}{\optional{strm}}
447Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
448specified, the instance will use it for logging output; otherwise,
449\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000450\end{classdesc}
451
452\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000453If a formatter is specified, it is used to format the record.
454The record is then written to the stream with a trailing newline.
455If exception information is present, it is formatted using
456\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000457\end{methoddesc}
458
459\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000460Flushes the stream by calling its \method{flush()} method. Note that
461the \method{close()} method is inherited from \class{Handler} and
462so does nothing, so an explicit \method{flush()} call may be needed
463at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000464\end{methoddesc}
465
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000466\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000467
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000468The \class{FileHandler} class sends logging output to a disk file.
Fred Drake68e6d572003-01-28 22:02:35 +0000469It inherits the output functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000470
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000471\begin{classdesc}{FileHandler}{filename\optional{, mode}}
472Returns a new instance of the \class{FileHandler} class. The specified
473file is opened and used as the stream for logging. If \var{mode} is
474not specified, \constant{"a"} is used. By default, the file grows
475indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000476\end{classdesc}
477
478\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000479Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000480\end{methoddesc}
481
482\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000483Outputs the record to the file.
484\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000485
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000486\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000487
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000488The \class{RotatingFileHandler} class supports rotation of disk log files.
489
490\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode, maxBytes,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000491 backupCount}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000492Returns a new instance of the \class{RotatingFileHandler} class. The
493specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +0000494\var{mode} is not specified, \code{'a'} is used. By default, the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000495file grows indefinitely. You can use the \var{maxBytes} and
496\var{backupCount} values to allow the file to \dfn{rollover} at a
497predetermined size. When the size is about to be exceeded, the file is
498closed and a new file opened for output, transparently to the
499caller. Rollover occurs whenever the current log file is nearly
500\var{maxBytes} in length. If \var{backupCount} is >= 1, the system
501will successively create new files with the same pathname as the base
502file, but with extensions ".1", ".2" etc. appended to it. For example,
503with a backupCount of 5 and a base file name of "app.log", you would
504get "app.log", "app.log.1", "app.log.2", ... through to
505"app.log.5". When the last file reaches its size limit, the logging
506reverts to "app.log" which is truncated to zero length. If
507\var{maxBytes} is zero, rollover never occurs.
508\end{classdesc}
509
510\begin{methoddesc}{doRollover}{}
511Does a rollover, as described above.
512\end{methoddesc}
513
514\begin{methoddesc}{emit}{record}
515Outputs the record to the file, catering for rollover as described
516in \method{setRollover()}.
517\end{methoddesc}
518
519\subsubsection{SocketHandler}
520
521The \class{SocketHandler} class sends logging output to a network
522socket. The base class uses a TCP socket.
523
524\begin{classdesc}{SocketHandler}{host, port}
525Returns a new instance of the \class{SocketHandler} class intended to
526communicate with a remote machine whose address is given by \var{host}
527and \var{port}.
528\end{classdesc}
529
530\begin{methoddesc}{close}{}
531Closes the socket.
532\end{methoddesc}
533
534\begin{methoddesc}{handleError}{}
535\end{methoddesc}
536
537\begin{methoddesc}{emit}{}
538Pickles the record and writes it to the socket in binary format.
539If there is an error with the socket, silently drops the packet.
540If the connection was previously lost, re-establishes the connection.
541\end{methoddesc}
542
543\begin{methoddesc}{handleError}{}
544Handles an error which has occurred during \method{emit()}. The
545most likely cause is a lost connection. Closes the socket so that
546we can retry on the next event.
547\end{methoddesc}
548
549\begin{methoddesc}{makeSocket}{}
550This is a factory method which allows subclasses to define the precise
551type of socket they want. The default implementation creates a TCP
552socket (\constant{socket.SOCK_STREAM}).
553\end{methoddesc}
554
555\begin{methoddesc}{makePickle}{record}
556Pickles the record in binary format with a length prefix, and returns
557it ready for transmission across the socket.
558\end{methoddesc}
559
560\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000561Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000562for partial sends which can happen when the network is busy.
563\end{methoddesc}
564
565\subsubsection{DatagramHandler}
566
567The \class{DatagramHandler} class inherits from \class{SocketHandler}
568to support sending logging messages over UDP sockets.
569
570\begin{classdesc}{DatagramHandler}{host, port}
571Returns a new instance of the \class{DatagramHandler} class intended to
572communicate with a remote machine whose address is given by \var{host}
573and \var{port}.
574\end{classdesc}
575
576\begin{methoddesc}{emit}{}
577Pickles the record and writes it to the socket in binary format.
578If there is an error with the socket, silently drops the packet.
579\end{methoddesc}
580
581\begin{methoddesc}{makeSocket}{}
582The factory method of \class{SocketHandler} is here overridden to create
583a UDP socket (\constant{socket.SOCK_DGRAM}).
584\end{methoddesc}
585
586\begin{methoddesc}{send}{s}
587Send a pickled string to a socket. This function allows for
588partial sends which can happen when the network is busy.
589\end{methoddesc}
590
591\subsubsection{SysLogHandler}
592
593The \class{SysLogHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000594remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000595
596\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
597Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +0000598communicate with a remote \UNIX{} machine whose address is given by
599\var{address} in the form of a \code{(\var{host}, \var{port})}
600tuple. If \var{address} is not specified, \code{('localhost', 514)} is
601used. The address is used to open a UDP socket. If \var{facility} is
602not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000603\end{classdesc}
604
605\begin{methoddesc}{close}{}
606Closes the socket to the remote host.
607\end{methoddesc}
608
609\begin{methoddesc}{emit}{record}
610The record is formatted, and then sent to the syslog server. If
611exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +0000612\end{methoddesc}
613
614\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000615Encodes the facility and priority into an integer. You can pass in strings
616or integers - if strings are passed, internal mapping dictionaries are used
617to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000618\end{methoddesc}
619
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000620\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000621
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000622The \class{NTEventLogHandler} class supports sending logging messages
623to a local Windows NT, Windows 2000 or Windows XP event log. Before
624you can use it, you need Mark Hammond's Win32 extensions for Python
625installed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000626
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000627\begin{classdesc}{NTEventLogHandler}{appname
628 \optional{, dllname\optional{, logtype}}}
629Returns a new instance of the \class{NTEventLogHandler} class. The
630\var{appname} is used to define the application name as it appears in the
631event log. An appropriate registry entry is created using this name.
632The \var{dllname} should give the fully qualified pathname of a .dll or .exe
633which contains message definitions to hold in the log (if not specified,
634\constant{"win32service.pyd"} is used - this is installed with the Win32
635extensions and contains some basic placeholder message definitions.
636Note that use of these placeholders will make your event logs big, as the
637entire message source is held in the log. If you want slimmer logs, you have
638to pass in the name of your own .dll or .exe which contains the message
639definitions you want to use in the event log). The \var{logtype} is one of
640\constant{"Application"}, \constant{"System"} or \constant{"Security"}, and
641defaults to \constant{"Application"}.
642\end{classdesc}
643
644\begin{methoddesc}{close}{}
645At this point, you can remove the application name from the registry as a
646source of event log entries. However, if you do this, you will not be able
647to see the events as you intended in the Event Log Viewer - it needs to be
648able to access the registry to get the .dll name. The current version does
649not do this (in fact it doesn't do anything).
650\end{methoddesc}
651
652\begin{methoddesc}{emit}{record}
653Determines the message ID, event category and event type, and then logs the
654message in the NT event log.
655\end{methoddesc}
656
657\begin{methoddesc}{getEventCategory}{record}
658Returns the event category for the record. Override this if you
659want to specify your own categories. This version returns 0.
660\end{methoddesc}
661
662\begin{methoddesc}{getEventType}{record}
663Returns the event type for the record. Override this if you want
664to specify your own types. This version does a mapping using the
665handler's typemap attribute, which is set up in \method{__init__()}
666to a dictionary which contains mappings for \constant{DEBUG},
667\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
668\constant{CRITICAL}. If you are using your own levels, you will either need
669to override this method or place a suitable dictionary in the
670handler's \var{typemap} attribute.
671\end{methoddesc}
672
673\begin{methoddesc}{getMessageID}{record}
674Returns the message ID for the record. If you are using your
675own messages, you could do this by having the \var{msg} passed to the
676logger being an ID rather than a format string. Then, in here,
677you could use a dictionary lookup to get the message ID. This
678version returns 1, which is the base message ID in
679\constant{win32service.pyd}.
680\end{methoddesc}
681
682\subsubsection{SMTPHandler}
683
684The \class{SMTPHandler} class supports sending logging messages to an email
685address via SMTP.
686
687\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
688Returns a new instance of the \class{SMTPHandler} class. The
689instance is initialized with the from and to addresses and subject
690line of the email. The \var{toaddrs} should be a list of strings without
691domain names (That's what the \var{mailhost} is for). To specify a
692non-standard SMTP port, use the (host, port) tuple format for the
693\var{mailhost} argument. If you use a string, the standard SMTP port
694is used.
695\end{classdesc}
696
697\begin{methoddesc}{emit}{record}
698Formats the record and sends it to the specified addressees.
699\end{methoddesc}
700
701\begin{methoddesc}{getSubject}{record}
702If you want to specify a subject line which is record-dependent,
703override this method.
704\end{methoddesc}
705
706\subsubsection{MemoryHandler}
707
708The \class{MemoryHandler} supports buffering of logging records in memory,
709periodically flushing them to a \dfn{target} handler. Flushing occurs
710whenever the buffer is full, or when an event of a certain severity or
711greater is seen.
712
713\class{MemoryHandler} is a subclass of the more general
714\class{BufferingHandler}, which is an abstract class. This buffers logging
715records in memory. Whenever each record is added to the buffer, a
716check is made by calling \method{shouldFlush()} to see if the buffer
717should be flushed. If it should, then \method{flush()} is expected to
718do the needful.
719
720\begin{classdesc}{BufferingHandler}{capacity}
721Initializes the handler with a buffer of the specified capacity.
722\end{classdesc}
723
724\begin{methoddesc}{emit}{record}
725Appends the record to the buffer. If \method{shouldFlush()} returns true,
726calls \method{flush()} to process the buffer.
727\end{methoddesc}
728
729\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000730You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000731just zaps the buffer to empty.
732\end{methoddesc}
733
734\begin{methoddesc}{shouldFlush}{record}
735Returns true if the buffer is up to capacity. This method can be
736overridden to implement custom flushing strategies.
737\end{methoddesc}
738
739\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000740\optional{, target}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000741Returns a new instance of the \class{MemoryHandler} class. The
742instance is initialized with a buffer size of \var{capacity}. If
743\var{flushLevel} is not specified, \constant{ERROR} is used. If no
744\var{target} is specified, the target will need to be set using
745\method{setTarget()} before this handler does anything useful.
746\end{classdesc}
747
748\begin{methoddesc}{close}{}
749Calls \method{flush()}, sets the target to \constant{None} and
750clears the buffer.
751\end{methoddesc}
752
753\begin{methoddesc}{flush}{}
754For a \class{MemoryHandler}, flushing means just sending the buffered
755records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000756different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000757\end{methoddesc}
758
759\begin{methoddesc}{setTarget}{target}
760Sets the target handler for this handler.
761\end{methoddesc}
762
763\begin{methoddesc}{shouldFlush}{record}
764Checks for buffer full or a record at the \var{flushLevel} or higher.
765\end{methoddesc}
766
767\subsubsection{HTTPHandler}
768
769The \class{HTTPHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000770Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000771
772\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
773Returns a new instance of the \class{HTTPHandler} class. The
774instance is initialized with a host address, url and HTTP method.
Fred Drake68e6d572003-01-28 22:02:35 +0000775If no \var{method} is specified, \samp{GET} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000776\end{classdesc}
777
778\begin{methoddesc}{emit}{record}
779Sends the record to the Web server as an URL-encoded dictionary.
780\end{methoddesc}
781
782\subsection{Formatter Objects}
783
784\class{Formatter}s have the following attributes and methods. They are
785responsible for converting a \class{LogRecord} to (usually) a string
786which can be interpreted by either a human or an external system. The
787base
788\class{Formatter} allows a formatting string to be specified. If none is
789supplied, the default value of "\%s(message)\\n" is used.
790
791A Formatter can be initialized with a format string which makes use of
792knowledge of the \class{LogRecord} attributes - e.g. the default value
793mentioned above makes use of the fact that the user's message and
794arguments are pre- formatted into a LogRecord's \var{message}
795attribute. Currently, the useful attributes in a LogRecord are
796described by:
797
798\%(name)s Name of the logger (logging channel)
799\%(levelno)s Numeric logging level for the message (DEBUG, INFO,
800 WARNING, ERROR, CRITICAL)
801\%(levelname)s Text logging level for the message ("DEBUG", "INFO",
802 "WARNING", "ERROR", "CRITICAL")
803\%(pathname)s Full pathname of the source file where the logging
804 call was issued (if available)
805\%(filename)s Filename portion of pathname
806\%(module)s Module (name portion of filename)
807\%(lineno)d Source line number where the logging call was issued
808 (if available)
809\%(created)f Time when the LogRecord was created (time.time()
810 return value)
811\%(asctime)s Textual time when the LogRecord was created
812\%(msecs)d Millisecond portion of the creation time
813\%(relativeCreated)d Time in milliseconds when the LogRecord was created,
814 relative to the time the logging module was loaded
815 (typically at application startup time)
816\%(thread)d Thread ID (if available)
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000817\%(process)d Process ID (if available)
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000818\%(message)s The result of msg \% args, computed just as the
819 record is emitted
820
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000821\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
822Returns a new instance of the \class{Formatter} class. The
823instance is initialized with a format string for the message as a whole,
824as well as a format string for the date/time portion of a message. If
825no \var{fmt} is specified, "\%(message)s" is used. If no \var{datefmt}
826is specified, the ISO8601 date format is used.
827\end{classdesc}
828
829\begin{methoddesc}{format}{record}
830The record's attribute dictionary is used as the operand to a
831string formatting operation. Returns the resulting string.
832Before formatting the dictionary, a couple of preparatory steps
833are carried out. The \var{message} attribute of the record is computed
834using \var{msg} \% \var{args}. If the formatting string contains
835\constant{"(asctime)"}, \method{formatTime()} is called to format the
836event time. If there is exception information, it is formatted using
837\method{formatException()} and appended to the message.
838\end{methoddesc}
839
840\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
841This method should be called from \method{format()} by a formatter which
842wants to make use of a formatted time. This method can be overridden
843in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000844basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +0000845it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000846record. Otherwise, the ISO8601 format is used. The resulting
847string is returned.
848\end{methoddesc}
849
850\begin{methoddesc}{formatException}{exc_info}
851Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +0000852as returned by \function{sys.exc_info()}) as a string. This default
853implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000854The resulting string is returned.
855\end{methoddesc}
856
857\subsection{Filter Objects}
858
859\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
860more sophisticated filtering than is provided by levels. The base filter
861class only allows events which are below a certain point in the logger
862hierarchy. For example, a filter initialized with "A.B" will allow events
863logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
864"B.A.B" etc. If initialized with the empty string, all events are passed.
865
866\begin{classdesc}{Filter}{\optional{name}}
867Returns an instance of the \class{Filter} class. If \var{name} is specified,
868it names a logger which, together with its children, will have its events
869allowed through the filter. If no name is specified, allows every event.
870\end{classdesc}
871
872\begin{methoddesc}{filter}{record}
873Is the specified record to be logged? Returns zero for no, nonzero for
874yes. If deemed appropriate, the record may be modified in-place by this
875method.
876\end{methoddesc}
877
878\subsection{LogRecord Objects}
879
880LogRecord instances are created every time something is logged. They
881contain all the information pertinent to the event being logged. The
882main information passed in is in msg and args, which are combined
883using msg \% args to create the message field of the record. The record
884also includes information such as when the record was created, the
885source line where the logging call was made, and any exception
886information to be logged.
887
888LogRecord has no methods; it's just a repository for information about the
889logging event. The only reason it's a class rather than a dictionary is to
890facilitate extension.
891
892\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000893 exc_info}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000894Returns an instance of \class{LogRecord} initialized with interesting
895information. The \var{name} is the logger name; \var{lvl} is the
896numeric level; \var{pathname} is the absolute pathname of the source
897file in which the logging call was made; \var{lineno} is the line
898number in that file where the logging call is found; \var{msg} is the
899user-supplied message (a format string); \var{args} is the tuple
900which, together with \var{msg}, makes up the user message; and
901\var{exc_info} is the exception tuple obtained by calling
902\function{sys.exc_info() }(or \constant{None}, if no exception information
903is available).
904\end{classdesc}
905
906\subsection{Thread Safety}
907
908The logging module is intended to be thread-safe without any special work
909needing to be done by its clients. It achieves this though using threading
910locks; there is one lock to serialize access to the module's shared data,
911and each handler also creates a lock to serialize access to its underlying
912I/O.
913
914\subsection{Configuration}
915
916
917\subsubsection{Configuration functions}
918
919The following functions allow the logging module to be configured.
920
921\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
922Reads the logging configuration from a ConfigParser-format file named
923\var{fname}. This function can be called several times from an application,
924allowing an end user the ability to select from various pre-canned
925configurations (if the developer provides a mechanism to present the
926choices and load the chosen configuration). Defaults to be passed to
927ConfigParser can be specified in the \var{defaults} argument.
928\end{funcdesc}
929
930\begin{funcdesc}{listen}{\optional{port}}
931Starts up a socket server on the specified port, and listens for new
932configurations. If no port is specified, the module's default
933\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
934will be sent as a file suitable for processing by \function{fileConfig()}.
935Returns a \class{Thread} instance on which you can call \method{start()}
936to start the server, and which you can \method{join()} when appropriate.
937To stop the server, call \function{stopListening()}.
938\end{funcdesc}
939
940\begin{funcdesc}{stopListening}{}
941Stops the listening server which was created with a call to
942\function{listen()}. This is typically called before calling \method{join()}
943on the return value from \function{listen()}.
944\end{funcdesc}
945
946\subsubsection{Configuration file format}
947
948The configuration file format understood by \function{fileConfig} is
949based on ConfigParser functionality. The file must contain sections
950called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
951which identify by name the entities of each type which are defined in
952the file. For each such entity, there is a separate section which
953identified how that entity is configured. Thus, for a logger named
954\code{log01} in the \code{[loggers]} section, the relevant
955configuration details are held in a section
956\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
957the \code{[handlers]} section will have its configuration held in a
958section called \code{[handler_hand01]}, while a formatter called
959\code{form01} in the \code{[formatters]} section will have its
960configuration specified in a section called
961\code{[formatter_form01]}. The root logger configuration must be
962specified in a section called \code{[logger_root]}.
963
964Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +0000965
966\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000967[loggers]
968keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +0000969
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000970[handlers]
971keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
972
973[formatters]
974keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +0000975\end{verbatim}
976
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000977The root logger must specify a level and a list of handlers. An
978example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +0000979
980\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000981[logger_root]
982level=NOTSET
983handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +0000984\end{verbatim}
985
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000986The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
987ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
988\code{NOTSET} means that all messages will be logged. Level values are
989\function{eval()}uated in the context of the \code{logging} package's
990namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +0000991
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000992The \code{handlers} entry is a comma-separated list of handler names,
993which must appear in the \code{[handlers]} section. These names must
994appear in the \code{[handlers]} section and have corresponding
995sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000996
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000997For loggers other than the root logger, some additional information is
998required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +0000999
1000\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001001[logger_parser]
1002level=DEBUG
1003handlers=hand01
1004propagate=1
1005qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001006\end{verbatim}
1007
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001008The \code{level} and \code{handlers} entries are interpreted as for
1009the root logger, except that if a non-root logger's level is specified
1010as \code{NOTSET}, the system consults loggers higher up the hierarchy
1011to determine the effective level of the logger. The \code{propagate}
1012entry is set to 1 to indicate that messages must propagate to handlers
1013higher up the logger hierarchy from this logger, or 0 to indicate that
1014messages are \strong{not} propagated to handlers up the hierarchy. The
1015\code{qualname} entry is the hierarchical channel name of the logger,
1016i.e. the name used by the application to get the logger.
1017
1018Sections which specify handler configuration are exemplified by the
1019following.
1020
Skip Montanaro649698f2002-11-14 03:57:19 +00001021\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001022[handler_hand01]
1023class=StreamHandler
1024level=NOTSET
1025formatter=form01
1026args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001027\end{verbatim}
1028
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001029The \code{class} entry indicates the handler's class (as determined by
1030\function{eval()} in the \code{logging} package's namespace). The
1031\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1032to mean "log everything".
1033
1034The \code{formatter} entry indicates the key name of the formatter for
1035this handler. If blank, a default formatter
1036(\code{logging._defaultFormatter}) is used. If a name is specified, it
1037must appear in the \code{[formatters]} section and have a
1038corresponding section in the configuration file.
1039
1040The \code{args} entry, when \function{eval()}uated in the context of
1041the \code{logging} package's namespace, is the list of arguments to
1042the constructor for the handler class. Refer to the constructors for
1043the relevant handlers, or to the examples below, to see how typical
1044entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001045
1046\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001047[handler_hand02]
1048class=FileHandler
1049level=DEBUG
1050formatter=form02
1051args=('python.log', 'w')
1052
1053[handler_hand03]
1054class=handlers.SocketHandler
1055level=INFO
1056formatter=form03
1057args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1058
1059[handler_hand04]
1060class=handlers.DatagramHandler
1061level=WARN
1062formatter=form04
1063args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1064
1065[handler_hand05]
1066class=handlers.SysLogHandler
1067level=ERROR
1068formatter=form05
1069args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1070
1071[handler_hand06]
1072class=NTEventLogHandler
1073level=CRITICAL
1074formatter=form06
1075args=('Python Application', '', 'Application')
1076
1077[handler_hand07]
1078class=SMTPHandler
1079level=WARN
1080formatter=form07
1081args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1082
1083[handler_hand08]
1084class=MemoryHandler
1085level=NOTSET
1086formatter=form08
1087target=
1088args=(10, ERROR)
1089
1090[handler_hand09]
1091class=HTTPHandler
1092level=NOTSET
1093formatter=form09
1094args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001095\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001096
1097Sections which specify formatter configuration are typified by the following.
1098
1099\begin{verbatim}
1100[formatter_form01]
1101format=F1 %(asctime)s %(levelname)s %(message)s
1102datefmt=
1103\end{verbatim}
1104
1105The \code{format} entry is the overall format string, and the
1106\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1107string. If empty, the package substitutes ISO8601 format date/times, which
1108is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1109The ISO8601 format also specifies milliseconds, which are appended to the
1110result of using the above format string, with a comma separator. An example
1111time in ISO8601 format is \code{2003-01-23 00:29:50,411}.