view tools/python/logging/logging- @ 3887:4385894c52ae

bitkeeper revision 1.1230.2.4 (421a95cepOZORm0EbZfqBeZ6PZ8MwA)

Merge freefall.cl.cam.ac.uk:/auto/groups/xeno/users/cl349/BK/xen-unstable.bk
into freefall.cl.cam.ac.uk:/auto/groups/xeno-xenod/BK/xen-unstable.bk
author iap10@freefall.cl.cam.ac.uk
date Tue Feb 22 02:15:42 2005 +0000 (2005-02-22)
parents dae98734f12e
line source
1 \section{\module{logging} ---
2 Logging facility for Python}
4 \declaremodule{standard}{logging}
6 % These apply to all modules, and may be given more than once:
8 \moduleauthor{Vinay Sajip}{vinay_sajip@red-dove.com}
9 \sectionauthor{Vinay Sajip}{vinay_sajip@red-dove.com}
11 \modulesynopsis{Logging module for Python based on \pep{282}.}
13 \indexii{Errors}{logging}
15 \versionadded{2.3}
16 This module defines functions and classes which implement a flexible
17 error logging system for applications.
19 Logging is performed by calling methods on instances of the
20 \class{Logger} class (hereafter called \dfn{loggers}). Each instance has a
21 name, and they are conceptually arranged in a name space hierarchy
22 using dots (periods) as separators. For example, a logger named
23 "scan" is the parent of loggers "scan.text", "scan.html" and "scan.pdf".
24 Logger names can be anything you want, and indicate the area of an
25 application in which a logged message originates.
27 Logged messages also have levels of importance associated with them.
28 The default levels provided are \constant{DEBUG}, \constant{INFO},
29 \constant{WARNING}, \constant{ERROR} and \constant{CRITICAL}. As a
30 convenience, you indicate the importance of a logged message by calling
31 an appropriate method of \class{Logger}. The methods are
32 \method{debug()}, \method{info()}, \method{warning()}, \method{error()} and
33 \method{critical()}, which mirror the default levels. You are not
34 constrained to use these levels: you can specify your own and use a
35 more general \class{Logger} method, \method{log()}, which takes an
36 explicit level argument.
38 Levels can also be associated with loggers, being set either by the
39 developer or through loading a saved logging configuration. When a
40 logging method is called on a logger, the logger compares its own
41 level with the level associated with the method call. If the logger's
42 level is higher than the method call's, no logging message is actually
43 generated. This is the basic mechanism controlling the verbosity of
44 logging output.
46 Logging messages are encoded as instances of the \class{LogRecord} class.
47 When a logger decides to actually log an event, an \class{LogRecord}
48 instance is created from the logging message.
50 Logging messages are subjected to a dispatch mechanism through the
51 use of \dfn{handlers}, which are instances of subclasses of the
52 \class{Handler} class. Handlers are responsible for ensuring that a logged
53 message (in the form of a \class{LogRecord}) ends up in a particular
54 location (or set of locations) which is useful for the target audience for
55 that message (such as end users, support desk staff, system administrators,
56 developers). Handlers are passed \class{LogRecord} instances intended for
57 particular destinations. Each logger can have zero, one or more handlers
58 associated with it (via the \method{addHandler} method of \class{Logger}).
59 In addition to any handlers directly associated with a logger,
60 \emph{all handlers associated with all ancestors of the logger} are
61 called to dispatch the message.
63 Just as for loggers, handlers can have levels associated with them.
64 A handler's level acts as a filter in the same way as a logger's level does.
65 If a handler decides to actually dispatch an event, the \method{emit()} method
66 is used to send the message to its destination. Most user-defined subclasses
67 of \class{Handler} will need to override this \method{emit()}.
69 In addition to the base \class{Handler} class, many useful subclasses
70 are provided:
72 \begin{enumerate}
74 \item \class{StreamHandler} instances send error messages to
75 streams (file-like objects).
77 \item \class{FileHandler} instances send error messages to disk
78 files.
80 \item \class{RotatingFileHandler} instances send error messages to disk
81 files, with support for maximum log file sizes and log file rotation.
83 \item \class{SocketHandler} instances send error messages to
84 TCP/IP sockets.
86 \item \class{DatagramHandler} instances send error messages to UDP
87 sockets.
89 \item \class{SMTPHandler} instances send error messages to a
90 designated email address.
92 \item \class{SysLogHandler} instances send error messages to a
93 \UNIX{} syslog daemon, possibly on a remote machine.
95 \item \class{NTEventLogHandler} instances send error messages to a
96 Windows NT/2000/XP event log.
98 \item \class{MemoryHandler} instances send error messages to a
99 buffer in memory, which is flushed whenever specific criteria are
100 met.
102 \item \class{HTTPHandler} instances send error messages to an
103 HTTP server using either \samp{GET} or \samp{POST} semantics.
105 \end{enumerate}
107 The \class{StreamHandler} and \class{FileHandler} classes are defined
108 in the core logging package. The other handlers are defined in a sub-
109 module, \module{logging.handlers}. (There is also another sub-module,
110 \module{logging.config}, for configuration functionality.)
112 Logged messages are formatted for presentation through instances of the
113 \class{Formatter} class. They are initialized with a format string
114 suitable for use with the \% operator and a dictionary.
116 For formatting multiple messages in a batch, instances of
117 \class{BufferingFormatter} can be used. In addition to the format string
118 (which is applied to each message in the batch), there is provision for
119 header and trailer format strings.
121 When filtering based on logger level and/or handler level is not enough,
122 instances of \class{Filter} can be added to both \class{Logger} and
123 \class{Handler} instances (through their \method{addFilter()} method).
124 Before deciding to process a message further, both loggers and handlers
125 consult all their filters for permission. If any filter returns a false
126 value, the message is not processed further.
128 The basic \class{Filter} functionality allows filtering by specific logger
129 name. If this feature is used, messages sent to the named logger and its
130 children are allowed through the filter, and all others dropped.
132 In addition to the classes described above, there are a number of module-
133 level functions.
135 \begin{funcdesc}{getLogger}{\optional{name}}
136 Return a logger with the specified name or, if no name is specified, return
137 a logger which is the root logger of the hierarchy.
139 All calls to this function with a given name return the same logger instance.
140 This means that logger instances never need to be passed between different
141 parts of an application.
142 \end{funcdesc}
144 \begin{funcdesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
145 Logs a message with level \constant{DEBUG} on the root logger.
146 The \var{msg} is the message format string, and the \var{args} are the
147 arguments which are merged into \var{msg}. The only keyword argument in
148 \var{kwargs} which is inspected is \var{exc_info} which, if it does not
149 evaluate as false, causes exception information (via a call to
150 \function{sys.exc_info()}) to be added to the logging message.
151 \end{funcdesc}
153 \begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
154 Logs a message with level \constant{INFO} on the root logger.
155 The arguments are interpreted as for \function{debug()}.
156 \end{funcdesc}
158 \begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
159 Logs a message with level \constant{WARNING} on the root logger.
160 The arguments are interpreted as for \function{debug()}.
161 \end{funcdesc}
163 \begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
164 Logs a message with level \constant{ERROR} on the root logger.
165 The arguments are interpreted as for \function{debug()}.
166 \end{funcdesc}
168 \begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
169 Logs a message with level \constant{CRITICAL} on the root logger.
170 The arguments are interpreted as for \function{debug()}.
171 \end{funcdesc}
173 \begin{funcdesc}{exception}{msg\optional{, *args}}
174 Logs a message with level \constant{ERROR} on the root logger.
175 The arguments are interpreted as for \function{debug()}. Exception info
176 is added to the logging message. This function should only be called
177 from an exception handler.
178 \end{funcdesc}
180 \begin{funcdesc}{disable}{lvl}
181 Provides an overriding level \var{lvl} for all loggers which takes
182 precedence over the logger's own level. When the need arises to
183 temporarily throttle logging output down across the whole application,
184 this function can be useful.
185 \end{funcdesc}
187 \begin{funcdesc}{addLevelName}{lvl, levelName}
188 Associates level \var{lvl} with text \var{levelName} in an internal
189 dictionary, which is used to map numeric levels to a textual
190 representation, for example when a \class{Formatter} formats a message.
191 This function can also be used to define your own levels. The only
192 constraints are that all levels used must be registered using this
193 function, levels should be positive integers and they should increase
194 in increasing order of severity.
195 \end{funcdesc}
197 \begin{funcdesc}{getLevelName}{lvl}
198 Returns the textual representation of logging level \var{lvl}. If the
199 level is one of the predefined levels \constant{CRITICAL},
200 \constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG}
201 then you get the corresponding string. If you have associated levels
202 with names using \function{addLevelName()} then the name you have associated
203 with \var{lvl} is returned. Otherwise, the string "Level \%s" \% lvl is
204 returned.
205 \end{funcdesc}
207 \begin{funcdesc}{makeLogRecord}{attrdict}
208 Creates and returns a new \class{LogRecord} instance whose attributes are
209 defined by \var{attrdict}. This function is useful for taking a pickled
210 \class{LogRecord} attribute dictionary, sent over a socket, and reconstituting
211 it as a \class{LogRecord} instance at the receiving end.
212 \end{funcdesc}
214 \begin{funcdesc}{basicConfig}{}
215 Does basic configuration for the logging system by creating a
216 \class{StreamHandler} with a default \class{Formatter} and adding it to
217 the root logger. The functions \function{debug()}, \function{info()},
218 \function{warning()}, \function{error()} and \function{critical()} will call
219 \function{basicConfig()} automatically if no handlers are defined for the
220 root logger.
221 \end{funcdesc}
223 \begin{funcdesc}{shutdown}{}
224 Informs the logging system to perform an orderly shutdown by flushing and
225 closing all handlers.
226 \end{funcdesc}
228 \begin{funcdesc}{setLoggerClass}{klass}
229 Tells the logging system to use the class \var{klass} when instantiating a
230 logger. The class should define \method{__init__()} such that only a name
231 argument is required, and the \method{__init__()} should call
232 \method{Logger.__init__()}. This function is typically called before any
233 loggers are instantiated by applications which need to use custom logger
234 behavior.
235 \end{funcdesc}
238 \begin{seealso}
239 \seepep{282}{A Logging System}
240 {The proposal which described this feature for inclusion in
241 the Python standard library.}
242 \seelink{http://www.red-dove.com/python_logging.html}
243 {Original Python \module{logging} package}
244 {This is the original source for the \module{logging}
245 package. The version of the package available from this
246 site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x, which
247 do not include the \module{logging} package in the standard
248 library.}
249 \end{seealso}
252 \subsection{Logger Objects}
254 Loggers have the following attributes and methods. Note that Loggers are
255 never instantiated directly, but always through the module-level function
256 \function{logging.getLogger(name)}.
258 \begin{datadesc}{propagate}
259 If this evaluates to false, logging messages are not passed by this
260 logger or by child loggers to higher level (ancestor) loggers. The
261 constructor sets this attribute to 1.
262 \end{datadesc}
264 \begin{methoddesc}{setLevel}{lvl}
265 Sets the threshold for this logger to \var{lvl}. Logging messages
266 which are less severe than \var{lvl} will be ignored. When a logger is
267 created, the level is set to \constant{NOTSET} (which causes all messages
268 to be processed in the root logger, or delegation to the parent in non-root
269 loggers).
270 \end{methoddesc}
272 \begin{methoddesc}{isEnabledFor}{lvl}
273 Indicates if a message of severity \var{lvl} would be processed by
274 this logger. This method checks first the module-level level set by
275 \function{logging.disable(lvl)} and then the logger's effective level as
276 determined by \method{getEffectiveLevel()}.
277 \end{methoddesc}
279 \begin{methoddesc}{getEffectiveLevel}{}
280 Indicates the effective level for this logger. If a value other than
281 \constant{NOTSET} has been set using \method{setLevel()}, it is returned.
282 Otherwise, the hierarchy is traversed towards the root until a value
283 other than \constant{NOTSET} is found, and that value is returned.
284 \end{methoddesc}
286 \begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
287 Logs a message with level \constant{DEBUG} on this logger.
288 The \var{msg} is the message format string, and the \var{args} are the
289 arguments which are merged into \var{msg}. The only keyword argument in
290 \var{kwargs} which is inspected is \var{exc_info} which, if it does not
291 evaluate as false, causes exception information (via a call to
292 \function{sys.exc_info()}) to be added to the logging message.
293 \end{methoddesc}
295 \begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
296 Logs a message with level \constant{INFO} on this logger.
297 The arguments are interpreted as for \method{debug()}.
298 \end{methoddesc}
300 \begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
301 Logs a message with level \constant{WARNING} on this logger.
302 The arguments are interpreted as for \method{debug()}.
303 \end{methoddesc}
305 \begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
306 Logs a message with level \constant{ERROR} on this logger.
307 The arguments are interpreted as for \method{debug()}.
308 \end{methoddesc}
310 \begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
311 Logs a message with level \constant{CRITICAL} on this logger.
312 The arguments are interpreted as for \method{debug()}.
313 \end{methoddesc}
315 \begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
316 Logs a message with level \var{lvl} on this logger.
317 The other arguments are interpreted as for \method{debug()}.
318 \end{methoddesc}
320 \begin{methoddesc}{exception}{msg\optional{, *args}}
321 Logs a message with level \constant{ERROR} on this logger.
322 The arguments are interpreted as for \method{debug()}. Exception info
323 is added to the logging message. This method should only be called
324 from an exception handler.
325 \end{methoddesc}
327 \begin{methoddesc}{addFilter}{filt}
328 Adds the specified filter \var{filt} to this logger.
329 \end{methoddesc}
331 \begin{methoddesc}{removeFilter}{filt}
332 Removes the specified filter \var{filt} from this logger.
333 \end{methoddesc}
335 \begin{methoddesc}{filter}{record}
336 Applies this logger's filters to the record and returns a true value if
337 the record is to be processed.
338 \end{methoddesc}
340 \begin{methoddesc}{addHandler}{hdlr}
341 Adds the specified handler \var{hdlr} to this logger.
342 \end{methoddesc}
344 \begin{methoddesc}{removeHandler}{hdlr}
345 Removes the specified handler \var{hdlr} from this logger.
346 \end{methoddesc}
348 \begin{methoddesc}{findCaller}{}
349 Finds the caller's source filename and line number. Returns the filename
350 and line number as a 2-element tuple.
351 \end{methoddesc}
353 \begin{methoddesc}{handle}{record}
354 Handles a record by passing it to all handlers associated with this logger
355 and its ancestors (until a false value of \var{propagate} is found).
356 This method is used for unpickled records received from a socket, as well
357 as those created locally. Logger-level filtering is applied using
358 \method{filter()}.
359 \end{methoddesc}
361 \begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info}
362 This is a factory method which can be overridden in subclasses to create
363 specialized \class{LogRecord} instances.
364 \end{methoddesc}
366 \subsection{Handler Objects}
368 Handlers have the following attributes and methods. Note that
369 \class{Handler} is never instantiated directly; this class acts as a
370 base for more useful subclasses. However, the \method{__init__()}
371 method in subclasses needs to call \method{Handler.__init__()}.
373 \begin{methoddesc}{__init__}{level=\constant{NOTSET}}
374 Initializes the \class{Handler} instance by setting its level, setting
375 the list of filters to the empty list and creating a lock (using
376 \method{createLock()}) for serializing access to an I/O mechanism.
377 \end{methoddesc}
379 \begin{methoddesc}{createLock}{}
380 Initializes a thread lock which can be used to serialize access to
381 underlying I/O functionality which may not be threadsafe.
382 \end{methoddesc}
384 \begin{methoddesc}{acquire}{}
385 Acquires the thread lock created with \method{createLock()}.
386 \end{methoddesc}
388 \begin{methoddesc}{release}{}
389 Releases the thread lock acquired with \method{acquire()}.
390 \end{methoddesc}
392 \begin{methoddesc}{setLevel}{lvl}
393 Sets the threshold for this handler to \var{lvl}. Logging messages which are
394 less severe than \var{lvl} will be ignored. When a handler is created, the
395 level is set to \constant{NOTSET} (which causes all messages to be processed).
396 \end{methoddesc}
398 \begin{methoddesc}{setFormatter}{form}
399 Sets the \class{Formatter} for this handler to \var{form}.
400 \end{methoddesc}
402 \begin{methoddesc}{addFilter}{filt}
403 Adds the specified filter \var{filt} to this handler.
404 \end{methoddesc}
406 \begin{methoddesc}{removeFilter}{filt}
407 Removes the specified filter \var{filt} from this handler.
408 \end{methoddesc}
410 \begin{methoddesc}{filter}{record}
411 Applies this handler's filters to the record and returns a true value if
412 the record is to be processed.
413 \end{methoddesc}
415 \begin{methoddesc}{flush}{}
416 Ensure all logging output has been flushed. This version does
417 nothing and is intended to be implemented by subclasses.
418 \end{methoddesc}
420 \begin{methoddesc}{close}{}
421 Tidy up any resources used by the handler. This version does
422 nothing and is intended to be implemented by subclasses.
423 \end{methoddesc}
425 \begin{methoddesc}{handle}{record}
426 Conditionally emits the specified logging record, depending on
427 filters which may have been added to the handler. Wraps the actual
428 emission of the record with acquisition/release of the I/O thread
429 lock.
430 \end{methoddesc}
432 \begin{methoddesc}{handleError}{record}
433 This method should be called from handlers when an exception is
434 encountered during an \method{emit()} call. By default it does nothing,
435 which means that exceptions get silently ignored. This is what is
436 mostly wanted for a logging system - most users will not care
437 about errors in the logging system, they are more interested in
438 application errors. You could, however, replace this with a custom
439 handler if you wish. The specified record is the one which was being
440 processed when the exception occurred.
441 \end{methoddesc}
443 \begin{methoddesc}{format}{record}
444 Do formatting for a record - if a formatter is set, use it.
445 Otherwise, use the default formatter for the module.
446 \end{methoddesc}
448 \begin{methoddesc}{emit}{record}
449 Do whatever it takes to actually log the specified logging record.
450 This version is intended to be implemented by subclasses and so
451 raises a \exception{NotImplementedError}.
452 \end{methoddesc}
454 \subsubsection{StreamHandler}
456 The \class{StreamHandler} class sends logging output to streams such as
457 \var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more
458 precisely, any object which supports \method{write()} and \method{flush()}
459 methods).
461 \begin{classdesc}{StreamHandler}{\optional{strm}}
462 Returns a new instance of the \class{StreamHandler} class. If \var{strm} is
463 specified, the instance will use it for logging output; otherwise,
464 \var{sys.stderr} will be used.
465 \end{classdesc}
467 \begin{methoddesc}{emit}{record}
468 If a formatter is specified, it is used to format the record.
469 The record is then written to the stream with a trailing newline.
470 If exception information is present, it is formatted using
471 \function{traceback.print_exception()} and appended to the stream.
472 \end{methoddesc}
474 \begin{methoddesc}{flush}{}
475 Flushes the stream by calling its \method{flush()} method. Note that
476 the \method{close()} method is inherited from \class{Handler} and
477 so does nothing, so an explicit \method{flush()} call may be needed
478 at times.
479 \end{methoddesc}
481 \subsubsection{FileHandler}
483 The \class{FileHandler} class sends logging output to a disk file.
484 It inherits the output functionality from \class{StreamHandler}.
486 \begin{classdesc}{FileHandler}{filename\optional{, mode}}
487 Returns a new instance of the \class{FileHandler} class. The specified
488 file is opened and used as the stream for logging. If \var{mode} is
489 not specified, \constant{'a'} is used. By default, the file grows
490 indefinitely.
491 \end{classdesc}
493 \begin{methoddesc}{close}{}
494 Closes the file.
495 \end{methoddesc}
497 \begin{methoddesc}{emit}{record}
498 Outputs the record to the file.
499 \end{methoddesc}
501 \subsubsection{RotatingFileHandler}
503 The \class{RotatingFileHandler} class supports rotation of disk log files.
505 \begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{,
506 maxBytes\optional{, backupCount}}}}
507 Returns a new instance of the \class{RotatingFileHandler} class. The
508 specified file is opened and used as the stream for logging. If
509 \var{mode} is not specified, \code{'a'} is used. By default, the
510 file grows indefinitely.
512 You can use the \var{maxBytes} and
513 \var{backupCount} values to allow the file to \dfn{rollover} at a
514 predetermined size. When the size is about to be exceeded, the file is
515 closed and a new file is silently opened for output. Rollover occurs
516 whenever the current log file is nearly \var{maxBytes} in length; if
517 \var{maxBytes} is zero, rollover never occurs. If \var{backupCount}
518 is non-zero, the system will save old log files by appending the
519 extensions ".1", ".2" etc., to the filename. For example, with
520 a \var{backupCount} of 5 and a base file name of
521 \file{app.log}, you would get \file{app.log},
522 \file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being
523 written to is always \file{app.log}. When this file is filled, it is
524 closed and renamed to \file{app.log.1}, and if files \file{app.log.1},
525 \file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2},
526 \file{app.log.3} etc. respectively.
527 \end{classdesc}
529 \begin{methoddesc}{doRollover}{}
530 Does a rollover, as described above.
531 \end{methoddesc}
533 \begin{methoddesc}{emit}{record}
534 Outputs the record to the file, catering for rollover as described
535 in \method{setRollover()}.
536 \end{methoddesc}
538 \subsubsection{SocketHandler}
540 The \class{SocketHandler} class sends logging output to a network
541 socket. The base class uses a TCP socket.
543 \begin{classdesc}{SocketHandler}{host, port}
544 Returns a new instance of the \class{SocketHandler} class intended to
545 communicate with a remote machine whose address is given by \var{host}
546 and \var{port}.
547 \end{classdesc}
549 \begin{methoddesc}{close}{}
550 Closes the socket.
551 \end{methoddesc}
553 \begin{methoddesc}{handleError}{}
554 \end{methoddesc}
556 \begin{methoddesc}{emit}{}
557 Pickles the record's attribute dictionary and writes it to the socket in
558 binary format. If there is an error with the socket, silently drops the
559 packet. If the connection was previously lost, re-establishes the connection.
560 To unpickle the record at the receiving end into a LogRecord, use the
561 \function{makeLogRecord} function.
562 \end{methoddesc}
564 \begin{methoddesc}{handleError}{}
565 Handles an error which has occurred during \method{emit()}. The
566 most likely cause is a lost connection. Closes the socket so that
567 we can retry on the next event.
568 \end{methoddesc}
570 \begin{methoddesc}{makeSocket}{}
571 This is a factory method which allows subclasses to define the precise
572 type of socket they want. The default implementation creates a TCP
573 socket (\constant{socket.SOCK_STREAM}).
574 \end{methoddesc}
576 \begin{methoddesc}{makePickle}{record}
577 Pickles the record's attribute dictionary in binary format with a length
578 prefix, and returns it ready for transmission across the socket.
579 \end{methoddesc}
581 \begin{methoddesc}{send}{packet}
582 Send a pickled string \var{packet} to the socket. This function allows
583 for partial sends which can happen when the network is busy.
584 \end{methoddesc}
586 \subsubsection{DatagramHandler}
588 The \class{DatagramHandler} class inherits from \class{SocketHandler}
589 to support sending logging messages over UDP sockets.
591 \begin{classdesc}{DatagramHandler}{host, port}
592 Returns a new instance of the \class{DatagramHandler} class intended to
593 communicate with a remote machine whose address is given by \var{host}
594 and \var{port}.
595 \end{classdesc}
597 \begin{methoddesc}{emit}{}
598 Pickles the record's attribute dictionary and writes it to the socket in
599 binary format. If there is an error with the socket, silently drops the
600 packet.
601 To unpickle the record at the receiving end into a LogRecord, use the
602 \function{makeLogRecord} function.
603 \end{methoddesc}
605 \begin{methoddesc}{makeSocket}{}
606 The factory method of \class{SocketHandler} is here overridden to create
607 a UDP socket (\constant{socket.SOCK_DGRAM}).
608 \end{methoddesc}
610 \begin{methoddesc}{send}{s}
611 Send a pickled string to a socket.
612 \end{methoddesc}
614 \subsubsection{SysLogHandler}
616 The \class{SysLogHandler} class supports sending logging messages to a
617 remote or local \UNIX{} syslog.
619 \begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}}
620 Returns a new instance of the \class{SysLogHandler} class intended to
621 communicate with a remote \UNIX{} machine whose address is given by
622 \var{address} in the form of a \code{(\var{host}, \var{port})}
623 tuple. If \var{address} is not specified, \code{('localhost', 514)} is
624 used. The address is used to open a UDP socket. If \var{facility} is
625 not specified, \constant{LOG_USER} is used.
626 \end{classdesc}
628 \begin{methoddesc}{close}{}
629 Closes the socket to the remote host.
630 \end{methoddesc}
632 \begin{methoddesc}{emit}{record}
633 The record is formatted, and then sent to the syslog server. If
634 exception information is present, it is \emph{not} sent to the server.
635 \end{methoddesc}
637 \begin{methoddesc}{encodePriority}{facility, priority}
638 Encodes the facility and priority into an integer. You can pass in strings
639 or integers - if strings are passed, internal mapping dictionaries are used
640 to convert them to integers.
641 \end{methoddesc}
643 \subsubsection{NTEventLogHandler}
645 The \class{NTEventLogHandler} class supports sending logging messages
646 to a local Windows NT, Windows 2000 or Windows XP event log. Before
647 you can use it, you need Mark Hammond's Win32 extensions for Python
648 installed.
650 \begin{classdesc}{NTEventLogHandler}{appname\optional{,
651 dllname\optional{, logtype}}}
652 Returns a new instance of the \class{NTEventLogHandler} class. The
653 \var{appname} is used to define the application name as it appears in the
654 event log. An appropriate registry entry is created using this name.
655 The \var{dllname} should give the fully qualified pathname of a .dll or .exe
656 which contains message definitions to hold in the log (if not specified,
657 \code{'win32service.pyd'} is used - this is installed with the Win32
658 extensions and contains some basic placeholder message definitions.
659 Note that use of these placeholders will make your event logs big, as the
660 entire message source is held in the log. If you want slimmer logs, you have
661 to pass in the name of your own .dll or .exe which contains the message
662 definitions you want to use in the event log). The \var{logtype} is one of
663 \code{'Application'}, \code{'System'} or \code{'Security'}, and
664 defaults to \code{'Application'}.
665 \end{classdesc}
667 \begin{methoddesc}{close}{}
668 At this point, you can remove the application name from the registry as a
669 source of event log entries. However, if you do this, you will not be able
670 to see the events as you intended in the Event Log Viewer - it needs to be
671 able to access the registry to get the .dll name. The current version does
672 not do this (in fact it doesn't do anything).
673 \end{methoddesc}
675 \begin{methoddesc}{emit}{record}
676 Determines the message ID, event category and event type, and then logs the
677 message in the NT event log.
678 \end{methoddesc}
680 \begin{methoddesc}{getEventCategory}{record}
681 Returns the event category for the record. Override this if you
682 want to specify your own categories. This version returns 0.
683 \end{methoddesc}
685 \begin{methoddesc}{getEventType}{record}
686 Returns the event type for the record. Override this if you want
687 to specify your own types. This version does a mapping using the
688 handler's typemap attribute, which is set up in \method{__init__()}
689 to a dictionary which contains mappings for \constant{DEBUG},
690 \constant{INFO}, \constant{WARNING}, \constant{ERROR} and
691 \constant{CRITICAL}. If you are using your own levels, you will either need
692 to override this method or place a suitable dictionary in the
693 handler's \var{typemap} attribute.
694 \end{methoddesc}
696 \begin{methoddesc}{getMessageID}{record}
697 Returns the message ID for the record. If you are using your
698 own messages, you could do this by having the \var{msg} passed to the
699 logger being an ID rather than a format string. Then, in here,
700 you could use a dictionary lookup to get the message ID. This
701 version returns 1, which is the base message ID in
702 \file{win32service.pyd}.
703 \end{methoddesc}
705 \subsubsection{SMTPHandler}
707 The \class{SMTPHandler} class supports sending logging messages to an email
708 address via SMTP.
710 \begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
711 Returns a new instance of the \class{SMTPHandler} class. The
712 instance is initialized with the from and to addresses and subject
713 line of the email. The \var{toaddrs} should be a list of strings without
714 domain names (That's what the \var{mailhost} is for). To specify a
715 non-standard SMTP port, use the (host, port) tuple format for the
716 \var{mailhost} argument. If you use a string, the standard SMTP port
717 is used.
718 \end{classdesc}
720 \begin{methoddesc}{emit}{record}
721 Formats the record and sends it to the specified addressees.
722 \end{methoddesc}
724 \begin{methoddesc}{getSubject}{record}
725 If you want to specify a subject line which is record-dependent,
726 override this method.
727 \end{methoddesc}
729 \subsubsection{MemoryHandler}
731 The \class{MemoryHandler} supports buffering of logging records in memory,
732 periodically flushing them to a \dfn{target} handler. Flushing occurs
733 whenever the buffer is full, or when an event of a certain severity or
734 greater is seen.
736 \class{MemoryHandler} is a subclass of the more general
737 \class{BufferingHandler}, which is an abstract class. This buffers logging
738 records in memory. Whenever each record is added to the buffer, a
739 check is made by calling \method{shouldFlush()} to see if the buffer
740 should be flushed. If it should, then \method{flush()} is expected to
741 do the needful.
743 \begin{classdesc}{BufferingHandler}{capacity}
744 Initializes the handler with a buffer of the specified capacity.
745 \end{classdesc}
747 \begin{methoddesc}{emit}{record}
748 Appends the record to the buffer. If \method{shouldFlush()} returns true,
749 calls \method{flush()} to process the buffer.
750 \end{methoddesc}
752 \begin{methoddesc}{flush}{}
753 You can override this to implement custom flushing behavior. This version
754 just zaps the buffer to empty.
755 \end{methoddesc}
757 \begin{methoddesc}{shouldFlush}{record}
758 Returns true if the buffer is up to capacity. This method can be
759 overridden to implement custom flushing strategies.
760 \end{methoddesc}
762 \begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
763 \optional{, target}}}
764 Returns a new instance of the \class{MemoryHandler} class. The
765 instance is initialized with a buffer size of \var{capacity}. If
766 \var{flushLevel} is not specified, \constant{ERROR} is used. If no
767 \var{target} is specified, the target will need to be set using
768 \method{setTarget()} before this handler does anything useful.
769 \end{classdesc}
771 \begin{methoddesc}{close}{}
772 Calls \method{flush()}, sets the target to \constant{None} and
773 clears the buffer.
774 \end{methoddesc}
776 \begin{methoddesc}{flush}{}
777 For a \class{MemoryHandler}, flushing means just sending the buffered
778 records to the target, if there is one. Override if you want
779 different behavior.
780 \end{methoddesc}
782 \begin{methoddesc}{setTarget}{target}
783 Sets the target handler for this handler.
784 \end{methoddesc}
786 \begin{methoddesc}{shouldFlush}{record}
787 Checks for buffer full or a record at the \var{flushLevel} or higher.
788 \end{methoddesc}
790 \subsubsection{HTTPHandler}
792 The \class{HTTPHandler} class supports sending logging messages to a
793 Web server, using either \samp{GET} or \samp{POST} semantics.
795 \begin{classdesc}{HTTPHandler}{host, url\optional{, method}}
796 Returns a new instance of the \class{HTTPHandler} class. The
797 instance is initialized with a host address, url and HTTP method.
798 If no \var{method} is specified, \samp{GET} is used.
799 \end{classdesc}
801 \begin{methoddesc}{emit}{record}
802 Sends the record to the Web server as an URL-encoded dictionary.
803 \end{methoddesc}
805 \subsection{Formatter Objects}
807 \class{Formatter}s have the following attributes and methods. They are
808 responsible for converting a \class{LogRecord} to (usually) a string
809 which can be interpreted by either a human or an external system. The
810 base
811 \class{Formatter} allows a formatting string to be specified. If none is
812 supplied, the default value of \code{'\%(message)s\e'} is used.
814 A Formatter can be initialized with a format string which makes use of
815 knowledge of the \class{LogRecord} attributes - such as the default value
816 mentioned above making use of the fact that the user's message and
817 arguments are pre-formatted into a LogRecord's \var{message}
818 attribute. This format string contains standard python \%-style
819 mapping keys. See section \ref{typesseq-strings}, ``String Formatting
820 Operations,'' for more information on string formatting.
822 Currently, the useful mapping keys in a LogRecord are:
824 \begin{tableii}{l|l}{code}{Format}{Description}
825 \lineii{\%(name)s} {Name of the logger (logging channel).}
826 \lineii{\%(levelno)s} {Numeric logging level for the message
827 (\constant{DEBUG}, \constant{INFO},
828 \constant{WARNING}, \constant{ERROR},
829 \constant{CRITICAL}).}
830 \lineii{\%(levelname)s}{Text logging level for the message
831 (\code{'DEBUG'}, \code{'INFO'},
832 \code{'WARNING'}, \code{'ERROR'},
833 \code{'CRITICAL'}).}
834 \lineii{\%(pathname)s} {Full pathname of the source file where the logging
835 call was issued (if available).}
836 \lineii{\%(filename)s} {Filename portion of pathname.}
837 \lineii{\%(module)s} {Module (name portion of filename).}
838 \lineii{\%(lineno)d} {Source line number where the logging call was issued
839 (if available).}
840 \lineii{\%(created)f} {Time when the LogRecord was created (as
841 returned by \function{time.time()}).}
842 \lineii{\%(asctime)s} {Human-readable time when the LogRecord was created.
843 By default this is of the form
844 ``2003-07-08 16:49:45,896'' (the numbers after the
845 comma are millisecond portion of the time).}
846 \lineii{\%(msecs)d} {Millisecond portion of the time when the
847 \class{LogRecord} was created.}
848 \lineii{\%(thread)d} {Thread ID (if available).}
849 \lineii{\%(process)d} {Process ID (if available).}
850 \lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}
851 \end{tableii}
853 \begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
854 Returns a new instance of the \class{Formatter} class. The
855 instance is initialized with a format string for the message as a whole,
856 as well as a format string for the date/time portion of a message. If
857 no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}
858 is specified, the ISO8601 date format is used.
859 \end{classdesc}
861 \begin{methoddesc}{format}{record}
862 The record's attribute dictionary is used as the operand to a
863 string formatting operation. Returns the resulting string.
864 Before formatting the dictionary, a couple of preparatory steps
865 are carried out. The \var{message} attribute of the record is computed
866 using \var{msg} \% \var{args}. If the formatting string contains
867 \code{'(asctime)'}, \method{formatTime()} is called to format the
868 event time. If there is exception information, it is formatted using
869 \method{formatException()} and appended to the message.
870 \end{methoddesc}
872 \begin{methoddesc}{formatTime}{record\optional{, datefmt}}
873 This method should be called from \method{format()} by a formatter which
874 wants to make use of a formatted time. This method can be overridden
875 in formatters to provide for any specific requirement, but the
876 basic behavior is as follows: if \var{datefmt} (a string) is specified,
877 it is used with \function{time.strftime()} to format the creation time of the
878 record. Otherwise, the ISO8601 format is used. The resulting
879 string is returned.
880 \end{methoddesc}
882 \begin{methoddesc}{formatException}{exc_info}
883 Formats the specified exception information (a standard exception tuple
884 as returned by \function{sys.exc_info()}) as a string. This default
885 implementation just uses \function{traceback.print_exception()}.
886 The resulting string is returned.
887 \end{methoddesc}
889 \subsection{Filter Objects}
891 \class{Filter}s can be used by \class{Handler}s and \class{Logger}s for
892 more sophisticated filtering than is provided by levels. The base filter
893 class only allows events which are below a certain point in the logger
894 hierarchy. For example, a filter initialized with "A.B" will allow events
895 logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB",
896 "B.A.B" etc. If initialized with the empty string, all events are passed.
898 \begin{classdesc}{Filter}{\optional{name}}
899 Returns an instance of the \class{Filter} class. If \var{name} is specified,
900 it names a logger which, together with its children, will have its events
901 allowed through the filter. If no name is specified, allows every event.
902 \end{classdesc}
904 \begin{methoddesc}{filter}{record}
905 Is the specified record to be logged? Returns zero for no, nonzero for
906 yes. If deemed appropriate, the record may be modified in-place by this
907 method.
908 \end{methoddesc}
910 \subsection{LogRecord Objects}
912 LogRecord instances are created every time something is logged. They
913 contain all the information pertinent to the event being logged. The
914 main information passed in is in msg and args, which are combined
915 using msg \% args to create the message field of the record. The record
916 also includes information such as when the record was created, the
917 source line where the logging call was made, and any exception
918 information to be logged.
920 LogRecord has no methods; it's just a repository for information about the
921 logging event. The only reason it's a class rather than a dictionary is to
922 facilitate extension.
924 \begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
925 exc_info}
926 Returns an instance of \class{LogRecord} initialized with interesting
927 information. The \var{name} is the logger name; \var{lvl} is the
928 numeric level; \var{pathname} is the absolute pathname of the source
929 file in which the logging call was made; \var{lineno} is the line
930 number in that file where the logging call is found; \var{msg} is the
931 user-supplied message (a format string); \var{args} is the tuple
932 which, together with \var{msg}, makes up the user message; and
933 \var{exc_info} is the exception tuple obtained by calling
934 \function{sys.exc_info() }(or \constant{None}, if no exception information
935 is available).
936 \end{classdesc}
938 \subsection{Thread Safety}
940 The logging module is intended to be thread-safe without any special work
941 needing to be done by its clients. It achieves this though using threading
942 locks; there is one lock to serialize access to the module's shared data,
943 and each handler also creates a lock to serialize access to its underlying
944 I/O.
946 \subsection{Configuration}
949 \subsubsection{Configuration functions}
951 The following functions allow the logging module to be
952 configured. Before they can be used, you must import
953 \module{logging.config}. Their use is optional --- you can configure
954 the logging module entirely by making calls to the main API (defined
955 in \module{logging} itself) and defining handlers which are declared
956 either in \module{logging} or \module{logging.handlers}.
958 \begin{funcdesc}{fileConfig}{fname\optional{, defaults}}
959 Reads the logging configuration from a ConfigParser-format file named
960 \var{fname}. This function can be called several times from an application,
961 allowing an end user the ability to select from various pre-canned
962 configurations (if the developer provides a mechanism to present the
963 choices and load the chosen configuration). Defaults to be passed to
964 ConfigParser can be specified in the \var{defaults} argument.
965 \end{funcdesc}
967 \begin{funcdesc}{listen}{\optional{port}}
968 Starts up a socket server on the specified port, and listens for new
969 configurations. If no port is specified, the module's default
970 \constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations
971 will be sent as a file suitable for processing by \function{fileConfig()}.
972 Returns a \class{Thread} instance on which you can call \method{start()}
973 to start the server, and which you can \method{join()} when appropriate.
974 To stop the server, call \function{stopListening()}.
975 \end{funcdesc}
977 \begin{funcdesc}{stopListening}{}
978 Stops the listening server which was created with a call to
979 \function{listen()}. This is typically called before calling \method{join()}
980 on the return value from \function{listen()}.
981 \end{funcdesc}
983 \subsubsection{Configuration file format}
985 The configuration file format understood by \function{fileConfig} is
986 based on ConfigParser functionality. The file must contain sections
987 called \code{[loggers]}, \code{[handlers]} and \code{[formatters]}
988 which identify by name the entities of each type which are defined in
989 the file. For each such entity, there is a separate section which
990 identified how that entity is configured. Thus, for a logger named
991 \code{log01} in the \code{[loggers]} section, the relevant
992 configuration details are held in a section
993 \code{[logger_log01]}. Similarly, a handler called \code{hand01} in
994 the \code{[handlers]} section will have its configuration held in a
995 section called \code{[handler_hand01]}, while a formatter called
996 \code{form01} in the \code{[formatters]} section will have its
997 configuration specified in a section called
998 \code{[formatter_form01]}. The root logger configuration must be
999 specified in a section called \code{[logger_root]}.
1001 Examples of these sections in the file are given below.
1003 \begin{verbatim}
1004 [loggers]
1005 keys=root,log02,log03,log04,log05,log06,log07
1007 [handlers]
1008 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
1010 [formatters]
1011 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
1012 \end{verbatim}
1014 The root logger must specify a level and a list of handlers. An
1015 example of a root logger section is given below.
1017 \begin{verbatim}
1018 [logger_root]
1019 level=NOTSET
1020 handlers=hand01
1021 \end{verbatim}
1023 The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,
1024 ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,
1025 \code{NOTSET} means that all messages will be logged. Level values are
1026 \function{eval()}uated in the context of the \code{logging} package's
1027 namespace.
1029 The \code{handlers} entry is a comma-separated list of handler names,
1030 which must appear in the \code{[handlers]} section. These names must
1031 appear in the \code{[handlers]} section and have corresponding
1032 sections in the configuration file.
1034 For loggers other than the root logger, some additional information is
1035 required. This is illustrated by the following example.
1037 \begin{verbatim}
1038 [logger_parser]
1039 level=DEBUG
1040 handlers=hand01
1041 propagate=1
1042 qualname=compiler.parser
1043 \end{verbatim}
1045 The \code{level} and \code{handlers} entries are interpreted as for
1046 the root logger, except that if a non-root logger's level is specified
1047 as \code{NOTSET}, the system consults loggers higher up the hierarchy
1048 to determine the effective level of the logger. The \code{propagate}
1049 entry is set to 1 to indicate that messages must propagate to handlers
1050 higher up the logger hierarchy from this logger, or 0 to indicate that
1051 messages are \strong{not} propagated to handlers up the hierarchy. The
1052 \code{qualname} entry is the hierarchical channel name of the logger,
1053 that is to say the name used by the application to get the logger.
1055 Sections which specify handler configuration are exemplified by the
1056 following.
1058 \begin{verbatim}
1059 [handler_hand01]
1060 class=StreamHandler
1061 level=NOTSET
1062 formatter=form01
1063 args=(sys.stdout,)
1064 \end{verbatim}
1066 The \code{class} entry indicates the handler's class (as determined by
1067 \function{eval()} in the \code{logging} package's namespace). The
1068 \code{level} is interpreted as for loggers, and \code{NOTSET} is taken
1069 to mean "log everything".
1071 The \code{formatter} entry indicates the key name of the formatter for
1072 this handler. If blank, a default formatter
1073 (\code{logging._defaultFormatter}) is used. If a name is specified, it
1074 must appear in the \code{[formatters]} section and have a
1075 corresponding section in the configuration file.
1077 The \code{args} entry, when \function{eval()}uated in the context of
1078 the \code{logging} package's namespace, is the list of arguments to
1079 the constructor for the handler class. Refer to the constructors for
1080 the relevant handlers, or to the examples below, to see how typical
1081 entries are constructed.
1083 \begin{verbatim}
1084 [handler_hand02]
1085 class=FileHandler
1086 level=DEBUG
1087 formatter=form02
1088 args=('python.log', 'w')
1090 [handler_hand03]
1091 class=handlers.SocketHandler
1092 level=INFO
1093 formatter=form03
1094 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
1096 [handler_hand04]
1097 class=handlers.DatagramHandler
1098 level=WARN
1099 formatter=form04
1100 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
1102 [handler_hand05]
1103 class=handlers.SysLogHandler
1104 level=ERROR
1105 formatter=form05
1106 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
1108 [handler_hand06]
1109 class=NTEventLogHandler
1110 level=CRITICAL
1111 formatter=form06
1112 args=('Python Application', '', 'Application')
1114 [handler_hand07]
1115 class=SMTPHandler
1116 level=WARN
1117 formatter=form07
1118 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
1120 [handler_hand08]
1121 class=MemoryHandler
1122 level=NOTSET
1123 formatter=form08
1124 target=
1125 args=(10, ERROR)
1127 [handler_hand09]
1128 class=HTTPHandler
1129 level=NOTSET
1130 formatter=form09
1131 args=('localhost:9022', '/log', 'GET')
1132 \end{verbatim}
1134 Sections which specify formatter configuration are typified by the following.
1136 \begin{verbatim}
1137 [formatter_form01]
1138 format=F1 %(asctime)s %(levelname)s %(message)s
1139 datefmt=
1140 \end{verbatim}
1142 The \code{format} entry is the overall format string, and the
1143 \code{datefmt} entry is the \function{strftime()}-compatible date/time format
1144 string. If empty, the package substitutes ISO8601 format date/times, which
1145 is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".
1146 The ISO8601 format also specifies milliseconds, which are appended to the
1147 result of using the above format string, with a comma separator. An example
1148 time in ISO8601 format is \code{2003-01-23 00:29:50,411}.
1150 \subsection{Using the logging package}
1152 \subsubsection{Simplest usage}
1154 Here's a simple example which shows the most casual usage of the logging
1155 package.
1157 \begin{verbatim}
1158 import logging
1159 logging.debug("Houston, we have a %s", "thorny problem")
1160 logging.info("Houston, we have a %s", "interesting problem")
1161 logging.warning("Houston, we have a %s", "bit of a problem")
1162 logging.error("Houston, we have a %s", "major problem")
1163 logging.critical("Houston, we have a %s", "major disaster")
1164 try:
1165 infinity = 1 / 0
1166 except:
1167 logging.exception("Houston, we have an %s", "unexpected problem")
1168 \end{verbatim}
1170 If you run the above example, this will produce:
1172 \begin{verbatim}
1173 WARNING:root:Houston, we have a bit of a problem
1174 ERROR:root:Houston, we have a major problem
1175 CRITICAL:root:Houston, we have a major disaster
1176 ERROR:root:Houston, we have an unexpected problem
1177 Traceback (most recent call last):
1178 File "C:\Projects\RDC\Python\packages\logging\test\tmp.py", line 8, in ?
1179 infinity = 1 / 0
1180 ZeroDivisionError: integer division or modulo by zero
1181 \end{verbatim}
1183 The reason you get this output is that the default format is
1185 \begin{verbatim}
1186 "%(levelname)s:%(name)s:%(message)s".
1187 \end{verbatim}
1189 When you invoke functions \function{info()}, \function{warning()} etc. in the
1190 logging package itself, these calls are delegated to the correspondingly
1191 named methods in the root logger. This is why the logger name shown in the above
1192 logging output is "root". If the root logger has no handlers configured, the
1193 logging package creates a console handler and adds it to the root logger
1194 automatically. (It does this by calling the \function{basicConfig()}, which you
1195 can also call directly from your own code.)
1197 By default, events with a severity below WARNING are suppressed. Notice
1198 that the \function{exception()} function acts like \function{error()}, except
1199 that a traceback is appended to the log entry.
1201 \subsubsection{Logging to the console}
1203 Here's a simple example which logs all messages to the console. We use a named
1204 logger:
1206 \begin{verbatim}
1207 import logging
1208 logging.basicConfig()
1209 logger = logging.getLogger('myapp')
1210 logger.setLevel(logging.DEBUG)
1211 logger.debug("Houston, we have a %s", "thorny problem")
1212 logger.info("Houston, we have a %s", "interesting problem")
1213 logger.warning("Houston, we have a %s", "bit of a problem")
1214 logger.error("Houston, we have a %s", "major problem")
1215 logger.critical("Houston, we have a %s", "major disaster")
1216 try:
1217 infinity = 1 / 0
1218 except:
1219 logger.exception("Houston, we have an %s", "unexpected problem")
1220 \end{verbatim}
1222 Here's the corresponding output:
1224 \begin{verbatim}
1225 DEBUG:myapp:Houston, we have a thorny problem
1226 INFO:myapp:Houston, we have a interesting problem
1227 WARNING:myapp:Houston, we have a bit of a problem
1228 ERROR:myapp:Houston, we have a major problem
1229 CRITICAL:myapp:Houston, we have a major disaster
1230 ERROR:myapp:Houston, we have an unexpected problem
1231 Traceback (most recent call last):
1232 File "C:\Projects\RDC\Python\packages\logging\test\tmp.py", line 11, in ?
1233 infinity = 1 / 0
1234 ZeroDivisionError: integer division or modulo by zero
1235 \end{verbatim}
1237 As you can see, the specified logger name now appears in the output, and
1238 DEBUG and INFO messages are included in the output because we explicitly
1239 asked for them via the call to \method{setLevel()}.
1241 \subsubsection{Logging to a file}
1243 Here's a simple logging example that just logs to a file. In order,
1244 it creates a \class{Logger} instance, then a \class{FileHandler}
1245 and a \class{Formatter}. It attaches the \class{Formatter} to the
1246 \class{FileHandler}, then the \class{FileHandler} to the \class{Logger}.
1247 Finally, it sets a debug level for the logger.
1249 \begin{verbatim}
1250 import logging
1251 logger = logging.getLogger('myapp')
1252 hdlr = logging.FileHandler('/var/tmp/myapp.log')
1253 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
1254 hdlr.setFormatter(formatter)
1255 logger.addHandler(hdlr)
1256 logger.setLevel(logging.WARNING)
1257 \end{verbatim}
1259 We can use this logger object now to write entries to the log file:
1261 \begin{verbatim}
1262 logger.error('We have a problem')
1263 logger.info('While this is just chatty')
1264 \end{verbatim}
1266 If we look in the file that was created, we'll see something like this:
1267 \begin{verbatim}
1268 2003-07-08 16:49:45,896 ERROR We have a problem
1269 \end{verbatim}
1271 The info message was not written to the file - we called the \method{setLevel}
1272 method to say we only wanted \code{WARNING} or worse, so the info message is
1273 discarded.
1275 The timestamp is of the form
1276 ``year-month-day hour:minutes:seconds,milliseconds.''
1277 Note that despite the three digits of precision in the milliseconds field,
1278 not all systems provide time with this much precision.
1280 \subsubsection{Logging to a rotating set of files}