blob: dabab53b60cebc492d8cbd1982d2d044a8f1de74 [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
Vinay Sajipe8fdc452004-12-02 21:27:42 +000038The numeric values of logging levels are given in the following table. These
39are primarily of interest if you want to define your own levels, and need
40them to have specific values relative to the predefined levels. If you
41define a level with the same numeric value, it overwrites the predefined
42value; the predefined name is lost.
43
44\begin{tableii}{l|l}{code}{Level}{Numeric value}
45 \lineii{CRITICAL}{50}
46 \lineii{ERROR}{40}
47 \lineii{WARNING}{30}
48 \lineii{INFO}{20}
49 \lineii{DEBUG}{10}
50 \lineii{NOTSET}{0}
51\end{tableii}
52
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000053Levels can also be associated with loggers, being set either by the
54developer or through loading a saved logging configuration. When a
55logging method is called on a logger, the logger compares its own
56level with the level associated with the method call. If the logger's
57level is higher than the method call's, no logging message is actually
58generated. This is the basic mechanism controlling the verbosity of
59logging output.
Skip Montanaro649698f2002-11-14 03:57:19 +000060
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000061Logging messages are encoded as instances of the \class{LogRecord} class.
Georg Brandl0f194232006-01-01 21:35:20 +000062When a logger decides to actually log an event, a \class{LogRecord}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000063instance is created from the logging message.
Skip Montanaro649698f2002-11-14 03:57:19 +000064
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000065Logging messages are subjected to a dispatch mechanism through the
66use of \dfn{handlers}, which are instances of subclasses of the
67\class{Handler} class. Handlers are responsible for ensuring that a logged
68message (in the form of a \class{LogRecord}) ends up in a particular
69location (or set of locations) which is useful for the target audience for
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +000070that message (such as end users, support desk staff, system administrators,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000071developers). Handlers are passed \class{LogRecord} instances intended for
72particular destinations. Each logger can have zero, one or more handlers
Fred Drake6b3b0462004-04-09 18:26:40 +000073associated with it (via the \method{addHandler()} method of \class{Logger}).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000074In addition to any handlers directly associated with a logger,
Fred Drakec23e0192003-01-28 22:09:16 +000075\emph{all handlers associated with all ancestors of the logger} are
76called to dispatch the message.
Skip Montanaro649698f2002-11-14 03:57:19 +000077
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000078Just as for loggers, handlers can have levels associated with them.
79A handler's level acts as a filter in the same way as a logger's level does.
Fred Drakec23e0192003-01-28 22:09:16 +000080If a handler decides to actually dispatch an event, the \method{emit()} method
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000081is used to send the message to its destination. Most user-defined subclasses
Fred Drakec23e0192003-01-28 22:09:16 +000082of \class{Handler} will need to override this \method{emit()}.
Skip Montanaro649698f2002-11-14 03:57:19 +000083
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000084In addition to the base \class{Handler} class, many useful subclasses
85are provided:
Skip Montanaro649698f2002-11-14 03:57:19 +000086
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000087\begin{enumerate}
Skip Montanaro649698f2002-11-14 03:57:19 +000088
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000089\item \class{StreamHandler} instances send error messages to
90streams (file-like objects).
Skip Montanaro649698f2002-11-14 03:57:19 +000091
Neal Norwitzcd5c8c22003-01-25 21:29:41 +000092\item \class{FileHandler} instances send error messages to disk
93files.
94
Andrew M. Kuchlinge0245142005-08-18 21:45:31 +000095\item \class{BaseRotatingHandler} is the base class for handlers that
Johannes Gijsbersf1643222004-11-07 16:11:35 +000096rotate log files at a certain point. It is not meant to be instantiated
Vinay Sajipedde4922004-11-11 13:54:48 +000097directly. Instead, use \class{RotatingFileHandler} or
98\class{TimedRotatingFileHandler}.
Johannes Gijsbersf1643222004-11-07 16:11:35 +000099
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000100\item \class{RotatingFileHandler} instances send error messages to disk
101files, with support for maximum log file sizes and log file rotation.
102
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +0000103\item \class{TimedRotatingFileHandler} instances send error messages to
104disk files rotating the log file at certain timed intervals.
105
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000106\item \class{SocketHandler} instances send error messages to
107TCP/IP sockets.
108
109\item \class{DatagramHandler} instances send error messages to UDP
110sockets.
111
112\item \class{SMTPHandler} instances send error messages to a
113designated email address.
114
115\item \class{SysLogHandler} instances send error messages to a
Fred Drake68e6d572003-01-28 22:02:35 +0000116\UNIX{} syslog daemon, possibly on a remote machine.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000117
118\item \class{NTEventLogHandler} instances send error messages to a
119Windows NT/2000/XP event log.
120
121\item \class{MemoryHandler} instances send error messages to a
122buffer in memory, which is flushed whenever specific criteria are
123met.
124
125\item \class{HTTPHandler} instances send error messages to an
Fred Drake68e6d572003-01-28 22:02:35 +0000126HTTP server using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000127
128\end{enumerate}
129
130The \class{StreamHandler} and \class{FileHandler} classes are defined
131in the core logging package. The other handlers are defined in a sub-
132module, \module{logging.handlers}. (There is also another sub-module,
133\module{logging.config}, for configuration functionality.)
134
135Logged messages are formatted for presentation through instances of the
136\class{Formatter} class. They are initialized with a format string
137suitable for use with the \% operator and a dictionary.
138
139For formatting multiple messages in a batch, instances of
140\class{BufferingFormatter} can be used. In addition to the format string
141(which is applied to each message in the batch), there is provision for
142header and trailer format strings.
143
144When filtering based on logger level and/or handler level is not enough,
145instances of \class{Filter} can be added to both \class{Logger} and
Fred Drakec23e0192003-01-28 22:09:16 +0000146\class{Handler} instances (through their \method{addFilter()} method).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000147Before deciding to process a message further, both loggers and handlers
148consult all their filters for permission. If any filter returns a false
149value, the message is not processed further.
150
151The basic \class{Filter} functionality allows filtering by specific logger
152name. If this feature is used, messages sent to the named logger and its
153children are allowed through the filter, and all others dropped.
154
155In addition to the classes described above, there are a number of module-
156level functions.
157
158\begin{funcdesc}{getLogger}{\optional{name}}
159Return a logger with the specified name or, if no name is specified, return
Vinay Sajip17952b72004-08-31 10:21:51 +0000160a logger which is the root logger of the hierarchy. If specified, the name
161is typically a dot-separated hierarchical name like \var{"a"}, \var{"a.b"}
162or \var{"a.b.c.d"}. Choice of these names is entirely up to the developer
163who is using logging.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000164
165All calls to this function with a given name return the same logger instance.
166This means that logger instances never need to be passed between different
167parts of an application.
Skip Montanaro649698f2002-11-14 03:57:19 +0000168\end{funcdesc}
169
Vinay Sajipc6646c02004-09-22 12:55:16 +0000170\begin{funcdesc}{getLoggerClass}{}
171Return either the standard \class{Logger} class, or the last class passed to
172\function{setLoggerClass()}. This function may be called from within a new
173class definition, to ensure that installing a customised \class{Logger} class
174will not undo customisations already applied by other code. For example:
175
176\begin{verbatim}
177 class MyLogger(logging.getLoggerClass()):
178 # ... override behaviour here
179\end{verbatim}
180
181\end{funcdesc}
182
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000183\begin{funcdesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
184Logs a message with level \constant{DEBUG} on the root logger.
185The \var{msg} is the message format string, and the \var{args} are the
Vinay Sajipb4549c42006-02-09 08:54:11 +0000186arguments which are merged into \var{msg} using the string formatting
187operator. (Note that this means that you can use keywords in the
188format string, together with a single dictionary argument.)
189
190There are two keyword arguments in \var{kwargs} which are inspected:
191\var{exc_info} which, if it does not evaluate as false, causes exception
192information to be added to the logging message. If an exception tuple (in the
193format returned by \function{sys.exc_info()}) is provided, it is used;
194otherwise, \function{sys.exc_info()} is called to get the exception
195information.
196
197The other optional keyword argument is \var{extra} which can be used to pass
198a dictionary which is used to populate the __dict__ of the LogRecord created
199for the logging event with user-defined attributes. These custom attributes
200can then be used as you like. For example, they could be incorporated into
201logged messages. For example:
202
203\begin{verbatim}
204 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
205 logging.basicConfig(format=FORMAT)
206 dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
207 logging.warning("Protocol problem: %s", "connection reset", extra=d)
208\end{verbatim}
209
210would print something like
211\begin{verbatim}
2122006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
213\end{verbatim}
214
215The keys in the dictionary passed in \var{extra} should not clash with the keys
216used by the logging system. (See the \class{Formatter} documentation for more
217information on which keys are used by the logging system.)
218
219If you choose to use these attributes in logged messages, you need to exercise
220some care. In the above example, for instance, the \class{Formatter} has been
221set up with a format string which expects 'clientip' and 'user' in the
222attribute dictionary of the LogRecord. If these are missing, the message will
223not be logged because a string formatting exception will occur. So in this
224case, you always need to pass the \var{extra} dictionary with these keys.
225
226While this might be annoying, this feature is intended for use in specialized
227circumstances, such as multi-threaded servers where the same code executes
228in many contexts, and interesting conditions which arise are dependent on this
229context (such as remote client IP address and authenticated user name, in the
230above example). In such circumstances, it is likely that specialized
231\class{Formatter}s would be used with particular \class{Handler}s.
Vinay Sajip55aafab2006-02-15 21:47:32 +0000232
233\versionchanged[\var{extra} was added]{2.5}
234
Skip Montanaro649698f2002-11-14 03:57:19 +0000235\end{funcdesc}
236
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000237\begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
238Logs a message with level \constant{INFO} on the root logger.
239The arguments are interpreted as for \function{debug()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000240\end{funcdesc}
241
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000242\begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
243Logs a message with level \constant{WARNING} on the root logger.
244The arguments are interpreted as for \function{debug()}.
245\end{funcdesc}
246
247\begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
248Logs a message with level \constant{ERROR} on the root logger.
249The arguments are interpreted as for \function{debug()}.
250\end{funcdesc}
251
252\begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
253Logs a message with level \constant{CRITICAL} on the root logger.
254The arguments are interpreted as for \function{debug()}.
255\end{funcdesc}
256
257\begin{funcdesc}{exception}{msg\optional{, *args}}
258Logs a message with level \constant{ERROR} on the root logger.
259The arguments are interpreted as for \function{debug()}. Exception info
260is added to the logging message. This function should only be called
261from an exception handler.
262\end{funcdesc}
263
Vinay Sajip739d49e2004-09-24 11:46:44 +0000264\begin{funcdesc}{log}{level, msg\optional{, *args\optional{, **kwargs}}}
265Logs a message with level \var{level} on the root logger.
266The other arguments are interpreted as for \function{debug()}.
267\end{funcdesc}
268
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000269\begin{funcdesc}{disable}{lvl}
270Provides an overriding level \var{lvl} for all loggers which takes
271precedence over the logger's own level. When the need arises to
272temporarily throttle logging output down across the whole application,
273this function can be useful.
274\end{funcdesc}
275
276\begin{funcdesc}{addLevelName}{lvl, levelName}
277Associates level \var{lvl} with text \var{levelName} in an internal
278dictionary, which is used to map numeric levels to a textual
279representation, for example when a \class{Formatter} formats a message.
280This function can also be used to define your own levels. The only
281constraints are that all levels used must be registered using this
282function, levels should be positive integers and they should increase
283in increasing order of severity.
284\end{funcdesc}
285
286\begin{funcdesc}{getLevelName}{lvl}
287Returns the textual representation of logging level \var{lvl}. If the
288level is one of the predefined levels \constant{CRITICAL},
289\constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG}
290then you get the corresponding string. If you have associated levels
291with names using \function{addLevelName()} then the name you have associated
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000292with \var{lvl} is returned. If a numeric value corresponding to one of the
293defined levels is passed in, the corresponding string representation is
294returned. Otherwise, the string "Level \%s" \% lvl is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000295\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000296
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000297\begin{funcdesc}{makeLogRecord}{attrdict}
298Creates and returns a new \class{LogRecord} instance whose attributes are
299defined by \var{attrdict}. This function is useful for taking a pickled
300\class{LogRecord} attribute dictionary, sent over a socket, and reconstituting
301it as a \class{LogRecord} instance at the receiving end.
302\end{funcdesc}
303
Vinay Sajipc320c222005-07-29 11:52:19 +0000304\begin{funcdesc}{basicConfig}{\optional{**kwargs}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000305Does basic configuration for the logging system by creating a
306\class{StreamHandler} with a default \class{Formatter} and adding it to
307the root logger. The functions \function{debug()}, \function{info()},
308\function{warning()}, \function{error()} and \function{critical()} will call
309\function{basicConfig()} automatically if no handlers are defined for the
310root logger.
Vinay Sajipc320c222005-07-29 11:52:19 +0000311
312\versionchanged[Formerly, \function{basicConfig} did not take any keyword
313arguments]{2.4}
314
315The following keyword arguments are supported.
316
317\begin{tableii}{l|l}{code}{Format}{Description}
318\lineii{filename}{Specifies that a FileHandler be created, using the
319specified filename, rather than a StreamHandler.}
320\lineii{filemode}{Specifies the mode to open the file, if filename is
321specified (if filemode is unspecified, it defaults to 'a').}
322\lineii{format}{Use the specified format string for the handler.}
323\lineii{datefmt}{Use the specified date/time format.}
324\lineii{level}{Set the root logger level to the specified level.}
325\lineii{stream}{Use the specified stream to initialize the StreamHandler.
326Note that this argument is incompatible with 'filename' - if both
327are present, 'stream' is ignored.}
328\end{tableii}
329
Skip Montanaro649698f2002-11-14 03:57:19 +0000330\end{funcdesc}
331
Skip Montanaro649698f2002-11-14 03:57:19 +0000332\begin{funcdesc}{shutdown}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000333Informs the logging system to perform an orderly shutdown by flushing and
334closing all handlers.
Skip Montanaro649698f2002-11-14 03:57:19 +0000335\end{funcdesc}
336
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000337\begin{funcdesc}{setLoggerClass}{klass}
338Tells the logging system to use the class \var{klass} when instantiating a
339logger. The class should define \method{__init__()} such that only a name
340argument is required, and the \method{__init__()} should call
341\method{Logger.__init__()}. This function is typically called before any
342loggers are instantiated by applications which need to use custom logger
343behavior.
344\end{funcdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000345
Fred Drake68e6d572003-01-28 22:02:35 +0000346
347\begin{seealso}
348 \seepep{282}{A Logging System}
349 {The proposal which described this feature for inclusion in
350 the Python standard library.}
Fred Drake11514792004-01-08 14:59:02 +0000351 \seelink{http://www.red-dove.com/python_logging.html}
352 {Original Python \module{logging} package}
353 {This is the original source for the \module{logging}
354 package. The version of the package available from this
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000355 site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x,
356 which do not include the \module{logging} package in the standard
Fred Drake11514792004-01-08 14:59:02 +0000357 library.}
Fred Drake68e6d572003-01-28 22:02:35 +0000358\end{seealso}
359
360
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000361\subsection{Logger Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000362
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000363Loggers have the following attributes and methods. Note that Loggers are
364never instantiated directly, but always through the module-level function
365\function{logging.getLogger(name)}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000366
Guido van Rossumd8faa362007-04-27 19:54:29 +0000367\begin{memberdesc}[Logger]{propagate}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000368If this evaluates to false, logging messages are not passed by this
369logger or by child loggers to higher level (ancestor) loggers. The
370constructor sets this attribute to 1.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000371\end{memberdesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000372
Guido van Rossumd8faa362007-04-27 19:54:29 +0000373\begin{methoddesc}[Logger]{setLevel}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000374Sets the threshold for this logger to \var{lvl}. Logging messages
375which are less severe than \var{lvl} will be ignored. When a logger is
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000376created, the level is set to \constant{NOTSET} (which causes all messages
Vinay Sajipe8fdc452004-12-02 21:27:42 +0000377to be processed when the logger is the root logger, or delegation to the
378parent when the logger is a non-root logger). Note that the root logger
379is created with level \constant{WARNING}.
Vinay Sajipd1c02392005-09-26 00:14:46 +0000380
381The term "delegation to the parent" means that if a logger has a level
382of NOTSET, its chain of ancestor loggers is traversed until either an
383ancestor with a level other than NOTSET is found, or the root is
384reached.
385
386If an ancestor is found with a level other than NOTSET, then that
387ancestor's level is treated as the effective level of the logger where
388the ancestor search began, and is used to determine how a logging
389event is handled.
390
391If the root is reached, and it has a level of NOTSET, then all
392messages will be processed. Otherwise, the root's level will be used
393as the effective level.
Skip Montanaro649698f2002-11-14 03:57:19 +0000394\end{methoddesc}
395
Guido van Rossumd8faa362007-04-27 19:54:29 +0000396\begin{methoddesc}[Logger]{isEnabledFor}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000397Indicates if a message of severity \var{lvl} would be processed by
398this logger. This method checks first the module-level level set by
399\function{logging.disable(lvl)} and then the logger's effective level as
400determined by \method{getEffectiveLevel()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000401\end{methoddesc}
402
Guido van Rossumd8faa362007-04-27 19:54:29 +0000403\begin{methoddesc}[Logger]{getEffectiveLevel}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000404Indicates the effective level for this logger. If a value other than
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000405\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000406Otherwise, the hierarchy is traversed towards the root until a value
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +0000407other than \constant{NOTSET} is found, and that value is returned.
Skip Montanaro649698f2002-11-14 03:57:19 +0000408\end{methoddesc}
409
Guido van Rossumd8faa362007-04-27 19:54:29 +0000410\begin{methoddesc}[Logger]{debug}{msg\optional{, *args\optional{, **kwargs}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000411Logs a message with level \constant{DEBUG} on this logger.
412The \var{msg} is the message format string, and the \var{args} are the
Vinay Sajipb4549c42006-02-09 08:54:11 +0000413arguments which are merged into \var{msg} using the string formatting
414operator. (Note that this means that you can use keywords in the
415format string, together with a single dictionary argument.)
416
417There are two keyword arguments in \var{kwargs} which are inspected:
418\var{exc_info} which, if it does not evaluate as false, causes exception
419information to be added to the logging message. If an exception tuple (in the
420format returned by \function{sys.exc_info()}) is provided, it is used;
421otherwise, \function{sys.exc_info()} is called to get the exception
422information.
423
424The other optional keyword argument is \var{extra} which can be used to pass
425a dictionary which is used to populate the __dict__ of the LogRecord created
426for the logging event with user-defined attributes. These custom attributes
427can then be used as you like. For example, they could be incorporated into
428logged messages. For example:
429
430\begin{verbatim}
431 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
432 logging.basicConfig(format=FORMAT)
433 dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
434 logger = logging.getLogger("tcpserver")
435 logger.warning("Protocol problem: %s", "connection reset", extra=d)
436\end{verbatim}
437
438would print something like
439\begin{verbatim}
4402006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
441\end{verbatim}
442
443The keys in the dictionary passed in \var{extra} should not clash with the keys
444used by the logging system. (See the \class{Formatter} documentation for more
445information on which keys are used by the logging system.)
446
447If you choose to use these attributes in logged messages, you need to exercise
448some care. In the above example, for instance, the \class{Formatter} has been
449set up with a format string which expects 'clientip' and 'user' in the
450attribute dictionary of the LogRecord. If these are missing, the message will
451not be logged because a string formatting exception will occur. So in this
452case, you always need to pass the \var{extra} dictionary with these keys.
453
454While this might be annoying, this feature is intended for use in specialized
455circumstances, such as multi-threaded servers where the same code executes
456in many contexts, and interesting conditions which arise are dependent on this
457context (such as remote client IP address and authenticated user name, in the
458above example). In such circumstances, it is likely that specialized
459\class{Formatter}s would be used with particular \class{Handler}s.
Vinay Sajip55aafab2006-02-15 21:47:32 +0000460
461\versionchanged[\var{extra} was added]{2.5}
462
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000463\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000464
Guido van Rossumd8faa362007-04-27 19:54:29 +0000465\begin{methoddesc}[Logger]{info}{msg\optional{, *args\optional{, **kwargs}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000466Logs a message with level \constant{INFO} on this logger.
467The arguments are interpreted as for \method{debug()}.
468\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000469
Guido van Rossumd8faa362007-04-27 19:54:29 +0000470\begin{methoddesc}[Logger]{warning}{msg\optional{, *args\optional{, **kwargs}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000471Logs a message with level \constant{WARNING} on this logger.
472The arguments are interpreted as for \method{debug()}.
473\end{methoddesc}
474
Guido van Rossumd8faa362007-04-27 19:54:29 +0000475\begin{methoddesc}[Logger]{error}{msg\optional{, *args\optional{, **kwargs}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000476Logs a message with level \constant{ERROR} on this logger.
477The arguments are interpreted as for \method{debug()}.
478\end{methoddesc}
479
Guido van Rossumd8faa362007-04-27 19:54:29 +0000480\begin{methoddesc}[Logger]{critical}{msg\optional{, *args\optional{, **kwargs}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000481Logs a message with level \constant{CRITICAL} on this logger.
482The arguments are interpreted as for \method{debug()}.
483\end{methoddesc}
484
Guido van Rossumd8faa362007-04-27 19:54:29 +0000485\begin{methoddesc}[Logger]{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
Vinay Sajip1cf56d02004-08-04 08:36:44 +0000486Logs a message with integer level \var{lvl} on this logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000487The other arguments are interpreted as for \method{debug()}.
488\end{methoddesc}
489
Guido van Rossumd8faa362007-04-27 19:54:29 +0000490\begin{methoddesc}[Logger]{exception}{msg\optional{, *args}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000491Logs a message with level \constant{ERROR} on this logger.
492The arguments are interpreted as for \method{debug()}. Exception info
493is added to the logging message. This method should only be called
494from an exception handler.
495\end{methoddesc}
496
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497\begin{methoddesc}[Logger]{addFilter}{filt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000498Adds the specified filter \var{filt} to this logger.
499\end{methoddesc}
500
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501\begin{methoddesc}[Logger]{removeFilter}{filt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000502Removes the specified filter \var{filt} from this logger.
503\end{methoddesc}
504
Guido van Rossumd8faa362007-04-27 19:54:29 +0000505\begin{methoddesc}[Logger]{filter}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000506Applies this logger's filters to the record and returns a true value if
507the record is to be processed.
508\end{methoddesc}
509
Guido van Rossumd8faa362007-04-27 19:54:29 +0000510\begin{methoddesc}[Logger]{addHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000511Adds the specified handler \var{hdlr} to this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000512\end{methoddesc}
513
Guido van Rossumd8faa362007-04-27 19:54:29 +0000514\begin{methoddesc}[Logger]{removeHandler}{hdlr}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000515Removes the specified handler \var{hdlr} from this logger.
Skip Montanaro649698f2002-11-14 03:57:19 +0000516\end{methoddesc}
517
Guido van Rossumd8faa362007-04-27 19:54:29 +0000518\begin{methoddesc}[Logger]{findCaller}{}
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000519Finds the caller's source filename and line number. Returns the filename,
520line number and function name as a 3-element tuple.
521\versionchanged[The function name was added. In earlier versions, the
522filename and line number were returned as a 2-element tuple.]{2.5}
Skip Montanaro649698f2002-11-14 03:57:19 +0000523\end{methoddesc}
524
Guido van Rossumd8faa362007-04-27 19:54:29 +0000525\begin{methoddesc}[Logger]{handle}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000526Handles a record by passing it to all handlers associated with this logger
527and its ancestors (until a false value of \var{propagate} is found).
528This method is used for unpickled records received from a socket, as well
529as those created locally. Logger-level filtering is applied using
530\method{filter()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000531\end{methoddesc}
532
Guido van Rossumd8faa362007-04-27 19:54:29 +0000533\begin{methoddesc}[Logger]{makeRecord}{name, lvl, fn, lno, msg, args, exc_info
534 \optional{, func, extra}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000535This is a factory method which can be overridden in subclasses to create
536specialized \class{LogRecord} instances.
Neal Norwitzc16dd482006-02-13 02:04:37 +0000537\versionchanged[\var{func} and \var{extra} were added]{2.5}
Skip Montanaro649698f2002-11-14 03:57:19 +0000538\end{methoddesc}
539
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000540\subsection{Basic example \label{minimal-example}}
541
Vinay Sajipc320c222005-07-29 11:52:19 +0000542\versionchanged[formerly \function{basicConfig} did not take any keyword
543arguments]{2.4}
544
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000545The \module{logging} package provides a lot of flexibility, and its
546configuration can appear daunting. This section demonstrates that simple
547use of the logging package is possible.
548
549The simplest example shows logging to the console:
550
551\begin{verbatim}
552import logging
553
554logging.debug('A debug message')
555logging.info('Some information')
556logging.warning('A shot across the bows')
557\end{verbatim}
558
559If you run the above script, you'll see this:
560\begin{verbatim}
561WARNING:root:A shot across the bows
562\end{verbatim}
563
564Because no particular logger was specified, the system used the root logger.
565The debug and info messages didn't appear because by default, the root
566logger is configured to only handle messages with a severity of WARNING
567or above. The message format is also a configuration default, as is the output
568destination of the messages - \code{sys.stderr}. The severity level,
569the message format and destination can be easily changed, as shown in
570the example below:
571
572\begin{verbatim}
573import logging
574
575logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000576 format='%(asctime)s %(levelname)s %(message)s',
577 filename='/tmp/myapp.log',
578 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000579logging.debug('A debug message')
580logging.info('Some information')
581logging.warning('A shot across the bows')
582\end{verbatim}
583
584The \method{basicConfig()} method is used to change the configuration
585defaults, which results in output (written to \code{/tmp/myapp.log})
586which should look something like the following:
587
588\begin{verbatim}
5892004-07-02 13:00:08,743 DEBUG A debug message
5902004-07-02 13:00:08,743 INFO Some information
5912004-07-02 13:00:08,743 WARNING A shot across the bows
592\end{verbatim}
593
594This time, all messages with a severity of DEBUG or above were handled,
595and the format of the messages was also changed, and output went to the
596specified file rather than the console.
597
598Formatting uses standard Python string formatting - see section
599\ref{typesseq-strings}. The format string takes the following
600common specifiers. For a complete list of specifiers, consult the
601\class{Formatter} documentation.
602
603\begin{tableii}{l|l}{code}{Format}{Description}
604\lineii{\%(name)s} {Name of the logger (logging channel).}
605\lineii{\%(levelname)s}{Text logging level for the message
606 (\code{'DEBUG'}, \code{'INFO'},
607 \code{'WARNING'}, \code{'ERROR'},
608 \code{'CRITICAL'}).}
609\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
610 was created. By default this is of the form
611 ``2003-07-08 16:49:45,896'' (the numbers after the
612 comma are millisecond portion of the time).}
613\lineii{\%(message)s} {The logged message.}
614\end{tableii}
615
616To change the date/time format, you can pass an additional keyword parameter,
617\var{datefmt}, as in the following:
618
619\begin{verbatim}
620import logging
621
622logging.basicConfig(level=logging.DEBUG,
Vinay Sajipe3c330b2004-07-07 15:59:49 +0000623 format='%(asctime)s %(levelname)-8s %(message)s',
624 datefmt='%a, %d %b %Y %H:%M:%S',
625 filename='/temp/myapp.log',
626 filemode='w')
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000627logging.debug('A debug message')
628logging.info('Some information')
629logging.warning('A shot across the bows')
630\end{verbatim}
631
632which would result in output like
633
634\begin{verbatim}
635Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
636Fri, 02 Jul 2004 13:06:18 INFO Some information
637Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
638\end{verbatim}
639
640The date format string follows the requirements of \function{strftime()} -
641see the documentation for the \refmodule{time} module.
642
643If, instead of sending logging output to the console or a file, you'd rather
644use a file-like object which you have created separately, you can pass it
645to \function{basicConfig()} using the \var{stream} keyword argument. Note
646that if both \var{stream} and \var{filename} keyword arguments are passed,
647the \var{stream} argument is ignored.
648
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000649Of course, you can put variable information in your output. To do this,
650simply have the message be a format string and pass in additional arguments
651containing the variable information, as in the following example:
652
653\begin{verbatim}
654import logging
655
656logging.basicConfig(level=logging.DEBUG,
657 format='%(asctime)s %(levelname)-8s %(message)s',
658 datefmt='%a, %d %b %Y %H:%M:%S',
659 filename='/temp/myapp.log',
660 filemode='w')
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000661logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000662\end{verbatim}
663
664which would result in
665
666\begin{verbatim}
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000667Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
Vinay Sajipb4bf62f2004-07-21 14:40:11 +0000668\end{verbatim}
669
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000670\subsection{Logging to multiple destinations \label{multiple-destinations}}
671
672Let's say you want to log to console and file with different message formats
673and in differing circumstances. Say you want to log messages with levels
674of DEBUG and higher to file, and those messages at level INFO and higher to
675the console. Let's also assume that the file should contain timestamps, but
676the console messages should not. Here's how you can achieve this:
677
678\begin{verbatim}
679import logging
680
Fred Drake048840c2004-10-29 14:35:42 +0000681# set up logging to file - see previous section for more details
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000682logging.basicConfig(level=logging.DEBUG,
683 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
684 datefmt='%m-%d %H:%M',
685 filename='/temp/myapp.log',
686 filemode='w')
Fred Drake048840c2004-10-29 14:35:42 +0000687# define a Handler which writes INFO messages or higher to the sys.stderr
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000688console = logging.StreamHandler()
689console.setLevel(logging.INFO)
Fred Drake048840c2004-10-29 14:35:42 +0000690# set a format which is simpler for console use
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000691formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Fred Drake048840c2004-10-29 14:35:42 +0000692# tell the handler to use this format
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000693console.setFormatter(formatter)
Fred Drake048840c2004-10-29 14:35:42 +0000694# add the handler to the root logger
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000695logging.getLogger('').addHandler(console)
696
Fred Drake048840c2004-10-29 14:35:42 +0000697# Now, we can log to the root logger, or any other logger. First the root...
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000698logging.info('Jackdaws love my big sphinx of quartz.')
699
Fred Drake048840c2004-10-29 14:35:42 +0000700# Now, define a couple of other loggers which might represent areas in your
701# application:
Vinay Sajip93ae4c12004-10-22 21:43:15 +0000702
703logger1 = logging.getLogger('myapp.area1')
704logger2 = logging.getLogger('myapp.area2')
705
706logger1.debug('Quick zephyrs blow, vexing daft Jim.')
707logger1.info('How quickly daft jumping zebras vex.')
708logger2.warning('Jail zesty vixen who grabbed pay from quack.')
709logger2.error('The five boxing wizards jump quickly.')
710\end{verbatim}
711
712When you run this, on the console you will see
713
714\begin{verbatim}
715root : INFO Jackdaws love my big sphinx of quartz.
716myapp.area1 : INFO How quickly daft jumping zebras vex.
717myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
718myapp.area2 : ERROR The five boxing wizards jump quickly.
719\end{verbatim}
720
721and in the file you will see something like
722
723\begin{verbatim}
72410-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
72510-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
72610-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
72710-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
72810-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
729\end{verbatim}
730
731As you can see, the DEBUG message only shows up in the file. The other
732messages are sent to both destinations.
733
Vinay Sajip006483b2004-10-29 12:30:28 +0000734This example uses console and file handlers, but you can use any number and
735combination of handlers you choose.
736
737\subsection{Sending and receiving logging events across a network
738\label{network-logging}}
739
740Let's say you want to send logging events across a network, and handle them
741at the receiving end. A simple way of doing this is attaching a
742\class{SocketHandler} instance to the root logger at the sending end:
743
744\begin{verbatim}
745import logging, logging.handlers
746
747rootLogger = logging.getLogger('')
748rootLogger.setLevel(logging.DEBUG)
749socketHandler = logging.handlers.SocketHandler('localhost',
750 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
751# don't bother with a formatter, since a socket handler sends the event as
752# an unformatted pickle
753rootLogger.addHandler(socketHandler)
754
Fred Drake048840c2004-10-29 14:35:42 +0000755# Now, we can log to the root logger, or any other logger. First the root...
Vinay Sajip006483b2004-10-29 12:30:28 +0000756logging.info('Jackdaws love my big sphinx of quartz.')
757
Fred Drake048840c2004-10-29 14:35:42 +0000758# Now, define a couple of other loggers which might represent areas in your
759# application:
Vinay Sajip006483b2004-10-29 12:30:28 +0000760
761logger1 = logging.getLogger('myapp.area1')
762logger2 = logging.getLogger('myapp.area2')
763
764logger1.debug('Quick zephyrs blow, vexing daft Jim.')
765logger1.info('How quickly daft jumping zebras vex.')
766logger2.warning('Jail zesty vixen who grabbed pay from quack.')
767logger2.error('The five boxing wizards jump quickly.')
768\end{verbatim}
769
770At the receiving end, you can set up a receiver using the
771\module{SocketServer} module. Here is a basic working example:
772
773\begin{verbatim}
Fred Drake048840c2004-10-29 14:35:42 +0000774import cPickle
775import logging
776import logging.handlers
777import SocketServer
778import struct
Vinay Sajip006483b2004-10-29 12:30:28 +0000779
Vinay Sajip006483b2004-10-29 12:30:28 +0000780
Fred Drake048840c2004-10-29 14:35:42 +0000781class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
782 """Handler for a streaming logging request.
783
784 This basically logs the record using whatever logging policy is
785 configured locally.
Vinay Sajip006483b2004-10-29 12:30:28 +0000786 """
787
788 def handle(self):
789 """
790 Handle multiple requests - each expected to be a 4-byte length,
791 followed by the LogRecord in pickle format. Logs the record
792 according to whatever policy is configured locally.
793 """
794 while 1:
795 chunk = self.connection.recv(4)
796 if len(chunk) < 4:
797 break
798 slen = struct.unpack(">L", chunk)[0]
799 chunk = self.connection.recv(slen)
800 while len(chunk) < slen:
801 chunk = chunk + self.connection.recv(slen - len(chunk))
802 obj = self.unPickle(chunk)
803 record = logging.makeLogRecord(obj)
804 self.handleLogRecord(record)
805
806 def unPickle(self, data):
807 return cPickle.loads(data)
808
809 def handleLogRecord(self, record):
Fred Drake048840c2004-10-29 14:35:42 +0000810 # if a name is specified, we use the named logger rather than the one
811 # implied by the record.
Vinay Sajip006483b2004-10-29 12:30:28 +0000812 if self.server.logname is not None:
813 name = self.server.logname
814 else:
815 name = record.name
816 logger = logging.getLogger(name)
Fred Drake048840c2004-10-29 14:35:42 +0000817 # N.B. EVERY record gets logged. This is because Logger.handle
818 # is normally called AFTER logger-level filtering. If you want
819 # to do filtering, do it at the client end to save wasting
820 # cycles and network bandwidth!
Vinay Sajip006483b2004-10-29 12:30:28 +0000821 logger.handle(record)
822
Fred Drake048840c2004-10-29 14:35:42 +0000823class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
824 """simple TCP socket-based logging receiver suitable for testing.
Vinay Sajip006483b2004-10-29 12:30:28 +0000825 """
826
827 allow_reuse_address = 1
828
829 def __init__(self, host='localhost',
Fred Drake048840c2004-10-29 14:35:42 +0000830 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
831 handler=LogRecordStreamHandler):
832 SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
Vinay Sajip006483b2004-10-29 12:30:28 +0000833 self.abort = 0
834 self.timeout = 1
835 self.logname = None
836
837 def serve_until_stopped(self):
838 import select
839 abort = 0
840 while not abort:
841 rd, wr, ex = select.select([self.socket.fileno()],
842 [], [],
843 self.timeout)
844 if rd:
845 self.handle_request()
846 abort = self.abort
847
848def main():
849 logging.basicConfig(
Vinay Sajipedde4922004-11-11 13:54:48 +0000850 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
Vinay Sajip006483b2004-10-29 12:30:28 +0000851 tcpserver = LogRecordSocketReceiver()
852 print "About to start TCP server..."
853 tcpserver.serve_until_stopped()
854
855if __name__ == "__main__":
856 main()
857\end{verbatim}
858
Vinay Sajipedde4922004-11-11 13:54:48 +0000859First run the server, and then the client. On the client side, nothing is
860printed on the console; on the server side, you should see something like:
Vinay Sajip006483b2004-10-29 12:30:28 +0000861
862\begin{verbatim}
863About to start TCP server...
864 59 root INFO Jackdaws love my big sphinx of quartz.
865 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
866 69 myapp.area1 INFO How quickly daft jumping zebras vex.
867 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
868 69 myapp.area2 ERROR The five boxing wizards jump quickly.
869\end{verbatim}
870
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000871\subsection{Handler Objects}
Skip Montanaro649698f2002-11-14 03:57:19 +0000872
Fred Drake68e6d572003-01-28 22:02:35 +0000873Handlers have the following attributes and methods. Note that
874\class{Handler} is never instantiated directly; this class acts as a
875base for more useful subclasses. However, the \method{__init__()}
876method in subclasses needs to call \method{Handler.__init__()}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000877
Guido van Rossumd8faa362007-04-27 19:54:29 +0000878\begin{methoddesc}[Handler]{__init__}{level=\constant{NOTSET}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000879Initializes the \class{Handler} instance by setting its level, setting
880the list of filters to the empty list and creating a lock (using
Raymond Hettingerc75c3e02003-09-01 22:50:52 +0000881\method{createLock()}) for serializing access to an I/O mechanism.
Skip Montanaro649698f2002-11-14 03:57:19 +0000882\end{methoddesc}
883
Guido van Rossumd8faa362007-04-27 19:54:29 +0000884\begin{methoddesc}[Handler]{createLock}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000885Initializes a thread lock which can be used to serialize access to
886underlying I/O functionality which may not be threadsafe.
Skip Montanaro649698f2002-11-14 03:57:19 +0000887\end{methoddesc}
888
Guido van Rossumd8faa362007-04-27 19:54:29 +0000889\begin{methoddesc}[Handler]{acquire}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000890Acquires the thread lock created with \method{createLock()}.
891\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000892
Guido van Rossumd8faa362007-04-27 19:54:29 +0000893\begin{methoddesc}[Handler]{release}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000894Releases the thread lock acquired with \method{acquire()}.
895\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000896
Guido van Rossumd8faa362007-04-27 19:54:29 +0000897\begin{methoddesc}[Handler]{setLevel}{lvl}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000898Sets the threshold for this handler to \var{lvl}. Logging messages which are
899less severe than \var{lvl} will be ignored. When a handler is created, the
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000900level is set to \constant{NOTSET} (which causes all messages to be processed).
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000901\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000902
Guido van Rossumd8faa362007-04-27 19:54:29 +0000903\begin{methoddesc}[Handler]{setFormatter}{form}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000904Sets the \class{Formatter} for this handler to \var{form}.
905\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000906
Guido van Rossumd8faa362007-04-27 19:54:29 +0000907\begin{methoddesc}[Handler]{addFilter}{filt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000908Adds the specified filter \var{filt} to this handler.
909\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000910
Guido van Rossumd8faa362007-04-27 19:54:29 +0000911\begin{methoddesc}[Handler]{removeFilter}{filt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000912Removes the specified filter \var{filt} from this handler.
913\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +0000914
Guido van Rossumd8faa362007-04-27 19:54:29 +0000915\begin{methoddesc}[Handler]{filter}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000916Applies this handler's filters to the record and returns a true value if
917the record is to be processed.
Skip Montanaro649698f2002-11-14 03:57:19 +0000918\end{methoddesc}
919
Guido van Rossumd8faa362007-04-27 19:54:29 +0000920\begin{methoddesc}[Handler]{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000921Ensure all logging output has been flushed. This version does
922nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000923\end{methoddesc}
924
Guido van Rossumd8faa362007-04-27 19:54:29 +0000925\begin{methoddesc}[Handler]{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000926Tidy up any resources used by the handler. This version does
927nothing and is intended to be implemented by subclasses.
Skip Montanaro649698f2002-11-14 03:57:19 +0000928\end{methoddesc}
929
Guido van Rossumd8faa362007-04-27 19:54:29 +0000930\begin{methoddesc}[Handler]{handle}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000931Conditionally emits the specified logging record, depending on
932filters which may have been added to the handler. Wraps the actual
933emission of the record with acquisition/release of the I/O thread
934lock.
Skip Montanaro649698f2002-11-14 03:57:19 +0000935\end{methoddesc}
936
Guido van Rossumd8faa362007-04-27 19:54:29 +0000937\begin{methoddesc}[Handler]{handleError}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000938This method should be called from handlers when an exception is
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000939encountered during an \method{emit()} call. By default it does nothing,
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000940which means that exceptions get silently ignored. This is what is
941mostly wanted for a logging system - most users will not care
942about errors in the logging system, they are more interested in
943application errors. You could, however, replace this with a custom
Vinay Sajipa13c60b2004-07-03 11:45:53 +0000944handler if you wish. The specified record is the one which was being
945processed when the exception occurred.
Skip Montanaro649698f2002-11-14 03:57:19 +0000946\end{methoddesc}
947
Guido van Rossumd8faa362007-04-27 19:54:29 +0000948\begin{methoddesc}[Handler]{format}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000949Do formatting for a record - if a formatter is set, use it.
950Otherwise, use the default formatter for the module.
Skip Montanaro649698f2002-11-14 03:57:19 +0000951\end{methoddesc}
952
Guido van Rossumd8faa362007-04-27 19:54:29 +0000953\begin{methoddesc}[Handler]{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000954Do whatever it takes to actually log the specified logging record.
955This version is intended to be implemented by subclasses and so
956raises a \exception{NotImplementedError}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000957\end{methoddesc}
958
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000959\subsubsection{StreamHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000960
Vinay Sajip51f52352006-01-22 11:58:39 +0000961The \class{StreamHandler} class, located in the core \module{logging}
962package, sends logging output to streams such as \var{sys.stdout},
963\var{sys.stderr} or any file-like object (or, more precisely, any
964object which supports \method{write()} and \method{flush()} methods).
Skip Montanaro649698f2002-11-14 03:57:19 +0000965
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000966\begin{classdesc}{StreamHandler}{\optional{strm}}
967Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
968specified, the instance will use it for logging output; otherwise,
969\var{sys.stderr} will be used.
Skip Montanaro649698f2002-11-14 03:57:19 +0000970\end{classdesc}
971
972\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000973If a formatter is specified, it is used to format the record.
974The record is then written to the stream with a trailing newline.
975If exception information is present, it is formatted using
976\function{traceback.print_exception()} and appended to the stream.
Skip Montanaro649698f2002-11-14 03:57:19 +0000977\end{methoddesc}
978
979\begin{methoddesc}{flush}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000980Flushes the stream by calling its \method{flush()} method. Note that
981the \method{close()} method is inherited from \class{Handler} and
982so does nothing, so an explicit \method{flush()} call may be needed
983at times.
Skip Montanaro649698f2002-11-14 03:57:19 +0000984\end{methoddesc}
985
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000986\subsubsection{FileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +0000987
Vinay Sajip51f52352006-01-22 11:58:39 +0000988The \class{FileHandler} class, located in the core \module{logging}
989package, sends logging output to a disk file. It inherits the output
990functionality from \class{StreamHandler}.
Skip Montanaro649698f2002-11-14 03:57:19 +0000991
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000992\begin{classdesc}{FileHandler}{filename\optional{, mode\optional{, encoding}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000993Returns a new instance of the \class{FileHandler} class. The specified
994file is opened and used as the stream for logging. If \var{mode} is
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000995not specified, \constant{'a'} is used. If \var{encoding} is not \var{None},
996it is used to open the file with that encoding. By default, the file grows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +0000997indefinitely.
Skip Montanaro649698f2002-11-14 03:57:19 +0000998\end{classdesc}
999
1000\begin{methoddesc}{close}{}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001001Closes the file.
Skip Montanaro649698f2002-11-14 03:57:19 +00001002\end{methoddesc}
1003
1004\begin{methoddesc}{emit}{record}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001005Outputs the record to the file.
1006\end{methoddesc}
Skip Montanaro649698f2002-11-14 03:57:19 +00001007
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001008\subsubsection{WatchedFileHandler}
1009
1010\versionadded{2.6}
1011The \class{WatchedFileHandler} class, located in the \module{logging.handlers}
1012module, is a \class{FileHandler} which watches the file it is logging to.
1013If the file changes, it is closed and reopened using the file name.
1014
1015A file change can happen because of usage of programs such as \var{newsyslog}
1016and \var{logrotate} which perform log file rotation. This handler, intended
1017for use under Unix/Linux, watches the file to see if it has changed since the
1018last emit. (A file is deemed to have changed if its device or inode have
1019changed.) If the file has changed, the old file stream is closed, and the file
1020opened to get a new stream.
1021
1022This handler is not appropriate for use under Windows, because under Windows
1023open log files cannot be moved or renamed - logging opens the files with
1024exclusive locks - and so there is no need for such a handler. Furthermore,
1025\var{ST_INO} is not supported under Windows; \function{stat()} always returns
1026zero for this value.
1027
1028\begin{classdesc}{WatchedFileHandler}{filename\optional{,mode\optional{,
1029 encoding}}}
1030Returns a new instance of the \class{WatchedFileHandler} class. The specified
1031file is opened and used as the stream for logging. If \var{mode} is
1032not specified, \constant{'a'} is used. If \var{encoding} is not \var{None},
1033it is used to open the file with that encoding. By default, the file grows
1034indefinitely.
1035\end{classdesc}
1036
1037\begin{methoddesc}{emit}{record}
1038Outputs the record to the file, but first checks to see if the file has
1039changed. If it has, the existing stream is flushed and closed and the file
1040opened again, before outputting the record to the file.
1041\end{methoddesc}
1042
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001043\subsubsection{RotatingFileHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +00001044
Vinay Sajip51f52352006-01-22 11:58:39 +00001045The \class{RotatingFileHandler} class, located in the \module{logging.handlers}
1046module, supports rotation of disk log files.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001047
Fred Drake9a5b6a62003-07-08 15:38:40 +00001048\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{,
1049 maxBytes\optional{, backupCount}}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001050Returns a new instance of the \class{RotatingFileHandler} class. The
1051specified file is opened and used as the stream for logging. If
Fred Drake68e6d572003-01-28 22:02:35 +00001052\var{mode} is not specified, \code{'a'} is used. By default, the
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001053file grows indefinitely.
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +00001054
1055You can use the \var{maxBytes} and
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001056\var{backupCount} values to allow the file to \dfn{rollover} at a
1057predetermined size. When the size is about to be exceeded, the file is
Andrew M. Kuchling7cf4d9b2003-09-26 13:45:18 +00001058closed and a new file is silently opened for output. Rollover occurs
1059whenever the current log file is nearly \var{maxBytes} in length; if
1060\var{maxBytes} is zero, rollover never occurs. If \var{backupCount}
1061is non-zero, the system will save old log files by appending the
1062extensions ".1", ".2" etc., to the filename. For example, with
1063a \var{backupCount} of 5 and a base file name of
1064\file{app.log}, you would get \file{app.log},
1065\file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being
1066written to is always \file{app.log}. When this file is filled, it is
1067closed and renamed to \file{app.log.1}, and if files \file{app.log.1},
1068\file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2},
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001069\file{app.log.3} etc. respectively.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001070\end{classdesc}
1071
1072\begin{methoddesc}{doRollover}{}
1073Does a rollover, as described above.
1074\end{methoddesc}
1075
1076\begin{methoddesc}{emit}{record}
Johannes Gijsbersf1643222004-11-07 16:11:35 +00001077Outputs the record to the file, catering for rollover as described previously.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001078\end{methoddesc}
1079
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +00001080\subsubsection{TimedRotatingFileHandler}
1081
Vinay Sajip51f52352006-01-22 11:58:39 +00001082The \class{TimedRotatingFileHandler} class, located in the
1083\module{logging.handlers} module, supports rotation of disk log files
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +00001084at certain timed intervals.
1085
1086\begin{classdesc}{TimedRotatingFileHandler}{filename
1087 \optional{,when
1088 \optional{,interval
1089 \optional{,backupCount}}}}
1090
1091Returns a new instance of the \class{TimedRotatingFileHandler} class. The
1092specified file is opened and used as the stream for logging. On rotating
1093it also sets the filename suffix. Rotating happens based on the product
Vinay Sajipedde4922004-11-11 13:54:48 +00001094of \var{when} and \var{interval}.
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +00001095
1096You can use the \var{when} to specify the type of \var{interval}. The
1097list of possible values is, note that they are not case sensitive:
1098
1099\begin{tableii}{l|l}{}{Value}{Type of interval}
1100 \lineii{S}{Seconds}
1101 \lineii{M}{Minutes}
1102 \lineii{H}{Hours}
1103 \lineii{D}{Days}
1104 \lineii{W}{Week day (0=Monday)}
1105 \lineii{midnight}{Roll over at midnight}
1106\end{tableii}
1107
1108If \var{backupCount} is non-zero, the system will save old log files by
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001109appending extensions to the filename. The extensions are date-and-time
1110based, using the strftime format \code{\%Y-\%m-\%d_\%H-\%M-\%S} or a leading
1111portion thereof, depending on the rollover interval. At most \var{backupCount}
1112files will be kept, and if more would be created when rollover occurs, the
1113oldest one is deleted.
Johannes Gijsbers4f802ac2004-11-07 14:14:27 +00001114\end{classdesc}
1115
1116\begin{methoddesc}{doRollover}{}
1117Does a rollover, as described above.
1118\end{methoddesc}
1119
1120\begin{methoddesc}{emit}{record}
1121Outputs the record to the file, catering for rollover as described
1122above.
1123\end{methoddesc}
1124
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001125\subsubsection{SocketHandler}
1126
Vinay Sajip51f52352006-01-22 11:58:39 +00001127The \class{SocketHandler} class, located in the
1128\module{logging.handlers} module, sends logging output to a network
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001129socket. The base class uses a TCP socket.
1130
1131\begin{classdesc}{SocketHandler}{host, port}
1132Returns a new instance of the \class{SocketHandler} class intended to
1133communicate with a remote machine whose address is given by \var{host}
1134and \var{port}.
1135\end{classdesc}
1136
1137\begin{methoddesc}{close}{}
1138Closes the socket.
1139\end{methoddesc}
1140
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001141\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001142Pickles the record's attribute dictionary and writes it to the socket in
1143binary format. If there is an error with the socket, silently drops the
1144packet. If the connection was previously lost, re-establishes the connection.
Fred Drake6b3b0462004-04-09 18:26:40 +00001145To unpickle the record at the receiving end into a \class{LogRecord}, use the
1146\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001147\end{methoddesc}
1148
1149\begin{methoddesc}{handleError}{}
1150Handles an error which has occurred during \method{emit()}. The
1151most likely cause is a lost connection. Closes the socket so that
1152we can retry on the next event.
1153\end{methoddesc}
1154
1155\begin{methoddesc}{makeSocket}{}
1156This is a factory method which allows subclasses to define the precise
1157type of socket they want. The default implementation creates a TCP
1158socket (\constant{socket.SOCK_STREAM}).
1159\end{methoddesc}
1160
1161\begin{methoddesc}{makePickle}{record}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001162Pickles the record's attribute dictionary in binary format with a length
1163prefix, and returns it ready for transmission across the socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001164\end{methoddesc}
1165
1166\begin{methoddesc}{send}{packet}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001167Send a pickled string \var{packet} to the socket. This function allows
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001168for partial sends which can happen when the network is busy.
1169\end{methoddesc}
1170
1171\subsubsection{DatagramHandler}
1172
Vinay Sajip51f52352006-01-22 11:58:39 +00001173The \class{DatagramHandler} class, located in the
1174\module{logging.handlers} module, inherits from \class{SocketHandler}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001175to support sending logging messages over UDP sockets.
1176
1177\begin{classdesc}{DatagramHandler}{host, port}
1178Returns a new instance of the \class{DatagramHandler} class intended to
1179communicate with a remote machine whose address is given by \var{host}
1180and \var{port}.
1181\end{classdesc}
1182
1183\begin{methoddesc}{emit}{}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001184Pickles the record's attribute dictionary and writes it to the socket in
1185binary format. If there is an error with the socket, silently drops the
1186packet.
Fred Drake6b3b0462004-04-09 18:26:40 +00001187To unpickle the record at the receiving end into a \class{LogRecord}, use the
1188\function{makeLogRecord()} function.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001189\end{methoddesc}
1190
1191\begin{methoddesc}{makeSocket}{}
1192The factory method of \class{SocketHandler} is here overridden to create
1193a UDP socket (\constant{socket.SOCK_DGRAM}).
1194\end{methoddesc}
1195
1196\begin{methoddesc}{send}{s}
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001197Send a pickled string to a socket.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001198\end{methoddesc}
1199
1200\subsubsection{SysLogHandler}
1201
Vinay Sajip51f52352006-01-22 11:58:39 +00001202The \class{SysLogHandler} class, located in the
1203\module{logging.handlers} module, supports sending logging messages to
1204a remote or local \UNIX{} syslog.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001205
1206\begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
1207Returns a new instance of the \class{SysLogHandler} class intended to
Fred Drake68e6d572003-01-28 22:02:35 +00001208communicate with a remote \UNIX{} machine whose address is given by
1209\var{address} in the form of a \code{(\var{host}, \var{port})}
1210tuple. If \var{address} is not specified, \code{('localhost', 514)} is
1211used. The address is used to open a UDP socket. If \var{facility} is
1212not specified, \constant{LOG_USER} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001213\end{classdesc}
1214
1215\begin{methoddesc}{close}{}
1216Closes the socket to the remote host.
1217\end{methoddesc}
1218
1219\begin{methoddesc}{emit}{record}
1220The record is formatted, and then sent to the syslog server. If
1221exception information is present, it is \emph{not} sent to the server.
Skip Montanaro649698f2002-11-14 03:57:19 +00001222\end{methoddesc}
1223
1224\begin{methoddesc}{encodePriority}{facility, priority}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001225Encodes the facility and priority into an integer. You can pass in strings
1226or integers - if strings are passed, internal mapping dictionaries are used
1227to convert them to integers.
Skip Montanaro649698f2002-11-14 03:57:19 +00001228\end{methoddesc}
1229
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001230\subsubsection{NTEventLogHandler}
Skip Montanaro649698f2002-11-14 03:57:19 +00001231
Vinay Sajip51f52352006-01-22 11:58:39 +00001232The \class{NTEventLogHandler} class, located in the
1233\module{logging.handlers} module, supports sending logging messages to
1234a local Windows NT, Windows 2000 or Windows XP event log. Before you
1235can use it, you need Mark Hammond's Win32 extensions for Python
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001236installed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001237
Fred Drake9a5b6a62003-07-08 15:38:40 +00001238\begin{classdesc}{NTEventLogHandler}{appname\optional{,
1239 dllname\optional{, logtype}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001240Returns a new instance of the \class{NTEventLogHandler} class. The
1241\var{appname} is used to define the application name as it appears in the
1242event log. An appropriate registry entry is created using this name.
1243The \var{dllname} should give the fully qualified pathname of a .dll or .exe
1244which contains message definitions to hold in the log (if not specified,
Fred Drake9a5b6a62003-07-08 15:38:40 +00001245\code{'win32service.pyd'} is used - this is installed with the Win32
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001246extensions and contains some basic placeholder message definitions.
1247Note that use of these placeholders will make your event logs big, as the
1248entire message source is held in the log. If you want slimmer logs, you have
1249to pass in the name of your own .dll or .exe which contains the message
1250definitions you want to use in the event log). The \var{logtype} is one of
Fred Drake9a5b6a62003-07-08 15:38:40 +00001251\code{'Application'}, \code{'System'} or \code{'Security'}, and
1252defaults to \code{'Application'}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001253\end{classdesc}
1254
1255\begin{methoddesc}{close}{}
1256At this point, you can remove the application name from the registry as a
1257source of event log entries. However, if you do this, you will not be able
1258to see the events as you intended in the Event Log Viewer - it needs to be
1259able to access the registry to get the .dll name. The current version does
1260not do this (in fact it doesn't do anything).
1261\end{methoddesc}
1262
1263\begin{methoddesc}{emit}{record}
1264Determines the message ID, event category and event type, and then logs the
1265message in the NT event log.
1266\end{methoddesc}
1267
1268\begin{methoddesc}{getEventCategory}{record}
1269Returns the event category for the record. Override this if you
1270want to specify your own categories. This version returns 0.
1271\end{methoddesc}
1272
1273\begin{methoddesc}{getEventType}{record}
1274Returns the event type for the record. Override this if you want
1275to specify your own types. This version does a mapping using the
1276handler's typemap attribute, which is set up in \method{__init__()}
1277to a dictionary which contains mappings for \constant{DEBUG},
1278\constant{INFO}, \constant{WARNING}, \constant{ERROR} and
1279\constant{CRITICAL}. If you are using your own levels, you will either need
1280to override this method or place a suitable dictionary in the
1281handler's \var{typemap} attribute.
1282\end{methoddesc}
1283
1284\begin{methoddesc}{getMessageID}{record}
1285Returns the message ID for the record. If you are using your
1286own messages, you could do this by having the \var{msg} passed to the
1287logger being an ID rather than a format string. Then, in here,
1288you could use a dictionary lookup to get the message ID. This
1289version returns 1, which is the base message ID in
Fred Drake9a5b6a62003-07-08 15:38:40 +00001290\file{win32service.pyd}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001291\end{methoddesc}
1292
1293\subsubsection{SMTPHandler}
1294
Vinay Sajip51f52352006-01-22 11:58:39 +00001295The \class{SMTPHandler} class, located in the
1296\module{logging.handlers} module, supports sending logging messages to
1297an email address via SMTP.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001298
1299\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
1300Returns a new instance of the \class{SMTPHandler} class. The
1301instance is initialized with the from and to addresses and subject
Vinay Sajip84df97f2005-02-18 11:50:11 +00001302line of the email. The \var{toaddrs} should be a list of strings. To specify a
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001303non-standard SMTP port, use the (host, port) tuple format for the
1304\var{mailhost} argument. If you use a string, the standard SMTP port
1305is used.
1306\end{classdesc}
1307
1308\begin{methoddesc}{emit}{record}
1309Formats the record and sends it to the specified addressees.
1310\end{methoddesc}
1311
1312\begin{methoddesc}{getSubject}{record}
1313If you want to specify a subject line which is record-dependent,
1314override this method.
1315\end{methoddesc}
1316
1317\subsubsection{MemoryHandler}
1318
Vinay Sajip51f52352006-01-22 11:58:39 +00001319The \class{MemoryHandler} class, located in the
1320\module{logging.handlers} module, supports buffering of logging
1321records in memory, periodically flushing them to a \dfn{target}
1322handler. Flushing occurs whenever the buffer is full, or when an event
1323of a certain severity or greater is seen.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001324
1325\class{MemoryHandler} is a subclass of the more general
1326\class{BufferingHandler}, which is an abstract class. This buffers logging
1327records in memory. Whenever each record is added to the buffer, a
1328check is made by calling \method{shouldFlush()} to see if the buffer
1329should be flushed. If it should, then \method{flush()} is expected to
1330do the needful.
1331
1332\begin{classdesc}{BufferingHandler}{capacity}
1333Initializes the handler with a buffer of the specified capacity.
1334\end{classdesc}
1335
1336\begin{methoddesc}{emit}{record}
1337Appends the record to the buffer. If \method{shouldFlush()} returns true,
1338calls \method{flush()} to process the buffer.
1339\end{methoddesc}
1340
1341\begin{methoddesc}{flush}{}
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001342You can override this to implement custom flushing behavior. This version
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001343just zaps the buffer to empty.
1344\end{methoddesc}
1345
1346\begin{methoddesc}{shouldFlush}{record}
1347Returns true if the buffer is up to capacity. This method can be
1348overridden to implement custom flushing strategies.
1349\end{methoddesc}
1350
1351\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
Neal Norwitz6fa635d2003-02-18 14:20:07 +00001352\optional{, target}}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001353Returns a new instance of the \class{MemoryHandler} class. The
1354instance is initialized with a buffer size of \var{capacity}. If
1355\var{flushLevel} is not specified, \constant{ERROR} is used. If no
1356\var{target} is specified, the target will need to be set using
1357\method{setTarget()} before this handler does anything useful.
1358\end{classdesc}
1359
1360\begin{methoddesc}{close}{}
1361Calls \method{flush()}, sets the target to \constant{None} and
1362clears the buffer.
1363\end{methoddesc}
1364
1365\begin{methoddesc}{flush}{}
1366For a \class{MemoryHandler}, flushing means just sending the buffered
1367records to the target, if there is one. Override if you want
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001368different behavior.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001369\end{methoddesc}
1370
1371\begin{methoddesc}{setTarget}{target}
1372Sets the target handler for this handler.
1373\end{methoddesc}
1374
1375\begin{methoddesc}{shouldFlush}{record}
1376Checks for buffer full or a record at the \var{flushLevel} or higher.
1377\end{methoddesc}
1378
1379\subsubsection{HTTPHandler}
1380
Vinay Sajip51f52352006-01-22 11:58:39 +00001381The \class{HTTPHandler} class, located in the
1382\module{logging.handlers} module, supports sending logging messages to
1383a Web server, using either \samp{GET} or \samp{POST} semantics.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001384
1385\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
1386Returns a new instance of the \class{HTTPHandler} class. The
1387instance is initialized with a host address, url and HTTP method.
Vinay Sajip00b5c932005-10-29 00:40:15 +00001388The \var{host} can be of the form \code{host:port}, should you need to
1389use a specific port number. If no \var{method} is specified, \samp{GET}
1390is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001391\end{classdesc}
1392
1393\begin{methoddesc}{emit}{record}
1394Sends the record to the Web server as an URL-encoded dictionary.
1395\end{methoddesc}
1396
1397\subsection{Formatter Objects}
1398
1399\class{Formatter}s have the following attributes and methods. They are
1400responsible for converting a \class{LogRecord} to (usually) a string
1401which can be interpreted by either a human or an external system. The
1402base
1403\class{Formatter} allows a formatting string to be specified. If none is
Fred Drake8efc74d2004-04-15 06:18:48 +00001404supplied, the default value of \code{'\%(message)s'} is used.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001405
1406A Formatter can be initialized with a format string which makes use of
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +00001407knowledge of the \class{LogRecord} attributes - such as the default value
1408mentioned above making use of the fact that the user's message and
Fred Drake6b3b0462004-04-09 18:26:40 +00001409arguments are pre-formatted into a \class{LogRecord}'s \var{message}
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001410attribute. This format string contains standard python \%-style
1411mapping keys. See section \ref{typesseq-strings}, ``String Formatting
1412Operations,'' for more information on string formatting.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001413
Fred Drake6b3b0462004-04-09 18:26:40 +00001414Currently, the useful mapping keys in a \class{LogRecord} are:
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001415
Fred Drake9a5b6a62003-07-08 15:38:40 +00001416\begin{tableii}{l|l}{code}{Format}{Description}
1417\lineii{\%(name)s} {Name of the logger (logging channel).}
1418\lineii{\%(levelno)s} {Numeric logging level for the message
1419 (\constant{DEBUG}, \constant{INFO},
1420 \constant{WARNING}, \constant{ERROR},
1421 \constant{CRITICAL}).}
1422\lineii{\%(levelname)s}{Text logging level for the message
1423 (\code{'DEBUG'}, \code{'INFO'},
1424 \code{'WARNING'}, \code{'ERROR'},
1425 \code{'CRITICAL'}).}
1426\lineii{\%(pathname)s} {Full pathname of the source file where the logging
1427 call was issued (if available).}
1428\lineii{\%(filename)s} {Filename portion of pathname.}
1429\lineii{\%(module)s} {Module (name portion of filename).}
Neal Norwitzc16dd482006-02-13 02:04:37 +00001430\lineii{\%(funcName)s} {Name of function containing the logging call.}
Fred Drake9a5b6a62003-07-08 15:38:40 +00001431\lineii{\%(lineno)d} {Source line number where the logging call was issued
1432 (if available).}
Fred Drake6b3b0462004-04-09 18:26:40 +00001433\lineii{\%(created)f} {Time when the \class{LogRecord} was created (as
Fred Drake9a5b6a62003-07-08 15:38:40 +00001434 returned by \function{time.time()}).}
Thomas Wouters89f507f2006-12-13 04:49:30 +00001435\lineii{\%(relativeCreated)d} {Time in milliseconds when the LogRecord was
1436 created, relative to the time the logging module was
1437 loaded.}
Fred Drake6b3b0462004-04-09 18:26:40 +00001438\lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord}
1439 was created. By default this is of the form
Fred Drake9a5b6a62003-07-08 15:38:40 +00001440 ``2003-07-08 16:49:45,896'' (the numbers after the
1441 comma are millisecond portion of the time).}
1442\lineii{\%(msecs)d} {Millisecond portion of the time when the
1443 \class{LogRecord} was created.}
1444\lineii{\%(thread)d} {Thread ID (if available).}
Vinay Sajip99358df2005-03-31 20:18:06 +00001445\lineii{\%(threadName)s} {Thread name (if available).}
Fred Drake9a5b6a62003-07-08 15:38:40 +00001446\lineii{\%(process)d} {Process ID (if available).}
1447\lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}
Anthony Baxtera6b7d342003-07-08 08:40:20 +00001448\end{tableii}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001449
Neal Norwitzc16dd482006-02-13 02:04:37 +00001450\versionchanged[\var{funcName} was added]{2.5}
1451
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001452\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
1453Returns a new instance of the \class{Formatter} class. The
1454instance is initialized with a format string for the message as a whole,
1455as well as a format string for the date/time portion of a message. If
Neal Norwitzdd3afa72003-07-08 16:26:34 +00001456no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001457is specified, the ISO8601 date format is used.
1458\end{classdesc}
1459
1460\begin{methoddesc}{format}{record}
1461The record's attribute dictionary is used as the operand to a
1462string formatting operation. Returns the resulting string.
1463Before formatting the dictionary, a couple of preparatory steps
1464are carried out. The \var{message} attribute of the record is computed
1465using \var{msg} \% \var{args}. If the formatting string contains
Fred Drake9a5b6a62003-07-08 15:38:40 +00001466\code{'(asctime)'}, \method{formatTime()} is called to format the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001467event time. If there is exception information, it is formatted using
1468\method{formatException()} and appended to the message.
1469\end{methoddesc}
1470
1471\begin{methoddesc}{formatTime}{record\optional{, datefmt}}
1472This method should be called from \method{format()} by a formatter which
1473wants to make use of a formatted time. This method can be overridden
1474in formatters to provide for any specific requirement, but the
Raymond Hettinger2ef85a72003-01-25 21:46:53 +00001475basic behavior is as follows: if \var{datefmt} (a string) is specified,
Fred Drakec23e0192003-01-28 22:09:16 +00001476it is used with \function{time.strftime()} to format the creation time of the
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001477record. Otherwise, the ISO8601 format is used. The resulting
1478string is returned.
1479\end{methoddesc}
1480
1481\begin{methoddesc}{formatException}{exc_info}
1482Formats the specified exception information (a standard exception tuple
Fred Drakec23e0192003-01-28 22:09:16 +00001483as returned by \function{sys.exc_info()}) as a string. This default
1484implementation just uses \function{traceback.print_exception()}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001485The resulting string is returned.
1486\end{methoddesc}
1487
1488\subsection{Filter Objects}
1489
1490\class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
1491more sophisticated filtering than is provided by levels. The base filter
1492class only allows events which are below a certain point in the logger
1493hierarchy. For example, a filter initialized with "A.B" will allow events
1494logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
1495"B.A.B" etc. If initialized with the empty string, all events are passed.
1496
1497\begin{classdesc}{Filter}{\optional{name}}
1498Returns an instance of the \class{Filter} class. If \var{name} is specified,
1499it names a logger which, together with its children, will have its events
1500allowed through the filter. If no name is specified, allows every event.
1501\end{classdesc}
1502
1503\begin{methoddesc}{filter}{record}
1504Is the specified record to be logged? Returns zero for no, nonzero for
1505yes. If deemed appropriate, the record may be modified in-place by this
1506method.
1507\end{methoddesc}
1508
1509\subsection{LogRecord Objects}
1510
Fred Drake6b3b0462004-04-09 18:26:40 +00001511\class{LogRecord} instances are created every time something is logged. They
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001512contain all the information pertinent to the event being logged. The
1513main information passed in is in msg and args, which are combined
1514using msg \% args to create the message field of the record. The record
1515also includes information such as when the record was created, the
1516source line where the logging call was made, and any exception
1517information to be logged.
1518
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001519\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
Thomas Wouters89f507f2006-12-13 04:49:30 +00001520 exc_info \optional{, func}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001521Returns an instance of \class{LogRecord} initialized with interesting
1522information. The \var{name} is the logger name; \var{lvl} is the
1523numeric level; \var{pathname} is the absolute pathname of the source
1524file in which the logging call was made; \var{lineno} is the line
1525number in that file where the logging call is found; \var{msg} is the
1526user-supplied message (a format string); \var{args} is the tuple
1527which, together with \var{msg}, makes up the user message; and
1528\var{exc_info} is the exception tuple obtained by calling
1529\function{sys.exc_info() }(or \constant{None}, if no exception information
Thomas Wouters89f507f2006-12-13 04:49:30 +00001530is available). The \var{func} is the name of the function from which the
Fred Drake4a76da72007-04-26 04:43:39 +00001531logging call was made. If not specified, it defaults to \code{None}.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001532\versionchanged[\var{func} was added]{2.5}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001533\end{classdesc}
1534
Vinay Sajipe8fdc452004-12-02 21:27:42 +00001535\begin{methoddesc}{getMessage}{}
1536Returns the message for this \class{LogRecord} instance after merging any
1537user-supplied arguments with the message.
1538\end{methoddesc}
1539
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001540\subsection{Thread Safety}
1541
1542The logging module is intended to be thread-safe without any special work
1543needing to be done by its clients. It achieves this though using threading
1544locks; there is one lock to serialize access to the module's shared data,
1545and each handler also creates a lock to serialize access to its underlying
1546I/O.
1547
1548\subsection{Configuration}
1549
1550
Fred Drake94ffbb72004-04-08 19:44:31 +00001551\subsubsection{Configuration functions%
1552 \label{logging-config-api}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001553
Vinay Sajip51f52352006-01-22 11:58:39 +00001554The following functions configure the logging module. They are located in the
1555\module{logging.config} module. Their use is optional --- you can configure
1556the logging module using these functions or by making calls to the
1557main API (defined in \module{logging} itself) and defining handlers
1558which are declared either in \module{logging} or
1559\module{logging.handlers}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001560
1561\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
1562Reads the logging configuration from a ConfigParser-format file named
1563\var{fname}. This function can be called several times from an application,
1564allowing an end user the ability to select from various pre-canned
1565configurations (if the developer provides a mechanism to present the
1566choices and load the chosen configuration). Defaults to be passed to
1567ConfigParser can be specified in the \var{defaults} argument.
1568\end{funcdesc}
1569
1570\begin{funcdesc}{listen}{\optional{port}}
1571Starts up a socket server on the specified port, and listens for new
1572configurations. If no port is specified, the module's default
1573\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
1574will be sent as a file suitable for processing by \function{fileConfig()}.
1575Returns a \class{Thread} instance on which you can call \method{start()}
1576to start the server, and which you can \method{join()} when appropriate.
Vinay Sajip4c1423b2005-06-05 20:39:36 +00001577To stop the server, call \function{stopListening()}. To send a configuration
1578to the socket, read in the configuration file and send it to the socket
1579as a string of bytes preceded by a four-byte length packed in binary using
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001580struct.\code{pack('>L', n)}.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001581\end{funcdesc}
1582
1583\begin{funcdesc}{stopListening}{}
1584Stops the listening server which was created with a call to
1585\function{listen()}. This is typically called before calling \method{join()}
1586on the return value from \function{listen()}.
1587\end{funcdesc}
1588
Fred Drake94ffbb72004-04-08 19:44:31 +00001589\subsubsection{Configuration file format%
1590 \label{logging-config-fileformat}}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001591
Fred Drake6b3b0462004-04-09 18:26:40 +00001592The configuration file format understood by \function{fileConfig()} is
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001593based on ConfigParser functionality. The file must contain sections
1594called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
1595which identify by name the entities of each type which are defined in
1596the file. For each such entity, there is a separate section which
1597identified how that entity is configured. Thus, for a logger named
1598\code{log01} in the \code{[loggers]} section, the relevant
1599configuration details are held in a section
1600\code{[logger_log01]}. Similarly, a handler called \code{hand01} in
1601the \code{[handlers]} section will have its configuration held in a
1602section called \code{[handler_hand01]}, while a formatter called
1603\code{form01} in the \code{[formatters]} section will have its
1604configuration specified in a section called
1605\code{[formatter_form01]}. The root logger configuration must be
1606specified in a section called \code{[logger_root]}.
1607
1608Examples of these sections in the file are given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001609
1610\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001611[loggers]
1612keys=root,log02,log03,log04,log05,log06,log07
Skip Montanaro649698f2002-11-14 03:57:19 +00001613
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001614[handlers]
1615keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1616
1617[formatters]
1618keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
Skip Montanaro649698f2002-11-14 03:57:19 +00001619\end{verbatim}
1620
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001621The root logger must specify a level and a list of handlers. An
1622example of a root logger section is given below.
Skip Montanaro649698f2002-11-14 03:57:19 +00001623
1624\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001625[logger_root]
1626level=NOTSET
1627handlers=hand01
Skip Montanaro649698f2002-11-14 03:57:19 +00001628\end{verbatim}
1629
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001630The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1631ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1632\code{NOTSET} means that all messages will be logged. Level values are
1633\function{eval()}uated in the context of the \code{logging} package's
1634namespace.
Skip Montanaro649698f2002-11-14 03:57:19 +00001635
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001636The \code{handlers} entry is a comma-separated list of handler names,
1637which must appear in the \code{[handlers]} section. These names must
1638appear in the \code{[handlers]} section and have corresponding
1639sections in the configuration file.
Skip Montanaro649698f2002-11-14 03:57:19 +00001640
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001641For loggers other than the root logger, some additional information is
1642required. This is illustrated by the following example.
Skip Montanaro649698f2002-11-14 03:57:19 +00001643
1644\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001645[logger_parser]
1646level=DEBUG
1647handlers=hand01
1648propagate=1
1649qualname=compiler.parser
Skip Montanaro649698f2002-11-14 03:57:19 +00001650\end{verbatim}
1651
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001652The \code{level} and \code{handlers} entries are interpreted as for
1653the root logger, except that if a non-root logger's level is specified
1654as \code{NOTSET}, the system consults loggers higher up the hierarchy
1655to determine the effective level of the logger. The \code{propagate}
1656entry is set to 1 to indicate that messages must propagate to handlers
1657higher up the logger hierarchy from this logger, or 0 to indicate that
1658messages are \strong{not} propagated to handlers up the hierarchy. The
1659\code{qualname} entry is the hierarchical channel name of the logger,
Vinay Sajipa13c60b2004-07-03 11:45:53 +00001660that is to say the name used by the application to get the logger.
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001661
1662Sections which specify handler configuration are exemplified by the
1663following.
1664
Skip Montanaro649698f2002-11-14 03:57:19 +00001665\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001666[handler_hand01]
1667class=StreamHandler
1668level=NOTSET
1669formatter=form01
1670args=(sys.stdout,)
Skip Montanaro649698f2002-11-14 03:57:19 +00001671\end{verbatim}
1672
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001673The \code{class} entry indicates the handler's class (as determined by
1674\function{eval()} in the \code{logging} package's namespace). The
1675\code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1676to mean "log everything".
1677
1678The \code{formatter} entry indicates the key name of the formatter for
1679this handler. If blank, a default formatter
1680(\code{logging._defaultFormatter}) is used. If a name is specified, it
1681must appear in the \code{[formatters]} section and have a
1682corresponding section in the configuration file.
1683
1684The \code{args} entry, when \function{eval()}uated in the context of
1685the \code{logging} package's namespace, is the list of arguments to
1686the constructor for the handler class. Refer to the constructors for
1687the relevant handlers, or to the examples below, to see how typical
1688entries are constructed.
Skip Montanaro649698f2002-11-14 03:57:19 +00001689
1690\begin{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001691[handler_hand02]
1692class=FileHandler
1693level=DEBUG
1694formatter=form02
1695args=('python.log', 'w')
1696
1697[handler_hand03]
1698class=handlers.SocketHandler
1699level=INFO
1700formatter=form03
1701args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1702
1703[handler_hand04]
1704class=handlers.DatagramHandler
1705level=WARN
1706formatter=form04
1707args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1708
1709[handler_hand05]
1710class=handlers.SysLogHandler
1711level=ERROR
1712formatter=form05
1713args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1714
1715[handler_hand06]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001716class=handlers.NTEventLogHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001717level=CRITICAL
1718formatter=form06
1719args=('Python Application', '', 'Application')
1720
1721[handler_hand07]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001722class=handlers.SMTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001723level=WARN
1724formatter=form07
1725args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1726
1727[handler_hand08]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001728class=handlers.MemoryHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001729level=NOTSET
1730formatter=form08
1731target=
1732args=(10, ERROR)
1733
1734[handler_hand09]
Vinay Sajip20f42c42004-07-12 15:48:04 +00001735class=handlers.HTTPHandler
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001736level=NOTSET
1737formatter=form09
1738args=('localhost:9022', '/log', 'GET')
Skip Montanaro649698f2002-11-14 03:57:19 +00001739\end{verbatim}
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001740
1741Sections which specify formatter configuration are typified by the following.
1742
1743\begin{verbatim}
1744[formatter_form01]
1745format=F1 %(asctime)s %(levelname)s %(message)s
1746datefmt=
Vinay Sajip51f52352006-01-22 11:58:39 +00001747class=logging.Formatter
Neal Norwitzcd5c8c22003-01-25 21:29:41 +00001748\end{verbatim}
1749
1750The \code{format} entry is the overall format string, and the
1751\code{datefmt} entry is the \function{strftime()}-compatible date/time format
1752string. If empty, the package substitutes ISO8601 format date/times, which
1753is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1754The ISO8601 format also specifies milliseconds, which are appended to the
1755result of using the above format string, with a comma separator. An example
1756time in ISO8601 format is \code{2003-01-23 00:29:50,411}.
Vinay Sajip51f52352006-01-22 11:58:39 +00001757
1758The \code{class} entry is optional. It indicates the name of the
1759formatter's class (as a dotted module and class name.) This option is
1760useful for instantiating a \class{Formatter} subclass. Subclasses of
1761\class{Formatter} can present exception tracebacks in an expanded or
1762condensed format.