blob: c86596d1d5be0edbc166f562b224afaadb8abc7f [file] [log] [blame]
Skip Montanaro649698f2002-11-14 03:57:19 +00001\section{\module{logging} ---
2 Logging facility for Python}
3
Fred Drake9a5b6a62003-07-08 15:38:40 +00004\declaremodule{standard}{logging}
Skip Montanaro649698f2002-11-14 03:57:19 +00005
6% These apply to all modules, and may be given more than once:
7
8\moduleauthor{Vinay Sajip}{vinay_sajip@red-dove.com}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00009\sectionauthor{Vinay Sajip}{vinay_sajip@red-dove.com}
Skip Montanaro649698f2002-11-14 03:57:19 +000010
Fred Drake68e6d572003-01-28 22:02:35 +000011\modulesynopsis{Logging module for Python based on \pep{282}.}
Skip Montanaro649698f2002-11-14 03:57:19 +000012
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000013\indexii{Errors}{logging}
Skip Montanaro649698f2002-11-14 03:57:19 +000014
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000015\versionadded{2.3}
16This module defines functions and classes which implement a flexible
17error logging system for applications.
Skip Montanaro649698f2002-11-14 03:57:19 +000018
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000019Logging is performed by calling methods on instances of the
20\class{Logger} class (hereafter called \dfn{loggers}). Each instance has a
21name, and they are conceptually arranged in a name space hierarchy
22using dots (periods) as separators. For example, a logger named
23"scan" is the parent of loggers "scan.text", "scan.html" and "scan.pdf".
24Logger names can be anything you want, and indicate the area of an
25application in which a logged message originates.
Skip Montanaro649698f2002-11-14 03:57:19 +000026
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000027Logged messages also have levels of importance associated with them.
28The default levels provided are \constant{DEBUG}, \constant{INFO},
29\constant{WARNING}, \constant{ERROR} and \constant{CRITICAL}. As a
30convenience, you indicate the importance of a logged message by calling
31an appropriate method of \class{Logger}. The methods are
Fred Drakec23e0192003-01-28 22:09:16 +000032\method{debug()}, \method{info()}, \method{warning()}, \method{error()} and
33\method{critical()}, which mirror the default levels. You are not
34constrained to use these levels: you can specify your own and use a
35more general \class{Logger} method, \method{log()}, which takes an
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000036explicit level argument.
Skip Montanaro649698f2002-11-14 03:57:19 +000037
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000038Levels can also be associated with loggers, being set either by the
39developer or through loading a saved logging configuration. When a
40logging method is called on a logger, the logger compares its own
41level with the level associated with the method call. If the logger's
42level is higher than the method call's, no logging message is actually
43generated. This is the basic mechanism controlling the verbosity of
44logging output.
Skip Montanaro649698f2002-11-14 03:57:19 +000045
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000046Logging messages are encoded as instances of the \class{LogRecord} class.
47When a logger decides to actually log an event, an \class{LogRecord}
48instance is created from the logging message.
Skip Montanaro649698f2002-11-14 03:57:19 +000049
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000050Logging messages are subjected to a dispatch mechanism through the
51use of \dfn{handlers}, which are instances of subclasses of the
52\class{Handler} class. Handlers are responsible for ensuring that a logged
53message (in the form of a \class{LogRecord}) ends up in a particular
54location (or set of locations) which is useful for the target audience for
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +000055that message (such as end users, support desk staff, system administrators,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000056developers). Handlers are passed \class{LogRecord} instances intended for
57particular destinations. Each logger can have zero, one or more handlers
Fred Drake6b3b0462004-04-09 18:26:40 +000058associated with it (via the \method{addHandler()} method of \class{Logger}).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000059In addition to any handlers directly associated with a logger,
Fred Drakec23e0192003-01-28 22:09:16 +000060\emph{all handlers associated with all ancestors of the logger} are
61called to dispatch the message.
Skip Montanaro649698f2002-11-14 03:57:19 +000062
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000063Just as for loggers, handlers can have levels associated with them.
64A handler's level acts as a filter in the same way as a logger's level does.
Fred Drakec23e0192003-01-28 22:09:16 +000065If a handler decides to actually dispatch an event, the \method{emit()} method
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000066is used to send the message to its destination. Most user-defined subclasses
Fred Drakec23e0192003-01-28 22:09:16 +000067of \class{Handler} will need to override this \method{emit()}.
Skip Montanaro649698f2002-11-14 03:57:19 +000068
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000069In addition to the base \class{Handler} class, many useful subclasses
70are provided:
Skip Montanaro649698f2002-11-14 03:57:19 +000071
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000072\begin{enumerate}
Skip Montanaro649698f2002-11-14 03:57:19 +000073
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000074\item \class{StreamHandler} instances send error messages to
75streams (file-like objects).
Skip Montanaro649698f2002-11-14 03:57:19 +000076
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000077\item \class{FileHandler} instances send error messages to disk
78files.
79
80\item \class{RotatingFileHandler} instances send error messages to disk
81files, with support for maximum log file sizes and log file rotation.
82
83\item \class{SocketHandler} instances send error messages to
84TCP/IP sockets.
85
86\item \class{DatagramHandler} instances send error messages to UDP
87sockets.
88
89\item \class{SMTPHandler} instances send error messages to a
90designated email address.
91
92\item \class{SysLogHandler} instances send error messages to a
Fred Drake68e6d572003-01-28 22:02:35 +000093\UNIX{} syslog daemon, possibly on a remote machine.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000094
95\item \class{NTEventLogHandler} instances send error messages to a
96Windows NT/2000/XP event log.
97
98\item \class{MemoryHandler} instances send error messages to a
99buffer in memory, which is flushed whenever specific criteria are
100met.
101
102\item \class{HTTPHandler} instances send error messages to an
Fred Drake68e6d572003-01-28 22:02:35 +0000103HTTP server using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000104
105\end{enumerate}
106
107The \class{StreamHandler} and \class{FileHandler} classes are defined
108in the core logging package. The other handlers are defined in a sub-
109module, \module{logging.handlers}. (There is also another sub-module,
110\module{logging.config}, for configuration functionality.)
111
112Logged messages are formatted for presentation through instances of the
113\class{Formatter} class. They are initialized with a format string
114suitable for use with the \% operator and a dictionary.
115
116For formatting multiple messages in a batch, instances of
117\class{BufferingFormatter} can be used. In addition to the format string
118(which is applied to each message in the batch), there is provision for
119header and trailer format strings.
120
121When filtering based on logger level and/or handler level is not enough,
122instances of \class{Filter} can be added to both \class{Logger} and
Fred Drakec23e0192003-01-28 22:09:16 +0000123\class{Handler} instances (through their \method{addFilter()} method).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000124Before deciding to process a message further, both loggers and handlers
125consult all their filters for permission. If any filter returns a false
126value, the message is not processed further.
127
128The basic \class{Filter} functionality allows filtering by specific logger
129name. If this feature is used, messages sent to the named logger and its
130children are allowed through the filter, and all others dropped.
131
132In addition to the classes described above, there are a number of module-
133level functions.
134
135\begin{funcdesc}{getLogger}{\optional{name}}
136Return a logger with the specified name or, if no name is specified, return
137a logger which is the root logger of the hierarchy.
138
139All calls to this function with a given name return the same logger instance.
140This means that logger instances never need to be passed between different
141parts of an application.
Skip Montanaro649698f2002-11-14 03:57:19 +0000142\end{funcdesc}
143
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000144\begin{funcdesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
145Logs a message with level \constant{DEBUG} on the root logger.
146The \var{msg} is the message format string, and the \var{args} are the
147arguments which are merged into \var{msg}. The only keyword argument in
148\var{kwargs} which is inspected is \var{exc_info} which, if it does not
149evaluate as false, causes exception information (via a call to
Fred Drakec23e0192003-01-28 22:09:16 +0000150\function{sys.exc_info()}) to be added to the logging message.
Skip Montanaro649698f2002-11-14 03:57:19 +0000151\end{funcdesc}
152
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000153\begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
154Logs a message with level \constant{INFO} on the root logger.
155The arguments are interpreted as for \function{debug()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000156\end{funcdesc}
157
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000158\begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
159Logs a message with level \constant{WARNING} on the root logger.
160The arguments are interpreted as for \function{debug()}.
161\end{funcdesc}
162
163\begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
164Logs a message with level \constant{ERROR} on the root logger.
165The arguments are interpreted as for \function{debug()}.
166\end{funcdesc}
167
168\begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
169Logs a message with level \constant{CRITICAL} on the root logger.
170The arguments are interpreted as for \function{debug()}.
171\end{funcdesc}
172
173\begin{funcdesc}{exception}{msg\optional{, *args}}
174Logs a message with level \constant{ERROR} on the root logger.
175The arguments are interpreted as for \function{debug()}. Exception info
176is added to the logging message. This function should only be called
177from an exception handler.
178\end{funcdesc}
179
180\begin{funcdesc}{disable}{lvl}
181Provides an overriding level \var{lvl} for all loggers which takes
182precedence over the logger's own level. When the need arises to
183temporarily throttle logging output down across the whole application,
184this function can be useful.
185\end{funcdesc}
186
187\begin{funcdesc}{addLevelName}{lvl, levelName}
188Associates level \var{lvl} with text \var{levelName} in an internal
189dictionary, which is used to map numeric levels to a textual
190representation, for example when a \class{Formatter} formats a message.
191This function can also be used to define your own levels. The only
192constraints are that all levels used must be registered using this
193function, levels should be positive integers and they should increase
194in increasing order of severity.
195\end{funcdesc}
196
197\begin{funcdesc}{getLevelName}{lvl}
198Returns the textual representation of logging level \var{lvl}. If the
199level is one of the predefined levels \constant{CRITICAL},
200\constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG}
201then you get the corresponding string. If you have associated levels
202with names using \function{addLevelName()} then the name you have associated
203with \var{lvl} is returned. Otherwise, the string "Level \%s" \% lvl is
204returned.
205\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000206
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000207\begin{funcdesc}{makeLogRecord}{attrdict}
208Creates and returns a new \class{LogRecord} instance whose attributes are
209defined by \var{attrdict}. This function is useful for taking a pickled
210\class{LogRecord} attribute dictionary, sent over a socket, and reconstituting
211it as a \class{LogRecord} instance at the receiving end.
212\end{funcdesc}
213
Skip Montanaro649698f2002-11-14 03:57:19 +0000214\begin{funcdesc}{basicConfig}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000215Does basic configuration for the logging system by creating a
216\class{StreamHandler} with a default \class{Formatter} and adding it to
217the root logger. The functions \function{debug()}, \function{info()},
218\function{warning()}, \function{error()} and \function{critical()} will call
219\function{basicConfig()} automatically if no handlers are defined for the
220root logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000221\end{funcdesc}
222
Skip Montanaro649698f2002-11-14 03:57:19 +0000223\begin{funcdesc}{shutdown}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000224Informs the logging system to perform an orderly shutdown by flushing and
225closing all handlers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000226\end{funcdesc}
227
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000228\begin{funcdesc}{setLoggerClass}{klass}
229Tells the logging system to use the class \var{klass} when instantiating a
230logger. The class should define \method{__init__()} such that only a name
231argument is required, and the \method{__init__()} should call
232\method{Logger.__init__()}. This function is typically called before any
233loggers are instantiated by applications which need to use custom logger
234behavior.
235\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000236
Fred Drake68e6d572003-01-28 22:02:35 +0000237
238\begin{seealso}
239 \seepep{282}{A Logging System}
240 {The proposal which described this feature for inclusion in
241 the Python standard library.}
Fred Drake11514792004-01-08 14:59:02 +0000242 \seelink{http://www.red-dove.com/python_logging.html}
243 {Original Python \module{logging} package}
244 {This is the original source for the \module{logging}
245 package. The version of the package available from this
246 site is suitable for use with Python 2.1.x and 2.2.x, which
247 do not include the \module{logging} package in the standard
248 library.}
Fred Drake68e6d572003-01-28 22:02:35 +0000249\end{seealso}
250
251
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000252\subsection{Logger Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000253
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000254Loggers have the following attributes and methods. Note that Loggers are
255never instantiated directly, but always through the module-level function
256\function{logging.getLogger(name)}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000257
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000258\begin{datadesc}{propagate}
259If this evaluates to false, logging messages are not passed by this
260logger or by child loggers to higher level (ancestor) loggers. The
261constructor sets this attribute to 1.
Skip Montanaro649698f2002-11-14 03:57:19 +0000262\end{datadesc}
263
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000264\begin{methoddesc}{setLevel}{lvl}
265Sets the threshold for this logger to \var{lvl}. Logging messages
266which are less severe than \var{lvl} will be ignored. When a logger is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000267created, the level is set to \constant{NOTSET} (which causes all messages
268to be processed in the root logger, or delegation to the parent in non-root
269loggers).
Skip Montanaro649698f2002-11-14 03:57:19 +0000270\end{methoddesc}
271
272\begin{methoddesc}{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000273Indicates if a message of severity \var{lvl} would be processed by
274this logger. This method checks first the module-level level set by
275\function{logging.disable(lvl)} and then the logger's effective level as
276determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000277\end{methoddesc}
278
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000279\begin{methoddesc}{getEffectiveLevel}{}
280Indicates the effective level for this logger. If a value other than
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000281\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000282Otherwise, the hierarchy is traversed towards the root until a value
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000283other than \constant{NOTSET} is found, and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000284\end{methoddesc}
285
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000286\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
287Logs a message with level \constant{DEBUG} on this logger.
288The \var{msg} is the message format string, and the \var{args} are the
289arguments which are merged into \var{msg}. The only keyword argument in
290\var{kwargs} which is inspected is \var{exc_info} which, if it does not
291evaluate as false, causes exception information (via a call to
Fred Drakec23e0192003-01-28 22:09:16 +0000292\function{sys.exc_info()}) to be added to the logging message.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000293\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000294
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000295\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
296Logs a message with level \constant{INFO} on this logger.
297The arguments are interpreted as for \method{debug()}.
298\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000299
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000300\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
301Logs a message with level \constant{WARNING} on this logger.
302The arguments are interpreted as for \method{debug()}.
303\end{methoddesc}
304
305\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
306Logs a message with level \constant{ERROR} on this logger.
307The arguments are interpreted as for \method{debug()}.
308\end{methoddesc}
309
310\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
311Logs a message with level \constant{CRITICAL} on this logger.
312The arguments are interpreted as for \method{debug()}.
313\end{methoddesc}
314
315\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
316Logs a message with level \var{lvl} on this logger.
317The other arguments are interpreted as for \method{debug()}.
318\end{methoddesc}
319
320\begin{methoddesc}{exception}{msg\optional{, *args}}
321Logs a message with level \constant{ERROR} on this logger.
322The arguments are interpreted as for \method{debug()}. Exception info
323is added to the logging message. This method should only be called
324from an exception handler.
325\end{methoddesc}
326
327\begin{methoddesc}{addFilter}{filt}
328Adds the specified filter \var{filt} to this logger.
329\end{methoddesc}
330
331\begin{methoddesc}{removeFilter}{filt}
332Removes the specified filter \var{filt} from this logger.
333\end{methoddesc}
334
335\begin{methoddesc}{filter}{record}
336Applies this logger's filters to the record and returns a true value if
337the record is to be processed.
338\end{methoddesc}
339
340\begin{methoddesc}{addHandler}{hdlr}
341Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000342\end{methoddesc}
343
344\begin{methoddesc}{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000345Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000346\end{methoddesc}
347
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000348\begin{methoddesc}{findCaller}{}
349Finds the caller's source filename and line number. Returns the filename
350and line number as a 2-element tuple.
Skip Montanaro649698f2002-11-14 03:57:19 +0000351\end{methoddesc}
352
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000353\begin{methoddesc}{handle}{record}
354Handles a record by passing it to all handlers associated with this logger
355and its ancestors (until a false value of \var{propagate} is found).
356This method is used for unpickled records received from a socket, as well
357as those created locally. Logger-level filtering is applied using
358\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000359\end{methoddesc}
360
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000361\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info}
362This is a factory method which can be overridden in subclasses to create
363specialized \class{LogRecord} instances.
Skip Montanaro649698f2002-11-14 03:57:19 +0000364\end{methoddesc}
365
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000366\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000367
Fred Drake68e6d572003-01-28 22:02:35 +0000368Handlers have the following attributes and methods. Note that
369\class{Handler} is never instantiated directly; this class acts as a
370base for more useful subclasses. However, the \method{__init__()}
371method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000372
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000373\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000374Initializes the \class{Handler} instance by setting its level, setting
375the list of filters to the empty list and creating a lock (using
Raymond Hettingerc75c3e02003-09-01 22:50:52 +0000376\method{createLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000377\end{methoddesc}
378
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000379\begin{methoddesc}{createLock}{}
380Initializes a thread lock which can be used to serialize access to
381underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000382\end{methoddesc}
383
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000384\begin{methoddesc}{acquire}{}
385Acquires the thread lock created with \method{createLock()}.
386\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000387
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000388\begin{methoddesc}{release}{}
389Releases the thread lock acquired with \method{acquire()}.
390\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000391
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000392\begin{methoddesc}{setLevel}{lvl}
393Sets the threshold for this handler to \var{lvl}. Logging messages which are
394less severe than \var{lvl} will be ignored. When a handler is created, the
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000395level is set to \constant{NOTSET} (which causes all messages to be processed).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000396\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000397
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000398\begin{methoddesc}{setFormatter}{form}
399Sets the \class{Formatter} for this handler to \var{form}.
400\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000401
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000402\begin{methoddesc}{addFilter}{filt}
403Adds the specified filter \var{filt} to this handler.
404\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000405
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000406\begin{methoddesc}{removeFilter}{filt}
407Removes the specified filter \var{filt} from this handler.
408\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000409
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000410\begin{methoddesc}{filter}{record}
411Applies this handler's filters to the record and returns a true value if
412the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000413\end{methoddesc}
414
415\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000416Ensure all logging output has been flushed. This version does
417nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000418\end{methoddesc}
419
Skip Montanaro649698f2002-11-14 03:57:19 +0000420\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000421Tidy up any resources used by the handler. This version does
422nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000423\end{methoddesc}
424
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000425\begin{methoddesc}{handle}{record}
426Conditionally emits the specified logging record, depending on
427filters which may have been added to the handler. Wraps the actual
428emission of the record with acquisition/release of the I/O thread
429lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000430\end{methoddesc}
431
432\begin{methoddesc}{handleError}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000433This method should be called from handlers when an exception is
434encountered during an emit() call. By default it does nothing,
435which means that exceptions get silently ignored. This is what is
436mostly wanted for a logging system - most users will not care
437about errors in the logging system, they are more interested in
438application errors. You could, however, replace this with a custom
439handler if you wish.
Skip Montanaro649698f2002-11-14 03:57:19 +0000440\end{methoddesc}
441
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000442\begin{methoddesc}{format}{record}
443Do formatting for a record - if a formatter is set, use it.
444Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000445\end{methoddesc}
446
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000447\begin{methoddesc}{emit}{record}
448Do whatever it takes to actually log the specified logging record.
449This version is intended to be implemented by subclasses and so
450raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000451\end{methoddesc}
452
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000453\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000454
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000455The \class{StreamHandler} class sends logging output to streams such as
456\var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more
457precisely, any object which supports \method{write()} and \method{flush()}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000458methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000459
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000460\begin{classdesc}{StreamHandler}{\optional{strm}}
461Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
462specified, the instance will use it for logging output; otherwise,
463\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000464\end{classdesc}
465
466\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000467If a formatter is specified, it is used to format the record.
468The record is then written to the stream with a trailing newline.
469If exception information is present, it is formatted using
470\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000471\end{methoddesc}
472
473\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000474Flushes the stream by calling its \method{flush()} method. Note that
475the \method{close()} method is inherited from \class{Handler} and
476so does nothing, so an explicit \method{flush()} call may be needed
477at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000478\end{methoddesc}
479
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000480\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000481
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000482The \class{FileHandler} class sends logging output to a disk file.
Fred Drake68e6d572003-01-28 22:02:35 +0000483It inherits the output functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000484
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000485\begin{classdesc}{FileHandler}{filename\optional{, mode}}
486Returns a new instance of the \class{FileHandler} class. The specified
487file is opened and used as the stream for logging. If \var{mode} is
Fred Drake9a5b6a62003-07-08 15:38:40 +0000488not specified, \constant{'a'} is used. By default, the file grows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000489indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000490\end{classdesc}
491
492\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000493Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +0000494\end{methoddesc}
495
496\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000497Outputs the record to the file.
498\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000499
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000500\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000501
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000502The \class{RotatingFileHandler} class supports rotation of disk log files.
503
Fred Drake9a5b6a62003-07-08 15:38:40 +0000504\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{,
505 maxBytes\optional{, backupCount}}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000506Returns a new instance of the \class{RotatingFileHandler} class. The
507specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +0000508\var{mode} is not specified, \code{'a'} is used. By default, the
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000509file grows indefinitely.
510
511You can use the \var{maxBytes} and
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000512\var{backupCount} values to allow the file to \dfn{rollover} at a
513predetermined size. When the size is about to be exceeded, the file is
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +0000514closed and a new file is silently opened for output. Rollover occurs
515whenever the current log file is nearly \var{maxBytes} in length; if
516\var{maxBytes} is zero, rollover never occurs. If \var{backupCount}
517is non-zero, the system will save old log files by appending the
518extensions ".1", ".2" etc., to the filename. For example, with
519a \var{backupCount} of 5 and a base file name of
520\file{app.log}, you would get \file{app.log},
521\file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being
522written to is always \file{app.log}. When this file is filled, it is
523closed and renamed to \file{app.log.1}, and if files \file{app.log.1},
524\file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2},
525\file{app.log.3} etc. respectively.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000526\end{classdesc}
527
528\begin{methoddesc}{doRollover}{}
529Does a rollover, as described above.
530\end{methoddesc}
531
532\begin{methoddesc}{emit}{record}
533Outputs the record to the file, catering for rollover as described
534in \method{setRollover()}.
535\end{methoddesc}
536
537\subsubsection{SocketHandler}
538
539The \class{SocketHandler} class sends logging output to a network
540socket. The base class uses a TCP socket.
541
542\begin{classdesc}{SocketHandler}{host, port}
543Returns a new instance of the \class{SocketHandler} class intended to
544communicate with a remote machine whose address is given by \var{host}
545and \var{port}.
546\end{classdesc}
547
548\begin{methoddesc}{close}{}
549Closes the socket.
550\end{methoddesc}
551
552\begin{methoddesc}{handleError}{}
553\end{methoddesc}
554
555\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000556Pickles the record's attribute dictionary and writes it to the socket in
557binary format. If there is an error with the socket, silently drops the
558packet. If the connection was previously lost, re-establishes the connection.
Fred Drake6b3b0462004-04-09 18:26:40 +0000559To unpickle the record at the receiving end into a \class{LogRecord}, use the
560\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000561\end{methoddesc}
562
563\begin{methoddesc}{handleError}{}
564Handles an error which has occurred during \method{emit()}. The
565most likely cause is a lost connection. Closes the socket so that
566we can retry on the next event.
567\end{methoddesc}
568
569\begin{methoddesc}{makeSocket}{}
570This is a factory method which allows subclasses to define the precise
571type of socket they want. The default implementation creates a TCP
572socket (\constant{socket.SOCK_STREAM}).
573\end{methoddesc}
574
575\begin{methoddesc}{makePickle}{record}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000576Pickles the record's attribute dictionary in binary format with a length
577prefix, and returns it ready for transmission across the socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000578\end{methoddesc}
579
580\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000581Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000582for partial sends which can happen when the network is busy.
583\end{methoddesc}
584
585\subsubsection{DatagramHandler}
586
587The \class{DatagramHandler} class inherits from \class{SocketHandler}
588to support sending logging messages over UDP sockets.
589
590\begin{classdesc}{DatagramHandler}{host, port}
591Returns a new instance of the \class{DatagramHandler} class intended to
592communicate with a remote machine whose address is given by \var{host}
593and \var{port}.
594\end{classdesc}
595
596\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000597Pickles the record's attribute dictionary and writes it to the socket in
598binary format. If there is an error with the socket, silently drops the
599packet.
Fred Drake6b3b0462004-04-09 18:26:40 +0000600To unpickle the record at the receiving end into a \class{LogRecord}, use the
601\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000602\end{methoddesc}
603
604\begin{methoddesc}{makeSocket}{}
605The factory method of \class{SocketHandler} is here overridden to create
606a UDP socket (\constant{socket.SOCK_DGRAM}).
607\end{methoddesc}
608
609\begin{methoddesc}{send}{s}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000610Send a pickled string to a socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000611\end{methoddesc}
612
613\subsubsection{SysLogHandler}
614
615The \class{SysLogHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000616remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000617
618\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
619Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +0000620communicate with a remote \UNIX{} machine whose address is given by
621\var{address} in the form of a \code{(\var{host}, \var{port})}
622tuple. If \var{address} is not specified, \code{('localhost', 514)} is
623used. The address is used to open a UDP socket. If \var{facility} is
624not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000625\end{classdesc}
626
627\begin{methoddesc}{close}{}
628Closes the socket to the remote host.
629\end{methoddesc}
630
631\begin{methoddesc}{emit}{record}
632The record is formatted, and then sent to the syslog server. If
633exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +0000634\end{methoddesc}
635
636\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000637Encodes the facility and priority into an integer. You can pass in strings
638or integers - if strings are passed, internal mapping dictionaries are used
639to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000640\end{methoddesc}
641
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000642\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000643
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000644The \class{NTEventLogHandler} class supports sending logging messages
645to a local Windows NT, Windows 2000 or Windows XP event log. Before
646you can use it, you need Mark Hammond's Win32 extensions for Python
647installed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000648
Fred Drake9a5b6a62003-07-08 15:38:40 +0000649\begin{classdesc}{NTEventLogHandler}{appname\optional{,
650 dllname\optional{, logtype}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000651Returns a new instance of the \class{NTEventLogHandler} class. The
652\var{appname} is used to define the application name as it appears in the
653event log. An appropriate registry entry is created using this name.
654The \var{dllname} should give the fully qualified pathname of a .dll or .exe
655which contains message definitions to hold in the log (if not specified,
Fred Drake9a5b6a62003-07-08 15:38:40 +0000656\code{'win32service.pyd'} is used - this is installed with the Win32
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000657extensions and contains some basic placeholder message definitions.
658Note that use of these placeholders will make your event logs big, as the
659entire message source is held in the log. If you want slimmer logs, you have
660to pass in the name of your own .dll or .exe which contains the message
661definitions you want to use in the event log). The \var{logtype} is one of
Fred Drake9a5b6a62003-07-08 15:38:40 +0000662\code{'Application'}, \code{'System'} or \code{'Security'}, and
663defaults to \code{'Application'}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000664\end{classdesc}
665
666\begin{methoddesc}{close}{}
667At this point, you can remove the application name from the registry as a
668source of event log entries. However, if you do this, you will not be able
669to see the events as you intended in the Event Log Viewer - it needs to be
670able to access the registry to get the .dll name. The current version does
671not do this (in fact it doesn't do anything).
672\end{methoddesc}
673
674\begin{methoddesc}{emit}{record}
675Determines the message ID, event category and event type, and then logs the
676message in the NT event log.
677\end{methoddesc}
678
679\begin{methoddesc}{getEventCategory}{record}
680Returns the event category for the record. Override this if you
681want to specify your own categories. This version returns 0.
682\end{methoddesc}
683
684\begin{methoddesc}{getEventType}{record}
685Returns the event type for the record. Override this if you want
686to specify your own types. This version does a mapping using the
687handler's typemap attribute, which is set up in \method{__init__()}
688to a dictionary which contains mappings for \constant{DEBUG},
689\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
690\constant{CRITICAL}. If you are using your own levels, you will either need
691to override this method or place a suitable dictionary in the
692handler's \var{typemap} attribute.
693\end{methoddesc}
694
695\begin{methoddesc}{getMessageID}{record}
696Returns the message ID for the record. If you are using your
697own messages, you could do this by having the \var{msg} passed to the
698logger being an ID rather than a format string. Then, in here,
699you could use a dictionary lookup to get the message ID. This
700version returns 1, which is the base message ID in
Fred Drake9a5b6a62003-07-08 15:38:40 +0000701\file{win32service.pyd}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000702\end{methoddesc}
703
704\subsubsection{SMTPHandler}
705
706The \class{SMTPHandler} class supports sending logging messages to an email
707address via SMTP.
708
709\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
710Returns a new instance of the \class{SMTPHandler} class. The
711instance is initialized with the from and to addresses and subject
712line of the email. The \var{toaddrs} should be a list of strings without
713domain names (That's what the \var{mailhost} is for). To specify a
714non-standard SMTP port, use the (host, port) tuple format for the
715\var{mailhost} argument. If you use a string, the standard SMTP port
716is used.
717\end{classdesc}
718
719\begin{methoddesc}{emit}{record}
720Formats the record and sends it to the specified addressees.
721\end{methoddesc}
722
723\begin{methoddesc}{getSubject}{record}
724If you want to specify a subject line which is record-dependent,
725override this method.
726\end{methoddesc}
727
728\subsubsection{MemoryHandler}
729
730The \class{MemoryHandler} supports buffering of logging records in memory,
731periodically flushing them to a \dfn{target} handler. Flushing occurs
732whenever the buffer is full, or when an event of a certain severity or
733greater is seen.
734
735\class{MemoryHandler} is a subclass of the more general
736\class{BufferingHandler}, which is an abstract class. This buffers logging
737records in memory. Whenever each record is added to the buffer, a
738check is made by calling \method{shouldFlush()} to see if the buffer
739should be flushed. If it should, then \method{flush()} is expected to
740do the needful.
741
742\begin{classdesc}{BufferingHandler}{capacity}
743Initializes the handler with a buffer of the specified capacity.
744\end{classdesc}
745
746\begin{methoddesc}{emit}{record}
747Appends the record to the buffer. If \method{shouldFlush()} returns true,
748calls \method{flush()} to process the buffer.
749\end{methoddesc}
750
751\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000752You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000753just zaps the buffer to empty.
754\end{methoddesc}
755
756\begin{methoddesc}{shouldFlush}{record}
757Returns true if the buffer is up to capacity. This method can be
758overridden to implement custom flushing strategies.
759\end{methoddesc}
760
761\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000762\optional{, target}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000763Returns a new instance of the \class{MemoryHandler} class. The
764instance is initialized with a buffer size of \var{capacity}. If
765\var{flushLevel} is not specified, \constant{ERROR} is used. If no
766\var{target} is specified, the target will need to be set using
767\method{setTarget()} before this handler does anything useful.
768\end{classdesc}
769
770\begin{methoddesc}{close}{}
771Calls \method{flush()}, sets the target to \constant{None} and
772clears the buffer.
773\end{methoddesc}
774
775\begin{methoddesc}{flush}{}
776For a \class{MemoryHandler}, flushing means just sending the buffered
777records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000778different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000779\end{methoddesc}
780
781\begin{methoddesc}{setTarget}{target}
782Sets the target handler for this handler.
783\end{methoddesc}
784
785\begin{methoddesc}{shouldFlush}{record}
786Checks for buffer full or a record at the \var{flushLevel} or higher.
787\end{methoddesc}
788
789\subsubsection{HTTPHandler}
790
791The \class{HTTPHandler} class supports sending logging messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000792Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000793
794\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
795Returns a new instance of the \class{HTTPHandler} class. The
796instance is initialized with a host address, url and HTTP method.
Fred Drake68e6d572003-01-28 22:02:35 +0000797If no \var{method} is specified, \samp{GET} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000798\end{classdesc}
799
800\begin{methoddesc}{emit}{record}
801Sends the record to the Web server as an URL-encoded dictionary.
802\end{methoddesc}
803
804\subsection{Formatter Objects}
805
806\class{Formatter}s have the following attributes and methods. They are
807responsible for converting a \class{LogRecord} to (usually) a string
808which can be interpreted by either a human or an external system. The
809base
810\class{Formatter} allows a formatting string to be specified. If none is
Fred Drake8efc74d2004-04-15 06:18:48 +0000811supplied, the default value of \code{'\%(message)s'} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000812
813A Formatter can be initialized with a format string which makes use of
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000814knowledge of the \class{LogRecord} attributes - such as the default value
815mentioned above making use of the fact that the user's message and
Fred Drake6b3b0462004-04-09 18:26:40 +0000816arguments are pre-formatted into a \class{LogRecord}'s \var{message}
Anthony Baxtera6b7d342003-07-08 08:40:20 +0000817attribute. This format string contains standard python \%-style
818mapping keys. See section \ref{typesseq-strings}, ``String Formatting
819Operations,'' for more information on string formatting.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000820
Fred Drake6b3b0462004-04-09 18:26:40 +0000821Currently, the useful mapping keys in a \class{LogRecord} are:
Anthony Baxtera6b7d342003-07-08 08:40:20 +0000822
Fred Drake9a5b6a62003-07-08 15:38:40 +0000823\begin{tableii}{l|l}{code}{Format}{Description}
824\lineii{\%(name)s} {Name of the logger (logging channel).}
825\lineii{\%(levelno)s} {Numeric logging level for the message
826 (\constant{DEBUG}, \constant{INFO},
827 \constant{WARNING}, \constant{ERROR},
828 \constant{CRITICAL}).}
829\lineii{\%(levelname)s}{Text logging level for the message
830 (\code{'DEBUG'}, \code{'INFO'},
831 \code{'WARNING'}, \code{'ERROR'},
832 \code{'CRITICAL'}).}
833\lineii{\%(pathname)s} {Full pathname of the source file where the logging
834 call was issued (if available).}
835\lineii{\%(filename)s} {Filename portion of pathname.}
836\lineii{\%(module)s} {Module (name portion of filename).}
837\lineii{\%(lineno)d} {Source line number where the logging call was issued
838 (if available).}
Fred Drake6b3b0462004-04-09 18:26:40 +0000839\lineii{\%(created)f} {Time when the \class{LogRecord} was created (as
Fred Drake9a5b6a62003-07-08 15:38:40 +0000840 returned by \function{time.time()}).}
Fred Drake6b3b0462004-04-09 18:26:40 +0000841\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
842 was created. By default this is of the form
Fred Drake9a5b6a62003-07-08 15:38:40 +0000843 ``2003-07-08 16:49:45,896'' (the numbers after the
844 comma are millisecond portion of the time).}
845\lineii{\%(msecs)d} {Millisecond portion of the time when the
846 \class{LogRecord} was created.}
847\lineii{\%(thread)d} {Thread ID (if available).}
848\lineii{\%(process)d} {Process ID (if available).}
849\lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}
Anthony Baxtera6b7d342003-07-08 08:40:20 +0000850\end{tableii}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000851
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000852\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
853Returns a new instance of the \class{Formatter} class. The
854instance is initialized with a format string for the message as a whole,
855as well as a format string for the date/time portion of a message. If
Neal Norwitzdd3afa72003-07-08 16:26:34 +0000856no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000857is specified, the ISO8601 date format is used.
858\end{classdesc}
859
860\begin{methoddesc}{format}{record}
861The record's attribute dictionary is used as the operand to a
862string formatting operation. Returns the resulting string.
863Before formatting the dictionary, a couple of preparatory steps
864are carried out. The \var{message} attribute of the record is computed
865using \var{msg} \% \var{args}. If the formatting string contains
Fred Drake9a5b6a62003-07-08 15:38:40 +0000866\code{'(asctime)'}, \method{formatTime()} is called to format the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000867event time. If there is exception information, it is formatted using
868\method{formatException()} and appended to the message.
869\end{methoddesc}
870
871\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
872This method should be called from \method{format()} by a formatter which
873wants to make use of a formatted time. This method can be overridden
874in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +0000875basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +0000876it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000877record. Otherwise, the ISO8601 format is used. The resulting
878string is returned.
879\end{methoddesc}
880
881\begin{methoddesc}{formatException}{exc_info}
882Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +0000883as returned by \function{sys.exc_info()}) as a string. This default
884implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000885The resulting string is returned.
886\end{methoddesc}
887
888\subsection{Filter Objects}
889
890\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
891more sophisticated filtering than is provided by levels. The base filter
892class only allows events which are below a certain point in the logger
893hierarchy. For example, a filter initialized with "A.B" will allow events
894logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
895"B.A.B" etc. If initialized with the empty string, all events are passed.
896
897\begin{classdesc}{Filter}{\optional{name}}
898Returns an instance of the \class{Filter} class. If \var{name} is specified,
899it names a logger which, together with its children, will have its events
900allowed through the filter. If no name is specified, allows every event.
901\end{classdesc}
902
903\begin{methoddesc}{filter}{record}
904Is the specified record to be logged? Returns zero for no, nonzero for
905yes. If deemed appropriate, the record may be modified in-place by this
906method.
907\end{methoddesc}
908
909\subsection{LogRecord Objects}
910
Fred Drake6b3b0462004-04-09 18:26:40 +0000911\class{LogRecord} instances are created every time something is logged. They
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000912contain all the information pertinent to the event being logged. The
913main information passed in is in msg and args, which are combined
914using msg \% args to create the message field of the record. The record
915also includes information such as when the record was created, the
916source line where the logging call was made, and any exception
917information to be logged.
918
Fred Drake6b3b0462004-04-09 18:26:40 +0000919\class{LogRecord} has no methods; it's just a repository for
920information about the logging event. The only reason it's a class
921rather than a dictionary is to facilitate extension.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000922
923\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
Fred Drake9a5b6a62003-07-08 15:38:40 +0000924 exc_info}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000925Returns an instance of \class{LogRecord} initialized with interesting
926information. The \var{name} is the logger name; \var{lvl} is the
927numeric level; \var{pathname} is the absolute pathname of the source
928file in which the logging call was made; \var{lineno} is the line
929number in that file where the logging call is found; \var{msg} is the
930user-supplied message (a format string); \var{args} is the tuple
931which, together with \var{msg}, makes up the user message; and
932\var{exc_info} is the exception tuple obtained by calling
933\function{sys.exc_info() }(or \constant{None}, if no exception information
934is available).
935\end{classdesc}
936
937\subsection{Thread Safety}
938
939The logging module is intended to be thread-safe without any special work
940needing to be done by its clients. It achieves this though using threading
941locks; there is one lock to serialize access to the module's shared data,
942and each handler also creates a lock to serialize access to its underlying
943I/O.
944
945\subsection{Configuration}
946
947
Fred Drake94ffbb72004-04-08 19:44:31 +0000948\subsubsection{Configuration functions%
949 \label{logging-config-api}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000950
Fred Drake9a5b6a62003-07-08 15:38:40 +0000951The following functions allow the logging module to be
952configured. Before they can be used, you must import
953\module{logging.config}. Their use is optional --- you can configure
954the logging module entirely by making calls to the main API (defined
955in \module{logging} itself) and defining handlers which are declared
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000956either in \module{logging} or \module{logging.handlers}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000957
958\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
959Reads the logging configuration from a ConfigParser-format file named
960\var{fname}. This function can be called several times from an application,
961allowing an end user the ability to select from various pre-canned
962configurations (if the developer provides a mechanism to present the
963choices and load the chosen configuration). Defaults to be passed to
964ConfigParser can be specified in the \var{defaults} argument.
965\end{funcdesc}
966
967\begin{funcdesc}{listen}{\optional{port}}
968Starts up a socket server on the specified port, and listens for new
969configurations. If no port is specified, the module's default
970\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
971will be sent as a file suitable for processing by \function{fileConfig()}.
972Returns a \class{Thread} instance on which you can call \method{start()}
973to start the server, and which you can \method{join()} when appropriate.
974To stop the server, call \function{stopListening()}.
975\end{funcdesc}
976
977\begin{funcdesc}{stopListening}{}
978Stops the listening server which was created with a call to
979\function{listen()}. This is typically called before calling \method{join()}
980on the return value from \function{listen()}.
981\end{funcdesc}
982
Fred Drake94ffbb72004-04-08 19:44:31 +0000983\subsubsection{Configuration file format%
984 \label{logging-config-fileformat}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000985
Fred Drake6b3b0462004-04-09 18:26:40 +0000986The configuration file format understood by \function{fileConfig()} is
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000987based on ConfigParser functionality. The file must contain sections
988called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
989which identify by name the entities of each type which are defined in
990the file. For each such entity, there is a separate section which
991identified how that entity is configured. Thus, for a logger named
992\code{log01} in the \code{[loggers]} section, the relevant
993configuration details are held in a section
994\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
995the \code{[handlers]} section will have its configuration held in a
996section called \code{[handler_hand01]}, while a formatter called
997\code{form01} in the \code{[formatters]} section will have its
998configuration specified in a section called
999\code{[formatter_form01]}. The root logger configuration must be
1000specified in a section called \code{[logger_root]}.
1001
1002Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001003
1004\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001005[loggers]
1006keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +00001007
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001008[handlers]
1009keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1010
1011[formatters]
1012keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +00001013\end{verbatim}
1014
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001015The root logger must specify a level and a list of handlers. An
1016example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001017
1018\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001019[logger_root]
1020level=NOTSET
1021handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +00001022\end{verbatim}
1023
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001024The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1025ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1026\code{NOTSET} means that all messages will be logged. Level values are
1027\function{eval()}uated in the context of the \code{logging} package's
1028namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +00001029
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001030The \code{handlers} entry is a comma-separated list of handler names,
1031which must appear in the \code{[handlers]} section. These names must
1032appear in the \code{[handlers]} section and have corresponding
1033sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +00001034
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001035For loggers other than the root logger, some additional information is
1036required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +00001037
1038\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001039[logger_parser]
1040level=DEBUG
1041handlers=hand01
1042propagate=1
1043qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001044\end{verbatim}
1045
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001046The \code{level} and \code{handlers} entries are interpreted as for
1047the root logger, except that if a non-root logger's level is specified
1048as \code{NOTSET}, the system consults loggers higher up the hierarchy
1049to determine the effective level of the logger. The \code{propagate}
1050entry is set to 1 to indicate that messages must propagate to handlers
1051higher up the logger hierarchy from this logger, or 0 to indicate that
1052messages are \strong{not} propagated to handlers up the hierarchy. The
1053\code{qualname} entry is the hierarchical channel name of the logger,
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001054for example, the name used by the application to get the logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001055
1056Sections which specify handler configuration are exemplified by the
1057following.
1058
Skip Montanaro649698f2002-11-14 03:57:19 +00001059\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001060[handler_hand01]
1061class=StreamHandler
1062level=NOTSET
1063formatter=form01
1064args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001065\end{verbatim}
1066
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001067The \code{class} entry indicates the handler's class (as determined by
1068\function{eval()} in the \code{logging} package's namespace). The
1069\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1070to mean "log everything".
1071
1072The \code{formatter} entry indicates the key name of the formatter for
1073this handler. If blank, a default formatter
1074(\code{logging._defaultFormatter}) is used. If a name is specified, it
1075must appear in the \code{[formatters]} section and have a
1076corresponding section in the configuration file.
1077
1078The \code{args} entry, when \function{eval()}uated in the context of
1079the \code{logging} package's namespace, is the list of arguments to
1080the constructor for the handler class. Refer to the constructors for
1081the relevant handlers, or to the examples below, to see how typical
1082entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001083
1084\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001085[handler_hand02]
1086class=FileHandler
1087level=DEBUG
1088formatter=form02
1089args=('python.log', 'w')
1090
1091[handler_hand03]
1092class=handlers.SocketHandler
1093level=INFO
1094formatter=form03
1095args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1096
1097[handler_hand04]
1098class=handlers.DatagramHandler
1099level=WARN
1100formatter=form04
1101args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1102
1103[handler_hand05]
1104class=handlers.SysLogHandler
1105level=ERROR
1106formatter=form05
1107args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1108
1109[handler_hand06]
1110class=NTEventLogHandler
1111level=CRITICAL
1112formatter=form06
1113args=('Python Application', '', 'Application')
1114
1115[handler_hand07]
1116class=SMTPHandler
1117level=WARN
1118formatter=form07
1119args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1120
1121[handler_hand08]
1122class=MemoryHandler
1123level=NOTSET
1124formatter=form08
1125target=
1126args=(10, ERROR)
1127
1128[handler_hand09]
1129class=HTTPHandler
1130level=NOTSET
1131formatter=form09
1132args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001133\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001134
1135Sections which specify formatter configuration are typified by the following.
1136
1137\begin{verbatim}
1138[formatter_form01]
1139format=F1 %(asctime)s %(levelname)s %(message)s
1140datefmt=
1141\end{verbatim}
1142
1143The \code{format} entry is the overall format string, and the
1144\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1145string. If empty, the package substitutes ISO8601 format date/times, which
1146is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1147The ISO8601 format also specifies milliseconds, which are appended to the
1148result of using the above format string, with a comma separator. An example
1149time in ISO8601 format is \code{2003-01-23 00:29:50,411}.
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001150
1151\subsection{Using the logging package}
1152
1153\subsubsection{Basic example - log to a file}
1154
1155Here's a simple logging example that just logs to a file. In order,
1156it creates a \class{Logger} instance, then a \class{FileHandler}
1157and a \class{Formatter}. It attaches the \class{Formatter} to the
1158\class{FileHandler}, then the \class{FileHandler} to the \class{Logger}.
1159Finally, it sets a debug level for the logger.
1160
1161\begin{verbatim}
1162import logging
1163logger = logging.getLogger('myapp')
1164hdlr = logging.FileHandler('/var/tmp/myapp.log')
1165formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
1166hdlr.setFormatter(formatter)
1167logger.addHandler(hdlr)
1168logger.setLevel(logging.WARNING)
1169\end{verbatim}
1170
1171We can use this logger object now to write entries to the log file:
1172
1173\begin{verbatim}
1174logger.error('We have a problem')
1175logger.info('While this is just chatty')
1176\end{verbatim}
1177
1178If we look in the file that was created, we'll see something like this:
1179\begin{verbatim}
11802003-07-08 16:49:45,896 ERROR We have a problem
1181\end{verbatim}
1182
Fred Drake6b3b0462004-04-09 18:26:40 +00001183The info message was not written to the file: we called the
1184\method{setLevel()} method to say we only wanted \constant{WARNING} or
1185worse, so the info message is discarded.
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001186
1187The timestamp is of the form
1188``year-month-day hour:minutes:seconds,milliseconds.''
1189Note that despite the three digits of precision in the milliseconds field,
1190not all systems provide time with this much precision.
1191