blob: c225479d334cd4c93ea49a30c9f160b3cfde2068 [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
11\modulesynopsis{Logging module for Python based on PEP 282.}
12
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
32\method{debug}, \method{info}, \method{warning}, \method{error} and
33\method{critical}, which mirrors 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
36explicit 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,
60\emph{all handlers associated with all ancestors of the logger} are called
61upon 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.
65If a handler decides to actually dispatch an event, the \method{emit} method
66is used to send the message to its destination. Most user-defined subclasses
67of \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
93Unix syslog, possibly on a remote machine.
94
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
103HTTP server using either GET or POST semantics.
104
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
123\class{Handler} instances (through their \method{addFilter} method).
124Before 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
150\method{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
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000230\subsection{Logger Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000231
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000232Loggers have the following attributes and methods. Note that Loggers are
233never instantiated directly, but always through the module-level function
234\function{logging.getLogger(name)}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000235
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000236\begin{datadesc}{propagate}
237If this evaluates to false, logging messages are not passed by this
238logger or by child loggers to higher level (ancestor) loggers. The
239constructor sets this attribute to 1.
Skip Montanaro649698f2002-11-14 03:57:19 +0000240\end{datadesc}
241
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000242\begin{methoddesc}{setLevel}{lvl}
243Sets the threshold for this logger to \var{lvl}. Logging messages
244which are less severe than \var{lvl} will be ignored. When a logger is
245created, the level is set to \constant{ALL} (which causes all messages
246to be processed).
Skip Montanaro649698f2002-11-14 03:57:19 +0000247\end{methoddesc}
248
249\begin{methoddesc}{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000250Indicates if a message of severity \var{lvl} would be processed by
251this logger. This method checks first the module-level level set by
252\function{logging.disable(lvl)} and then the logger's effective level as
253determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000254\end{methoddesc}
255
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000256\begin{methoddesc}{getEffectiveLevel}{}
257Indicates the effective level for this logger. If a value other than
258\constant{ALL} has been set using \method{setLevel()}, it is returned.
259Otherwise, the hierarchy is traversed towards the root until a value
260other than \constant{ALL} is found,and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000261\end{methoddesc}
262
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000263\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
264Logs a message with level \constant{DEBUG} on this logger.
265The \var{msg} is the message format string, and the \var{args} are the
266arguments which are merged into \var{msg}. The only keyword argument in
267\var{kwargs} which is inspected is \var{exc_info} which, if it does not
268evaluate as false, causes exception information (via a call to
269\method{sys.exc_info()}) to be added to the logging message.
270\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000271
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000272\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
273Logs a message with level \constant{INFO} on this logger.
274The arguments are interpreted as for \method{debug()}.
275\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000276
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000277\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
278Logs a message with level \constant{WARNING} on this logger.
279The arguments are interpreted as for \method{debug()}.
280\end{methoddesc}
281
282\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
283Logs a message with level \constant{ERROR} on this logger.
284The arguments are interpreted as for \method{debug()}.
285\end{methoddesc}
286
287\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
288Logs a message with level \constant{CRITICAL} on this logger.
289The arguments are interpreted as for \method{debug()}.
290\end{methoddesc}
291
292\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
293Logs a message with level \var{lvl} on this logger.
294The other arguments are interpreted as for \method{debug()}.
295\end{methoddesc}
296
297\begin{methoddesc}{exception}{msg\optional{, *args}}
298Logs a message with level \constant{ERROR} on this logger.
299The arguments are interpreted as for \method{debug()}. Exception info
300is added to the logging message. This method should only be called
301from an exception handler.
302\end{methoddesc}
303
304\begin{methoddesc}{addFilter}{filt}
305Adds the specified filter \var{filt} to this logger.
306\end{methoddesc}
307
308\begin{methoddesc}{removeFilter}{filt}
309Removes the specified filter \var{filt} from this logger.
310\end{methoddesc}
311
312\begin{methoddesc}{filter}{record}
313Applies this logger's filters to the record and returns a true value if
314the record is to be processed.
315\end{methoddesc}
316
317\begin{methoddesc}{addHandler}{hdlr}
318Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000319\end{methoddesc}
320
321\begin{methoddesc}{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000322Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000323\end{methoddesc}
324
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000325\begin{methoddesc}{findCaller}{}
326Finds the caller's source filename and line number. Returns the filename
327and line number as a 2-element tuple.
Skip Montanaro649698f2002-11-14 03:57:19 +0000328\end{methoddesc}
329
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000330\begin{methoddesc}{handle}{record}
331Handles a record by passing it to all handlers associated with this logger
332and its ancestors (until a false value of \var{propagate} is found).
333This method is used for unpickled records received from a socket, as well
334as those created locally. Logger-level filtering is applied using
335\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000336\end{methoddesc}
337
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000338\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info}
339This is a factory method which can be overridden in subclasses to create
340specialized \class{LogRecord} instances.
Skip Montanaro649698f2002-11-14 03:57:19 +0000341\end{methoddesc}
342
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000343\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000344
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000345Handlers have the following attributes and methods. Note that a Handler is
346never instantiated directly; this class acts as a base for more useful
347subclasses. However, the \method{__init__()} in subclasses needs to call
348\method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000349
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000350\begin{methoddesc}{__init__}{level=\constant{ALL}}
351Initializes the \class{Handler} instance by setting its level, setting
352the list of filters to the empty list and creating a lock (using
353\method{getLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000354\end{methoddesc}
355
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000356\begin{methoddesc}{createLock}{}
357Initializes a thread lock which can be used to serialize access to
358underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000359\end{methoddesc}
360
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000361\begin{methoddesc}{acquire}{}
362Acquires the thread lock created with \method{createLock()}.
363\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000364
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000365\begin{methoddesc}{release}{}
366Releases the thread lock acquired with \method{acquire()}.
367\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000368
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000369\begin{methoddesc}{setLevel}{lvl}
370Sets the threshold for this handler to \var{lvl}. Logging messages which are
371less severe than \var{lvl} will be ignored. When a handler is created, the
372level is set to \constant{ALL} (which causes all messages to be processed).
373\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000374
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000375\begin{methoddesc}{setFormatter}{form}
376Sets the \class{Formatter} for this handler to \var{form}.
377\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000378
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000379\begin{methoddesc}{addFilter}{filt}
380Adds the specified filter \var{filt} to this handler.
381\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000382
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000383\begin{methoddesc}{removeFilter}{filt}
384Removes the specified filter \var{filt} from this handler.
385\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000386
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000387\begin{methoddesc}{filter}{record}
388Applies this handler's filters to the record and returns a true value if
389the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000390\end{methoddesc}
391
392\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000393Ensure all logging output has been flushed. This version does
394nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000395\end{methoddesc}
396
Skip Montanaro649698f2002-11-14 03:57:19 +0000397\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000398Tidy up any resources used by the handler. This version does
399nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000400\end{methoddesc}
401
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000402\begin{methoddesc}{handle}{record}
403Conditionally emits the specified logging record, depending on
404filters which may have been added to the handler. Wraps the actual
405emission of the record with acquisition/release of the I/O thread
406lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000407\end{methoddesc}
408
409\begin{methoddesc}{handleError}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000410This method should be called from handlers when an exception is
411encountered during an emit() call. By default it does nothing,
412which means that exceptions get silently ignored. This is what is
413mostly wanted for a logging system - most users will not care
414about errors in the logging system, they are more interested in
415application errors. You could, however, replace this with a custom
416handler if you wish.
Skip Montanaro649698f2002-11-14 03:57:19 +0000417\end{methoddesc}
418
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000419\begin{methoddesc}{format}{record}
420Do formatting for a record - if a formatter is set, use it.
421Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000422\end{methoddesc}
423
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000424\begin{methoddesc}{emit}{record}
425Do whatever it takes to actually log the specified logging record.
426This version is intended to be implemented by subclasses and so
427raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000428\end{methoddesc}
429
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000430\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000431
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000432The \class{StreamHandler} class sends logging output to streams such as
433\var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more
434precisely, any object which supports \method{write()} and \method{flush()}
435methods.
Skip Montanaro649698f2002-11-14 03:57:19 +0000436
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000437\begin{classdesc}{StreamHandler}{\optional{strm}}
438Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
439specified, the instance will use it for logging output; otherwise,
440\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000441\end{classdesc}
442
443\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000444If a formatter is specified, it is used to format the record.
445The record is then written to the stream with a trailing newline.
446If exception information is present, it is formatted using
447\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000448\end{methoddesc}
449
450\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000451Flushes the stream by calling its \method{flush()} method. Note that
452the \method{close()} method is inherited from \class{Handler} and
453so does nothing, so an explicit \method{flush()} call may be needed
454at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000455\end{methoddesc}
456
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000457\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000458
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000459The \class{FileHandler} class sends logging output to a disk file.
460It delegates the output functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000461
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000462\begin{classdesc}{FileHandler}{filename\optional{, mode}}
463Returns a new instance of the \class{FileHandler} class. The specified
464file is opened and used as the stream for logging. If \var{mode} is
465not specified, \constant{"a"} is used. By default, the file grows
466indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000467\end{classdesc}
468
469\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000470Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000471\end{methoddesc}
472
473\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000474Outputs the record to the file.
475\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000476
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000477\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000478
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000479The \class{RotatingFileHandler} class supports rotation of disk log files.
480
481\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode, maxBytes,
482 backupCount}}
483Returns a new instance of the \class{RotatingFileHandler} class. The
484specified file is opened and used as the stream for logging. If
485\var{mode} is not specified, \constant{"a"} is used. By default, the
486file grows indefinitely. You can use the \var{maxBytes} and
487\var{backupCount} values to allow the file to \dfn{rollover} at a
488predetermined size. When the size is about to be exceeded, the file is
489closed and a new file opened for output, transparently to the
490caller. Rollover occurs whenever the current log file is nearly
491\var{maxBytes} in length. If \var{backupCount} is >= 1, the system
492will successively create new files with the same pathname as the base
493file, but with extensions ".1", ".2" etc. appended to it. For example,
494with a backupCount of 5 and a base file name of "app.log", you would
495get "app.log", "app.log.1", "app.log.2", ... through to
496"app.log.5". When the last file reaches its size limit, the logging
497reverts to "app.log" which is truncated to zero length. If
498\var{maxBytes} is zero, rollover never occurs.
499\end{classdesc}
500
501\begin{methoddesc}{doRollover}{}
502Does a rollover, as described above.
503\end{methoddesc}
504
505\begin{methoddesc}{emit}{record}
506Outputs the record to the file, catering for rollover as described
507in \method{setRollover()}.
508\end{methoddesc}
509
510\subsubsection{SocketHandler}
511
512The \class{SocketHandler} class sends logging output to a network
513socket. The base class uses a TCP socket.
514
515\begin{classdesc}{SocketHandler}{host, port}
516Returns a new instance of the \class{SocketHandler} class intended to
517communicate with a remote machine whose address is given by \var{host}
518and \var{port}.
519\end{classdesc}
520
521\begin{methoddesc}{close}{}
522Closes the socket.
523\end{methoddesc}
524
525\begin{methoddesc}{handleError}{}
526\end{methoddesc}
527
528\begin{methoddesc}{emit}{}
529Pickles the record and writes it to the socket in binary format.
530If there is an error with the socket, silently drops the packet.
531If the connection was previously lost, re-establishes the connection.
532\end{methoddesc}
533
534\begin{methoddesc}{handleError}{}
535Handles an error which has occurred during \method{emit()}. The
536most likely cause is a lost connection. Closes the socket so that
537we can retry on the next event.
538\end{methoddesc}
539
540\begin{methoddesc}{makeSocket}{}
541This is a factory method which allows subclasses to define the precise
542type of socket they want. The default implementation creates a TCP
543socket (\constant{socket.SOCK_STREAM}).
544\end{methoddesc}
545
546\begin{methoddesc}{makePickle}{record}
547Pickles the record in binary format with a length prefix, and returns
548it ready for transmission across the socket.
549\end{methoddesc}
550
551\begin{methoddesc}{send}{packet}
552Send a pickled string \var{packe} to the socket. This function allows
553for partial sends which can happen when the network is busy.
554\end{methoddesc}
555
556\subsubsection{DatagramHandler}
557
558The \class{DatagramHandler} class inherits from \class{SocketHandler}
559to support sending logging messages over UDP sockets.
560
561\begin{classdesc}{DatagramHandler}{host, port}
562Returns a new instance of the \class{DatagramHandler} class intended to
563communicate with a remote machine whose address is given by \var{host}
564and \var{port}.
565\end{classdesc}
566
567\begin{methoddesc}{emit}{}
568Pickles the record and writes it to the socket in binary format.
569If there is an error with the socket, silently drops the packet.
570\end{methoddesc}
571
572\begin{methoddesc}{makeSocket}{}
573The factory method of \class{SocketHandler} is here overridden to create
574a UDP socket (\constant{socket.SOCK_DGRAM}).
575\end{methoddesc}
576
577\begin{methoddesc}{send}{s}
578Send a pickled string to a socket. This function allows for
579partial sends which can happen when the network is busy.
580\end{methoddesc}
581
582\subsubsection{SysLogHandler}
583
584The \class{SysLogHandler} class supports sending logging messages to a
585remote or local Unix syslog.
586
587\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
588Returns a new instance of the \class{SysLogHandler} class intended to
589communicate with a remote Unix machine whose address is given by
590\var{address} in the form of a (host, port) tuple. If \var{address} is not
591specified, ('localhost', 514) is used. The address is used to open a UDP
592socket. If \var{facility} is not specified, \constant{LOG_USER} is used.
593\end{classdesc}
594
595\begin{methoddesc}{close}{}
596Closes the socket to the remote host.
597\end{methoddesc}
598
599\begin{methoddesc}{emit}{record}
600The record is formatted, and then sent to the syslog server. If
601exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +0000602\end{methoddesc}
603
604\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000605Encodes the facility and priority into an integer. You can pass in strings
606or integers - if strings are passed, internal mapping dictionaries are used
607to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000608\end{methoddesc}
609
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000610\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000611
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000612The \class{NTEventLogHandler} class supports sending logging messages
613to a local Windows NT, Windows 2000 or Windows XP event log. Before
614you can use it, you need Mark Hammond's Win32 extensions for Python
615installed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000616
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000617\begin{classdesc}{NTEventLogHandler}{appname
618 \optional{, dllname\optional{, logtype}}}
619Returns a new instance of the \class{NTEventLogHandler} class. The
620\var{appname} is used to define the application name as it appears in the
621event log. An appropriate registry entry is created using this name.
622The \var{dllname} should give the fully qualified pathname of a .dll or .exe
623which contains message definitions to hold in the log (if not specified,
624\constant{"win32service.pyd"} is used - this is installed with the Win32
625extensions and contains some basic placeholder message definitions.
626Note that use of these placeholders will make your event logs big, as the
627entire message source is held in the log. If you want slimmer logs, you have
628to pass in the name of your own .dll or .exe which contains the message
629definitions you want to use in the event log). The \var{logtype} is one of
630\constant{"Application"}, \constant{"System"} or \constant{"Security"}, and
631defaults to \constant{"Application"}.
632\end{classdesc}
633
634\begin{methoddesc}{close}{}
635At this point, you can remove the application name from the registry as a
636source of event log entries. However, if you do this, you will not be able
637to see the events as you intended in the Event Log Viewer - it needs to be
638able to access the registry to get the .dll name. The current version does
639not do this (in fact it doesn't do anything).
640\end{methoddesc}
641
642\begin{methoddesc}{emit}{record}
643Determines the message ID, event category and event type, and then logs the
644message in the NT event log.
645\end{methoddesc}
646
647\begin{methoddesc}{getEventCategory}{record}
648Returns the event category for the record. Override this if you
649want to specify your own categories. This version returns 0.
650\end{methoddesc}
651
652\begin{methoddesc}{getEventType}{record}
653Returns the event type for the record. Override this if you want
654to specify your own types. This version does a mapping using the
655handler's typemap attribute, which is set up in \method{__init__()}
656to a dictionary which contains mappings for \constant{DEBUG},
657\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
658\constant{CRITICAL}. If you are using your own levels, you will either need
659to override this method or place a suitable dictionary in the
660handler's \var{typemap} attribute.
661\end{methoddesc}
662
663\begin{methoddesc}{getMessageID}{record}
664Returns the message ID for the record. If you are using your
665own messages, you could do this by having the \var{msg} passed to the
666logger being an ID rather than a format string. Then, in here,
667you could use a dictionary lookup to get the message ID. This
668version returns 1, which is the base message ID in
669\constant{win32service.pyd}.
670\end{methoddesc}
671
672\subsubsection{SMTPHandler}
673
674The \class{SMTPHandler} class supports sending logging messages to an email
675address via SMTP.
676
677\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
678Returns a new instance of the \class{SMTPHandler} class. The
679instance is initialized with the from and to addresses and subject
680line of the email. The \var{toaddrs} should be a list of strings without
681domain names (That's what the \var{mailhost} is for). To specify a
682non-standard SMTP port, use the (host, port) tuple format for the
683\var{mailhost} argument. If you use a string, the standard SMTP port
684is used.
685\end{classdesc}
686
687\begin{methoddesc}{emit}{record}
688Formats the record and sends it to the specified addressees.
689\end{methoddesc}
690
691\begin{methoddesc}{getSubject}{record}
692If you want to specify a subject line which is record-dependent,
693override this method.
694\end{methoddesc}
695
696\subsubsection{MemoryHandler}
697
698The \class{MemoryHandler} supports buffering of logging records in memory,
699periodically flushing them to a \dfn{target} handler. Flushing occurs
700whenever the buffer is full, or when an event of a certain severity or
701greater is seen.
702
703\class{MemoryHandler} is a subclass of the more general
704\class{BufferingHandler}, which is an abstract class. This buffers logging
705records in memory. Whenever each record is added to the buffer, a
706check is made by calling \method{shouldFlush()} to see if the buffer
707should be flushed. If it should, then \method{flush()} is expected to
708do the needful.
709
710\begin{classdesc}{BufferingHandler}{capacity}
711Initializes the handler with a buffer of the specified capacity.
712\end{classdesc}
713
714\begin{methoddesc}{emit}{record}
715Appends the record to the buffer. If \method{shouldFlush()} returns true,
716calls \method{flush()} to process the buffer.
717\end{methoddesc}
718
719\begin{methoddesc}{flush}{}
720You can override this to implement custom flushing behaviour. This version
721just zaps the buffer to empty.
722\end{methoddesc}
723
724\begin{methoddesc}{shouldFlush}{record}
725Returns true if the buffer is up to capacity. This method can be
726overridden to implement custom flushing strategies.
727\end{methoddesc}
728
729\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
730 \optional{, target}}}
731Returns a new instance of the \class{MemoryHandler} class. The
732instance is initialized with a buffer size of \var{capacity}. If
733\var{flushLevel} is not specified, \constant{ERROR} is used. If no
734\var{target} is specified, the target will need to be set using
735\method{setTarget()} before this handler does anything useful.
736\end{classdesc}
737
738\begin{methoddesc}{close}{}
739Calls \method{flush()}, sets the target to \constant{None} and
740clears the buffer.
741\end{methoddesc}
742
743\begin{methoddesc}{flush}{}
744For a \class{MemoryHandler}, flushing means just sending the buffered
745records to the target, if there is one. Override if you want
746different behaviour.
747\end{methoddesc}
748
749\begin{methoddesc}{setTarget}{target}
750Sets the target handler for this handler.
751\end{methoddesc}
752
753\begin{methoddesc}{shouldFlush}{record}
754Checks for buffer full or a record at the \var{flushLevel} or higher.
755\end{methoddesc}
756
757\subsubsection{HTTPHandler}
758
759The \class{HTTPHandler} class supports sending logging messages to a
760Web server, using either GET or POST semantics.
761
762\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
763Returns a new instance of the \class{HTTPHandler} class. The
764instance is initialized with a host address, url and HTTP method.
765If no \var{method} is specified, GET is used.
766\end{classdesc}
767
768\begin{methoddesc}{emit}{record}
769Sends the record to the Web server as an URL-encoded dictionary.
770\end{methoddesc}
771
772\subsection{Formatter Objects}
773
774\class{Formatter}s have the following attributes and methods. They are
775responsible for converting a \class{LogRecord} to (usually) a string
776which can be interpreted by either a human or an external system. The
777base
778\class{Formatter} allows a formatting string to be specified. If none is
779supplied, the default value of "\%s(message)\\n" is used.
780
781A Formatter can be initialized with a format string which makes use of
782knowledge of the \class{LogRecord} attributes - e.g. the default value
783mentioned above makes use of the fact that the user's message and
784arguments are pre- formatted into a LogRecord's \var{message}
785attribute. Currently, the useful attributes in a LogRecord are
786described by:
787
788\%(name)s Name of the logger (logging channel)
789\%(levelno)s Numeric logging level for the message (DEBUG, INFO,
790 WARNING, ERROR, CRITICAL)
791\%(levelname)s Text logging level for the message ("DEBUG", "INFO",
792 "WARNING", "ERROR", "CRITICAL")
793\%(pathname)s Full pathname of the source file where the logging
794 call was issued (if available)
795\%(filename)s Filename portion of pathname
796\%(module)s Module (name portion of filename)
797\%(lineno)d Source line number where the logging call was issued
798 (if available)
799\%(created)f Time when the LogRecord was created (time.time()
800 return value)
801\%(asctime)s Textual time when the LogRecord was created
802\%(msecs)d Millisecond portion of the creation time
803\%(relativeCreated)d Time in milliseconds when the LogRecord was created,
804 relative to the time the logging module was loaded
805 (typically at application startup time)
806\%(thread)d Thread ID (if available)
807\%(message)s The result of msg \% args, computed just as the
808 record is emitted
809
810
811\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
812Returns a new instance of the \class{Formatter} class. The
813instance is initialized with a format string for the message as a whole,
814as well as a format string for the date/time portion of a message. If
815no \var{fmt} is specified, "\%(message)s" is used. If no \var{datefmt}
816is specified, the ISO8601 date format is used.
817\end{classdesc}
818
819\begin{methoddesc}{format}{record}
820The record's attribute dictionary is used as the operand to a
821string formatting operation. Returns the resulting string.
822Before formatting the dictionary, a couple of preparatory steps
823are carried out. The \var{message} attribute of the record is computed
824using \var{msg} \% \var{args}. If the formatting string contains
825\constant{"(asctime)"}, \method{formatTime()} is called to format the
826event time. If there is exception information, it is formatted using
827\method{formatException()} and appended to the message.
828\end{methoddesc}
829
830\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
831This method should be called from \method{format()} by a formatter which
832wants to make use of a formatted time. This method can be overridden
833in formatters to provide for any specific requirement, but the
834basic behaviour is as follows: if \var{datefmt} (a string) is specified,
835it is used with \method{time.strftime()} to format the creation time of the
836record. Otherwise, the ISO8601 format is used. The resulting
837string is returned.
838\end{methoddesc}
839
840\begin{methoddesc}{formatException}{exc_info}
841Formats the specified exception information (a standard exception tuple
842as returned by \method{sys.exc_info()}) as a string. This default
843implementation just uses \method{traceback.print_exception()}.
844The resulting string is returned.
845\end{methoddesc}
846
847\subsection{Filter Objects}
848
849\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
850more sophisticated filtering than is provided by levels. The base filter
851class only allows events which are below a certain point in the logger
852hierarchy. For example, a filter initialized with "A.B" will allow events
853logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
854"B.A.B" etc. If initialized with the empty string, all events are passed.
855
856\begin{classdesc}{Filter}{\optional{name}}
857Returns an instance of the \class{Filter} class. If \var{name} is specified,
858it names a logger which, together with its children, will have its events
859allowed through the filter. If no name is specified, allows every event.
860\end{classdesc}
861
862\begin{methoddesc}{filter}{record}
863Is the specified record to be logged? Returns zero for no, nonzero for
864yes. If deemed appropriate, the record may be modified in-place by this
865method.
866\end{methoddesc}
867
868\subsection{LogRecord Objects}
869
870LogRecord instances are created every time something is logged. They
871contain all the information pertinent to the event being logged. The
872main information passed in is in msg and args, which are combined
873using msg \% args to create the message field of the record. The record
874also includes information such as when the record was created, the
875source line where the logging call was made, and any exception
876information to be logged.
877
878LogRecord has no methods; it's just a repository for information about the
879logging event. The only reason it's a class rather than a dictionary is to
880facilitate extension.
881
882\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
883 exc_info}
884Returns an instance of \class{LogRecord} initialized with interesting
885information. The \var{name} is the logger name; \var{lvl} is the
886numeric level; \var{pathname} is the absolute pathname of the source
887file in which the logging call was made; \var{lineno} is the line
888number in that file where the logging call is found; \var{msg} is the
889user-supplied message (a format string); \var{args} is the tuple
890which, together with \var{msg}, makes up the user message; and
891\var{exc_info} is the exception tuple obtained by calling
892\function{sys.exc_info() }(or \constant{None}, if no exception information
893is available).
894\end{classdesc}
895
896\subsection{Thread Safety}
897
898The logging module is intended to be thread-safe without any special work
899needing to be done by its clients. It achieves this though using threading
900locks; there is one lock to serialize access to the module's shared data,
901and each handler also creates a lock to serialize access to its underlying
902I/O.
903
904\subsection{Configuration}
905
906
907\subsubsection{Configuration functions}
908
909The following functions allow the logging module to be configured.
910
911\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
912Reads the logging configuration from a ConfigParser-format file named
913\var{fname}. This function can be called several times from an application,
914allowing an end user the ability to select from various pre-canned
915configurations (if the developer provides a mechanism to present the
916choices and load the chosen configuration). Defaults to be passed to
917ConfigParser can be specified in the \var{defaults} argument.
918\end{funcdesc}
919
920\begin{funcdesc}{listen}{\optional{port}}
921Starts up a socket server on the specified port, and listens for new
922configurations. If no port is specified, the module's default
923\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
924will be sent as a file suitable for processing by \function{fileConfig()}.
925Returns a \class{Thread} instance on which you can call \method{start()}
926to start the server, and which you can \method{join()} when appropriate.
927To stop the server, call \function{stopListening()}.
928\end{funcdesc}
929
930\begin{funcdesc}{stopListening}{}
931Stops the listening server which was created with a call to
932\function{listen()}. This is typically called before calling \method{join()}
933on the return value from \function{listen()}.
934\end{funcdesc}
935
936\subsubsection{Configuration file format}
937
938The configuration file format understood by \function{fileConfig} is
939based on ConfigParser functionality. The file must contain sections
940called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
941which identify by name the entities of each type which are defined in
942the file. For each such entity, there is a separate section which
943identified how that entity is configured. Thus, for a logger named
944\code{log01} in the \code{[loggers]} section, the relevant
945configuration details are held in a section
946\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
947the \code{[handlers]} section will have its configuration held in a
948section called \code{[handler_hand01]}, while a formatter called
949\code{form01} in the \code{[formatters]} section will have its
950configuration specified in a section called
951\code{[formatter_form01]}. The root logger configuration must be
952specified in a section called \code{[logger_root]}.
953
954Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +0000955
956\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000957[loggers]
958keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +0000959
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000960[handlers]
961keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
962
963[formatters]
964keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +0000965\end{verbatim}
966
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000967The root logger must specify a level and a list of handlers. An
968example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +0000969
970\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000971[logger_root]
972level=NOTSET
973handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +0000974\end{verbatim}
975
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000976The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
977ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
978\code{NOTSET} means that all messages will be logged. Level values are
979\function{eval()}uated in the context of the \code{logging} package's
980namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +0000981
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000982The \code{handlers} entry is a comma-separated list of handler names,
983which must appear in the \code{[handlers]} section. These names must
984appear in the \code{[handlers]} section and have corresponding
985sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000986
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000987For loggers other than the root logger, some additional information is
988required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +0000989
990\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000991[logger_parser]
992level=DEBUG
993handlers=hand01
994propagate=1
995qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +0000996\end{verbatim}
997
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000998The \code{level} and \code{handlers} entries are interpreted as for
999the root logger, except that if a non-root logger's level is specified
1000as \code{NOTSET}, the system consults loggers higher up the hierarchy
1001to determine the effective level of the logger. The \code{propagate}
1002entry is set to 1 to indicate that messages must propagate to handlers
1003higher up the logger hierarchy from this logger, or 0 to indicate that
1004messages are \strong{not} propagated to handlers up the hierarchy. The
1005\code{qualname} entry is the hierarchical channel name of the logger,
1006i.e. the name used by the application to get the logger.
1007
1008Sections which specify handler configuration are exemplified by the
1009following.
1010
Skip Montanaro649698f2002-11-14 03:57:19 +00001011\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001012[handler_hand01]
1013class=StreamHandler
1014level=NOTSET
1015formatter=form01
1016args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001017\end{verbatim}
1018
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001019The \code{class} entry indicates the handler's class (as determined by
1020\function{eval()} in the \code{logging} package's namespace). The
1021\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1022to mean "log everything".
1023
1024The \code{formatter} entry indicates the key name of the formatter for
1025this handler. If blank, a default formatter
1026(\code{logging._defaultFormatter}) is used. If a name is specified, it
1027must appear in the \code{[formatters]} section and have a
1028corresponding section in the configuration file.
1029
1030The \code{args} entry, when \function{eval()}uated in the context of
1031the \code{logging} package's namespace, is the list of arguments to
1032the constructor for the handler class. Refer to the constructors for
1033the relevant handlers, or to the examples below, to see how typical
1034entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001035
1036\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001037[handler_hand02]
1038class=FileHandler
1039level=DEBUG
1040formatter=form02
1041args=('python.log', 'w')
1042
1043[handler_hand03]
1044class=handlers.SocketHandler
1045level=INFO
1046formatter=form03
1047args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1048
1049[handler_hand04]
1050class=handlers.DatagramHandler
1051level=WARN
1052formatter=form04
1053args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1054
1055[handler_hand05]
1056class=handlers.SysLogHandler
1057level=ERROR
1058formatter=form05
1059args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1060
1061[handler_hand06]
1062class=NTEventLogHandler
1063level=CRITICAL
1064formatter=form06
1065args=('Python Application', '', 'Application')
1066
1067[handler_hand07]
1068class=SMTPHandler
1069level=WARN
1070formatter=form07
1071args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1072
1073[handler_hand08]
1074class=MemoryHandler
1075level=NOTSET
1076formatter=form08
1077target=
1078args=(10, ERROR)
1079
1080[handler_hand09]
1081class=HTTPHandler
1082level=NOTSET
1083formatter=form09
1084args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001085\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001086
1087Sections which specify formatter configuration are typified by the following.
1088
1089\begin{verbatim}
1090[formatter_form01]
1091format=F1 %(asctime)s %(levelname)s %(message)s
1092datefmt=
1093\end{verbatim}
1094
1095The \code{format} entry is the overall format string, and the
1096\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1097string. If empty, the package substitutes ISO8601 format date/times, which
1098is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1099The ISO8601 format also specifies milliseconds, which are appended to the
1100result of using the above format string, with a comma separator. An example
1101time in ISO8601 format is \code{2003-01-23 00:29:50,411}.