blob: 00c6e8401ba37246090d56a0282f8a4ae20d4b6c [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
253created, the level is set to \constant{ALL} (which causes all messages
254to be processed).
Skip Montanaro649698f2002-11-14 03:57:19 +0000255\end{methoddesc}
256
257\begin{methoddesc}{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000258Indicates if a message of severity \var{lvl} would be processed by
259this logger. This method checks first the module-level level set by
260\function{logging.disable(lvl)} and then the logger's effective level as
261determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000262\end{methoddesc}
263
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000264\begin{methoddesc}{getEffectiveLevel}{}
265Indicates the effective level for this logger. If a value other than
266\constant{ALL} has been set using \method{setLevel()}, it is returned.
267Otherwise, the hierarchy is traversed towards the root until a value
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000268other than \constant{ALL} is found, and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000269\end{methoddesc}
270
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000271\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
272Logs a message with level \constant{DEBUG} on this logger.
273The \var{msg} is the message format string, and the \var{args} are the
274arguments which are merged into \var{msg}. The only keyword argument in
275\var{kwargs} which is inspected is \var{exc_info} which, if it does not
276evaluate as false, causes exception information (via a call to
Fred Drakec23e0192003-01-28 22:09:16 +0000277\function{sys.exc_info()}) to be added to the logging message.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000278\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000279
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000280\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
281Logs a message with level \constant{INFO} on this logger.
282The arguments are interpreted as for \method{debug()}.
283\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000284
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000285\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
286Logs a message with level \constant{WARNING} on this logger.
287The arguments are interpreted as for \method{debug()}.
288\end{methoddesc}
289
290\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
291Logs a message with level \constant{ERROR} on this logger.
292The arguments are interpreted as for \method{debug()}.
293\end{methoddesc}
294
295\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
296Logs a message with level \constant{CRITICAL} on this logger.
297The arguments are interpreted as for \method{debug()}.
298\end{methoddesc}
299
300\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
301Logs a message with level \var{lvl} on this logger.
302The other arguments are interpreted as for \method{debug()}.
303\end{methoddesc}
304
305\begin{methoddesc}{exception}{msg\optional{, *args}}
306Logs a message with level \constant{ERROR} on this logger.
307The arguments are interpreted as for \method{debug()}. Exception info
308is added to the logging message. This method should only be called
309from an exception handler.
310\end{methoddesc}
311
312\begin{methoddesc}{addFilter}{filt}
313Adds the specified filter \var{filt} to this logger.
314\end{methoddesc}
315
316\begin{methoddesc}{removeFilter}{filt}
317Removes the specified filter \var{filt} from this logger.
318\end{methoddesc}
319
320\begin{methoddesc}{filter}{record}
321Applies this logger's filters to the record and returns a true value if
322the record is to be processed.
323\end{methoddesc}
324
325\begin{methoddesc}{addHandler}{hdlr}
326Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000327\end{methoddesc}
328
329\begin{methoddesc}{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000330Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000331\end{methoddesc}
332
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000333\begin{methoddesc}{findCaller}{}
334Finds the caller's source filename and line number. Returns the filename
335and line number as a 2-element tuple.
Skip Montanaro649698f2002-11-14 03:57:19 +0000336\end{methoddesc}
337
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000338\begin{methoddesc}{handle}{record}
339Handles a record by passing it to all handlers associated with this logger
340and its ancestors (until a false value of \var{propagate} is found).
341This method is used for unpickled records received from a socket, as well
342as those created locally. Logger-level filtering is applied using
343\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000344\end{methoddesc}
345
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000346\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info}
347This is a factory method which can be overridden in subclasses to create
348specialized \class{LogRecord} instances.
Skip Montanaro649698f2002-11-14 03:57:19 +0000349\end{methoddesc}
350
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000351\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000352
Fred Drake68e6d572003-01-28 22:02:35 +0000353Handlers have the following attributes and methods. Note that
354\class{Handler} is never instantiated directly; this class acts as a
355base for more useful subclasses. However, the \method{__init__()}
356method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000357
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000358\begin{methoddesc}{__init__}{level=\constant{ALL}}
359Initializes the \class{Handler} instance by setting its level, setting
360the list of filters to the empty list and creating a lock (using
361\method{getLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000362\end{methoddesc}
363
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000364\begin{methoddesc}{createLock}{}
365Initializes a thread lock which can be used to serialize access to
366underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000367\end{methoddesc}
368
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000369\begin{methoddesc}{acquire}{}
370Acquires the thread lock created with \method{createLock()}.
371\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000372
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000373\begin{methoddesc}{release}{}
374Releases the thread lock acquired with \method{acquire()}.
375\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000376
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000377\begin{methoddesc}{setLevel}{lvl}
378Sets the threshold for this handler to \var{lvl}. Logging messages which are
379less severe than \var{lvl} will be ignored. When a handler is created, the
380level is set to \constant{ALL} (which causes all messages to be processed).
381\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000382
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000383\begin{methoddesc}{setFormatter}{form}
384Sets the \class{Formatter} for this handler to \var{form}.
385\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000386
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000387\begin{methoddesc}{addFilter}{filt}
388Adds the specified filter \var{filt} to this handler.
389\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000390
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000391\begin{methoddesc}{removeFilter}{filt}
392Removes the specified filter \var{filt} from this handler.
393\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000394
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000395\begin{methoddesc}{filter}{record}
396Applies this handler's filters to the record and returns a true value if
397the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000398\end{methoddesc}
399
400\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000401Ensure all logging output has been flushed. This version does
402nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000403\end{methoddesc}
404
Skip Montanaro649698f2002-11-14 03:57:19 +0000405\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000406Tidy up any resources used by the handler. This version does
407nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000408\end{methoddesc}
409
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000410\begin{methoddesc}{handle}{record}
411Conditionally emits the specified logging record, depending on
412filters which may have been added to the handler. Wraps the actual
413emission of the record with acquisition/release of the I/O thread
414lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000415\end{methoddesc}
416
417\begin{methoddesc}{handleError}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000418This method should be called from handlers when an exception is
419encountered during an emit() call. By default it does nothing,
420which means that exceptions get silently ignored. This is what is
421mostly wanted for a logging system - most users will not care
422about errors in the logging system, they are more interested in
423application errors. You could, however, replace this with a custom
424handler if you wish.
Skip Montanaro649698f2002-11-14 03:57:19 +0000425\end{methoddesc}
426
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000427\begin{methoddesc}{format}{record}
428Do formatting for a record - if a formatter is set, use it.
429Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000430\end{methoddesc}
431
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000432\begin{methoddesc}{emit}{record}
433Do whatever it takes to actually log the specified logging record.
434This version is intended to be implemented by subclasses and so
435raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000436\end{methoddesc}
437
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000438\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000439
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000440The \class{StreamHandler} class sends logging output to streams such as
441\var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more
442precisely, any object which supports \method{write()} and \method{flush()}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000443methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000444
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000445\begin{classdesc}{StreamHandler}{\optional{strm}}
446Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
447specified, the instance will use it for logging output; otherwise,
448\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000449\end{classdesc}
450
451\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000452If a formatter is specified, it is used to format the record.
453The record is then written to the stream with a trailing newline.
454If exception information is present, it is formatted using
455\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000456\end{methoddesc}
457
458\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000459Flushes the stream by calling its \method{flush()} method. Note that
460the \method{close()} method is inherited from \class{Handler} and
461so does nothing, so an explicit \method{flush()} call may be needed
462at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000463\end{methoddesc}
464
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000465\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000466
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000467The \class{FileHandler} class sends logging output to a disk file.
Fred Drake68e6d572003-01-28 22:02:35 +0000468It inherits the output functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000469
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000470\begin{classdesc}{FileHandler}{filename\optional{, mode}}
471Returns a new instance of the \class{FileHandler} class. The specified
472file is opened and used as the stream for logging. If \var{mode} is
473not specified, \constant{"a"} is used. By default, the file grows
474indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000475\end{classdesc}
476
477\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000478Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000479\end{methoddesc}
480
481\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000482Outputs the record to the file.
483\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000484
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000485\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000486
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000487The \class{RotatingFileHandler} class supports rotation of disk log files.
488
489\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode, maxBytes,
490 backupCount}}
491Returns a new instance of the \class{RotatingFileHandler} class. The
492specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +0000493\var{mode} is not specified, \code{'a'} is used. By default, the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000494file grows indefinitely. You can use the \var{maxBytes} and
495\var{backupCount} values to allow the file to \dfn{rollover} at a
496predetermined size. When the size is about to be exceeded, the file is
497closed and a new file opened for output, transparently to the
498caller. Rollover occurs whenever the current log file is nearly
499\var{maxBytes} in length. If \var{backupCount} is >= 1, the system
500will successively create new files with the same pathname as the base
501file, but with extensions ".1", ".2" etc. appended to it. For example,
502with a backupCount of 5 and a base file name of "app.log", you would
503get "app.log", "app.log.1", "app.log.2", ... through to
504"app.log.5". When the last file reaches its size limit, the logging
505reverts to "app.log" which is truncated to zero length. If
506\var{maxBytes} is zero, rollover never occurs.
507\end{classdesc}
508
509\begin{methoddesc}{doRollover}{}
510Does a rollover, as described above.
511\end{methoddesc}
512
513\begin{methoddesc}{emit}{record}
514Outputs the record to the file, catering for rollover as described
515in \method{setRollover()}.
516\end{methoddesc}
517
518\subsubsection{SocketHandler}
519
520The \class{SocketHandler} class sends logging output to a network
521socket. The base class uses a TCP socket.
522
523\begin{classdesc}{SocketHandler}{host, port}
524Returns a new instance of the \class{SocketHandler} class intended to
525communicate with a remote machine whose address is given by \var{host}
526and \var{port}.
527\end{classdesc}
528
529\begin{methoddesc}{close}{}
530Closes the socket.
531\end{methoddesc}
532
533\begin{methoddesc}{handleError}{}
534\end{methoddesc}
535
536\begin{methoddesc}{emit}{}
537Pickles the record and writes it to the socket in binary format.
538If there is an error with the socket, silently drops the packet.
539If the connection was previously lost, re-establishes the connection.
540\end{methoddesc}
541
542\begin{methoddesc}{handleError}{}
543Handles an error which has occurred during \method{emit()}. The
544most likely cause is a lost connection. Closes the socket so that
545we can retry on the next event.
546\end{methoddesc}
547
548\begin{methoddesc}{makeSocket}{}
549This is a factory method which allows subclasses to define the precise
550type of socket they want. The default implementation creates a TCP
551socket (\constant{socket.SOCK_STREAM}).
552\end{methoddesc}
553
554\begin{methoddesc}{makePickle}{record}
555Pickles the record in binary format with a length prefix, and returns
556it ready for transmission across the socket.
557\end{methoddesc}
558
559\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000560Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000561for partial sends which can happen when the network is busy.
562\end{methoddesc}
563
564\subsubsection{DatagramHandler}
565
566The \class{DatagramHandler} class inherits from \class{SocketHandler}
567to support sending logging messages over UDP sockets.
568
569\begin{classdesc}{DatagramHandler}{host, port}
570Returns a new instance of the \class{DatagramHandler} class intended to
571communicate with a remote machine whose address is given by \var{host}
572and \var{port}.
573\end{classdesc}
574
575\begin{methoddesc}{emit}{}
576Pickles the record and writes it to the socket in binary format.
577If there is an error with the socket, silently drops the packet.
578\end{methoddesc}
579
580\begin{methoddesc}{makeSocket}{}
581The factory method of \class{SocketHandler} is here overridden to create
582a UDP socket (\constant{socket.SOCK_DGRAM}).
583\end{methoddesc}
584
585\begin{methoddesc}{send}{s}
586Send a pickled string to a socket. This function allows for
587partial sends which can happen when the network is busy.
588\end{methoddesc}
589
590\subsubsection{SysLogHandler}
591
592The \class{SysLogHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000593remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000594
595\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
596Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +0000597communicate with a remote \UNIX{} machine whose address is given by
598\var{address} in the form of a \code{(\var{host}, \var{port})}
599tuple. If \var{address} is not specified, \code{('localhost', 514)} is
600used. The address is used to open a UDP socket. If \var{facility} is
601not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000602\end{classdesc}
603
604\begin{methoddesc}{close}{}
605Closes the socket to the remote host.
606\end{methoddesc}
607
608\begin{methoddesc}{emit}{record}
609The record is formatted, and then sent to the syslog server. If
610exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +0000611\end{methoddesc}
612
613\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000614Encodes the facility and priority into an integer. You can pass in strings
615or integers - if strings are passed, internal mapping dictionaries are used
616to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000617\end{methoddesc}
618
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000619\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000620
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000621The \class{NTEventLogHandler} class supports sending logging messages
622to a local Windows NT, Windows 2000 or Windows XP event log. Before
623you can use it, you need Mark Hammond's Win32 extensions for Python
624installed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000625
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000626\begin{classdesc}{NTEventLogHandler}{appname
627 \optional{, dllname\optional{, logtype}}}
628Returns a new instance of the \class{NTEventLogHandler} class. The
629\var{appname} is used to define the application name as it appears in the
630event log. An appropriate registry entry is created using this name.
631The \var{dllname} should give the fully qualified pathname of a .dll or .exe
632which contains message definitions to hold in the log (if not specified,
633\constant{"win32service.pyd"} is used - this is installed with the Win32
634extensions and contains some basic placeholder message definitions.
635Note that use of these placeholders will make your event logs big, as the
636entire message source is held in the log. If you want slimmer logs, you have
637to pass in the name of your own .dll or .exe which contains the message
638definitions you want to use in the event log). The \var{logtype} is one of
639\constant{"Application"}, \constant{"System"} or \constant{"Security"}, and
640defaults to \constant{"Application"}.
641\end{classdesc}
642
643\begin{methoddesc}{close}{}
644At this point, you can remove the application name from the registry as a
645source of event log entries. However, if you do this, you will not be able
646to see the events as you intended in the Event Log Viewer - it needs to be
647able to access the registry to get the .dll name. The current version does
648not do this (in fact it doesn't do anything).
649\end{methoddesc}
650
651\begin{methoddesc}{emit}{record}
652Determines the message ID, event category and event type, and then logs the
653message in the NT event log.
654\end{methoddesc}
655
656\begin{methoddesc}{getEventCategory}{record}
657Returns the event category for the record. Override this if you
658want to specify your own categories. This version returns 0.
659\end{methoddesc}
660
661\begin{methoddesc}{getEventType}{record}
662Returns the event type for the record. Override this if you want
663to specify your own types. This version does a mapping using the
664handler's typemap attribute, which is set up in \method{__init__()}
665to a dictionary which contains mappings for \constant{DEBUG},
666\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
667\constant{CRITICAL}. If you are using your own levels, you will either need
668to override this method or place a suitable dictionary in the
669handler's \var{typemap} attribute.
670\end{methoddesc}
671
672\begin{methoddesc}{getMessageID}{record}
673Returns the message ID for the record. If you are using your
674own messages, you could do this by having the \var{msg} passed to the
675logger being an ID rather than a format string. Then, in here,
676you could use a dictionary lookup to get the message ID. This
677version returns 1, which is the base message ID in
678\constant{win32service.pyd}.
679\end{methoddesc}
680
681\subsubsection{SMTPHandler}
682
683The \class{SMTPHandler} class supports sending logging messages to an email
684address via SMTP.
685
686\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
687Returns a new instance of the \class{SMTPHandler} class. The
688instance is initialized with the from and to addresses and subject
689line of the email. The \var{toaddrs} should be a list of strings without
690domain names (That's what the \var{mailhost} is for). To specify a
691non-standard SMTP port, use the (host, port) tuple format for the
692\var{mailhost} argument. If you use a string, the standard SMTP port
693is used.
694\end{classdesc}
695
696\begin{methoddesc}{emit}{record}
697Formats the record and sends it to the specified addressees.
698\end{methoddesc}
699
700\begin{methoddesc}{getSubject}{record}
701If you want to specify a subject line which is record-dependent,
702override this method.
703\end{methoddesc}
704
705\subsubsection{MemoryHandler}
706
707The \class{MemoryHandler} supports buffering of logging records in memory,
708periodically flushing them to a \dfn{target} handler. Flushing occurs
709whenever the buffer is full, or when an event of a certain severity or
710greater is seen.
711
712\class{MemoryHandler} is a subclass of the more general
713\class{BufferingHandler}, which is an abstract class. This buffers logging
714records in memory. Whenever each record is added to the buffer, a
715check is made by calling \method{shouldFlush()} to see if the buffer
716should be flushed. If it should, then \method{flush()} is expected to
717do the needful.
718
719\begin{classdesc}{BufferingHandler}{capacity}
720Initializes the handler with a buffer of the specified capacity.
721\end{classdesc}
722
723\begin{methoddesc}{emit}{record}
724Appends the record to the buffer. If \method{shouldFlush()} returns true,
725calls \method{flush()} to process the buffer.
726\end{methoddesc}
727
728\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000729You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000730just zaps the buffer to empty.
731\end{methoddesc}
732
733\begin{methoddesc}{shouldFlush}{record}
734Returns true if the buffer is up to capacity. This method can be
735overridden to implement custom flushing strategies.
736\end{methoddesc}
737
738\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
739 \optional{, target}}}
740Returns a new instance of the \class{MemoryHandler} class. The
741instance is initialized with a buffer size of \var{capacity}. If
742\var{flushLevel} is not specified, \constant{ERROR} is used. If no
743\var{target} is specified, the target will need to be set using
744\method{setTarget()} before this handler does anything useful.
745\end{classdesc}
746
747\begin{methoddesc}{close}{}
748Calls \method{flush()}, sets the target to \constant{None} and
749clears the buffer.
750\end{methoddesc}
751
752\begin{methoddesc}{flush}{}
753For a \class{MemoryHandler}, flushing means just sending the buffered
754records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000755different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000756\end{methoddesc}
757
758\begin{methoddesc}{setTarget}{target}
759Sets the target handler for this handler.
760\end{methoddesc}
761
762\begin{methoddesc}{shouldFlush}{record}
763Checks for buffer full or a record at the \var{flushLevel} or higher.
764\end{methoddesc}
765
766\subsubsection{HTTPHandler}
767
768The \class{HTTPHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000769Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000770
771\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
772Returns a new instance of the \class{HTTPHandler} class. The
773instance is initialized with a host address, url and HTTP method.
Fred Drake68e6d572003-01-28 22:02:35 +0000774If no \var{method} is specified, \samp{GET} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000775\end{classdesc}
776
777\begin{methoddesc}{emit}{record}
778Sends the record to the Web server as an URL-encoded dictionary.
779\end{methoddesc}
780
781\subsection{Formatter Objects}
782
783\class{Formatter}s have the following attributes and methods. They are
784responsible for converting a \class{LogRecord} to (usually) a string
785which can be interpreted by either a human or an external system. The
786base
787\class{Formatter} allows a formatting string to be specified. If none is
788supplied, the default value of "\%s(message)\\n" is used.
789
790A Formatter can be initialized with a format string which makes use of
791knowledge of the \class{LogRecord} attributes - e.g. the default value
792mentioned above makes use of the fact that the user's message and
793arguments are pre- formatted into a LogRecord's \var{message}
794attribute. Currently, the useful attributes in a LogRecord are
795described by:
796
797\%(name)s Name of the logger (logging channel)
798\%(levelno)s Numeric logging level for the message (DEBUG, INFO,
799 WARNING, ERROR, CRITICAL)
800\%(levelname)s Text logging level for the message ("DEBUG", "INFO",
801 "WARNING", "ERROR", "CRITICAL")
802\%(pathname)s Full pathname of the source file where the logging
803 call was issued (if available)
804\%(filename)s Filename portion of pathname
805\%(module)s Module (name portion of filename)
806\%(lineno)d Source line number where the logging call was issued
807 (if available)
808\%(created)f Time when the LogRecord was created (time.time()
809 return value)
810\%(asctime)s Textual time when the LogRecord was created
811\%(msecs)d Millisecond portion of the creation time
812\%(relativeCreated)d Time in milliseconds when the LogRecord was created,
813 relative to the time the logging module was loaded
814 (typically at application startup time)
815\%(thread)d Thread ID (if available)
816\%(message)s The result of msg \% args, computed just as the
817 record is emitted
818
819
820\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
821Returns a new instance of the \class{Formatter} class. The
822instance is initialized with a format string for the message as a whole,
823as well as a format string for the date/time portion of a message. If
824no \var{fmt} is specified, "\%(message)s" is used. If no \var{datefmt}
825is specified, the ISO8601 date format is used.
826\end{classdesc}
827
828\begin{methoddesc}{format}{record}
829The record's attribute dictionary is used as the operand to a
830string formatting operation. Returns the resulting string.
831Before formatting the dictionary, a couple of preparatory steps
832are carried out. The \var{message} attribute of the record is computed
833using \var{msg} \% \var{args}. If the formatting string contains
834\constant{"(asctime)"}, \method{formatTime()} is called to format the
835event time. If there is exception information, it is formatted using
836\method{formatException()} and appended to the message.
837\end{methoddesc}
838
839\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
840This method should be called from \method{format()} by a formatter which
841wants to make use of a formatted time. This method can be overridden
842in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000843basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +0000844it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000845record. Otherwise, the ISO8601 format is used. The resulting
846string is returned.
847\end{methoddesc}
848
849\begin{methoddesc}{formatException}{exc_info}
850Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +0000851as returned by \function{sys.exc_info()}) as a string. This default
852implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000853The resulting string is returned.
854\end{methoddesc}
855
856\subsection{Filter Objects}
857
858\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
859more sophisticated filtering than is provided by levels. The base filter
860class only allows events which are below a certain point in the logger
861hierarchy. For example, a filter initialized with "A.B" will allow events
862logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
863"B.A.B" etc. If initialized with the empty string, all events are passed.
864
865\begin{classdesc}{Filter}{\optional{name}}
866Returns an instance of the \class{Filter} class. If \var{name} is specified,
867it names a logger which, together with its children, will have its events
868allowed through the filter. If no name is specified, allows every event.
869\end{classdesc}
870
871\begin{methoddesc}{filter}{record}
872Is the specified record to be logged? Returns zero for no, nonzero for
873yes. If deemed appropriate, the record may be modified in-place by this
874method.
875\end{methoddesc}
876
877\subsection{LogRecord Objects}
878
879LogRecord instances are created every time something is logged. They
880contain all the information pertinent to the event being logged. The
881main information passed in is in msg and args, which are combined
882using msg \% args to create the message field of the record. The record
883also includes information such as when the record was created, the
884source line where the logging call was made, and any exception
885information to be logged.
886
887LogRecord has no methods; it's just a repository for information about the
888logging event. The only reason it's a class rather than a dictionary is to
889facilitate extension.
890
891\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
892 exc_info}
893Returns an instance of \class{LogRecord} initialized with interesting
894information. The \var{name} is the logger name; \var{lvl} is the
895numeric level; \var{pathname} is the absolute pathname of the source
896file in which the logging call was made; \var{lineno} is the line
897number in that file where the logging call is found; \var{msg} is the
898user-supplied message (a format string); \var{args} is the tuple
899which, together with \var{msg}, makes up the user message; and
900\var{exc_info} is the exception tuple obtained by calling
901\function{sys.exc_info() }(or \constant{None}, if no exception information
902is available).
903\end{classdesc}
904
905\subsection{Thread Safety}
906
907The logging module is intended to be thread-safe without any special work
908needing to be done by its clients. It achieves this though using threading
909locks; there is one lock to serialize access to the module's shared data,
910and each handler also creates a lock to serialize access to its underlying
911I/O.
912
913\subsection{Configuration}
914
915
916\subsubsection{Configuration functions}
917
918The following functions allow the logging module to be configured.
919
920\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
921Reads the logging configuration from a ConfigParser-format file named
922\var{fname}. This function can be called several times from an application,
923allowing an end user the ability to select from various pre-canned
924configurations (if the developer provides a mechanism to present the
925choices and load the chosen configuration). Defaults to be passed to
926ConfigParser can be specified in the \var{defaults} argument.
927\end{funcdesc}
928
929\begin{funcdesc}{listen}{\optional{port}}
930Starts up a socket server on the specified port, and listens for new
931configurations. If no port is specified, the module's default
932\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
933will be sent as a file suitable for processing by \function{fileConfig()}.
934Returns a \class{Thread} instance on which you can call \method{start()}
935to start the server, and which you can \method{join()} when appropriate.
936To stop the server, call \function{stopListening()}.
937\end{funcdesc}
938
939\begin{funcdesc}{stopListening}{}
940Stops the listening server which was created with a call to
941\function{listen()}. This is typically called before calling \method{join()}
942on the return value from \function{listen()}.
943\end{funcdesc}
944
945\subsubsection{Configuration file format}
946
947The configuration file format understood by \function{fileConfig} is
948based on ConfigParser functionality. The file must contain sections
949called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
950which identify by name the entities of each type which are defined in
951the file. For each such entity, there is a separate section which
952identified how that entity is configured. Thus, for a logger named
953\code{log01} in the \code{[loggers]} section, the relevant
954configuration details are held in a section
955\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
956the \code{[handlers]} section will have its configuration held in a
957section called \code{[handler_hand01]}, while a formatter called
958\code{form01} in the \code{[formatters]} section will have its
959configuration specified in a section called
960\code{[formatter_form01]}. The root logger configuration must be
961specified in a section called \code{[logger_root]}.
962
963Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +0000964
965\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000966[loggers]
967keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +0000968
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000969[handlers]
970keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
971
972[formatters]
973keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +0000974\end{verbatim}
975
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000976The root logger must specify a level and a list of handlers. An
977example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +0000978
979\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000980[logger_root]
981level=NOTSET
982handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +0000983\end{verbatim}
984
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000985The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
986ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
987\code{NOTSET} means that all messages will be logged. Level values are
988\function{eval()}uated in the context of the \code{logging} package's
989namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +0000990
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000991The \code{handlers} entry is a comma-separated list of handler names,
992which must appear in the \code{[handlers]} section. These names must
993appear in the \code{[handlers]} section and have corresponding
994sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000995
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000996For loggers other than the root logger, some additional information is
997required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +0000998
999\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001000[logger_parser]
1001level=DEBUG
1002handlers=hand01
1003propagate=1
1004qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001005\end{verbatim}
1006
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001007The \code{level} and \code{handlers} entries are interpreted as for
1008the root logger, except that if a non-root logger's level is specified
1009as \code{NOTSET}, the system consults loggers higher up the hierarchy
1010to determine the effective level of the logger. The \code{propagate}
1011entry is set to 1 to indicate that messages must propagate to handlers
1012higher up the logger hierarchy from this logger, or 0 to indicate that
1013messages are \strong{not} propagated to handlers up the hierarchy. The
1014\code{qualname} entry is the hierarchical channel name of the logger,
1015i.e. the name used by the application to get the logger.
1016
1017Sections which specify handler configuration are exemplified by the
1018following.
1019
Skip Montanaro649698f2002-11-14 03:57:19 +00001020\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001021[handler_hand01]
1022class=StreamHandler
1023level=NOTSET
1024formatter=form01
1025args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001026\end{verbatim}
1027
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001028The \code{class} entry indicates the handler's class (as determined by
1029\function{eval()} in the \code{logging} package's namespace). The
1030\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1031to mean "log everything".
1032
1033The \code{formatter} entry indicates the key name of the formatter for
1034this handler. If blank, a default formatter
1035(\code{logging._defaultFormatter}) is used. If a name is specified, it
1036must appear in the \code{[formatters]} section and have a
1037corresponding section in the configuration file.
1038
1039The \code{args} entry, when \function{eval()}uated in the context of
1040the \code{logging} package's namespace, is the list of arguments to
1041the constructor for the handler class. Refer to the constructors for
1042the relevant handlers, or to the examples below, to see how typical
1043entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001044
1045\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001046[handler_hand02]
1047class=FileHandler
1048level=DEBUG
1049formatter=form02
1050args=('python.log', 'w')
1051
1052[handler_hand03]
1053class=handlers.SocketHandler
1054level=INFO
1055formatter=form03
1056args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1057
1058[handler_hand04]
1059class=handlers.DatagramHandler
1060level=WARN
1061formatter=form04
1062args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1063
1064[handler_hand05]
1065class=handlers.SysLogHandler
1066level=ERROR
1067formatter=form05
1068args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1069
1070[handler_hand06]
1071class=NTEventLogHandler
1072level=CRITICAL
1073formatter=form06
1074args=('Python Application', '', 'Application')
1075
1076[handler_hand07]
1077class=SMTPHandler
1078level=WARN
1079formatter=form07
1080args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1081
1082[handler_hand08]
1083class=MemoryHandler
1084level=NOTSET
1085formatter=form08
1086target=
1087args=(10, ERROR)
1088
1089[handler_hand09]
1090class=HTTPHandler
1091level=NOTSET
1092formatter=form09
1093args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001094\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001095
1096Sections which specify formatter configuration are typified by the following.
1097
1098\begin{verbatim}
1099[formatter_form01]
1100format=F1 %(asctime)s %(levelname)s %(message)s
1101datefmt=
1102\end{verbatim}
1103
1104The \code{format} entry is the overall format string, and the
1105\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1106string. If empty, the package substitutes ISO8601 format date/times, which
1107is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1108The ISO8601 format also specifies milliseconds, which are appended to the
1109result of using the above format string, with a comma separator. An example
1110time in ISO8601 format is \code{2003-01-23 00:29:50,411}.