Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1 | \section{\module{logging} --- |
| 2 | Logging facility for Python} |
| 3 | |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 4 | \declaremodule{standard}{logging} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 5 | |
| 6 | % These apply to all modules, and may be given more than once: |
| 7 | |
| 8 | \moduleauthor{Vinay Sajip}{vinay_sajip@red-dove.com} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 9 | \sectionauthor{Vinay Sajip}{vinay_sajip@red-dove.com} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 10 | |
Fred Drake | 68e6d57 | 2003-01-28 22:02:35 +0000 | [diff] [blame] | 11 | \modulesynopsis{Logging module for Python based on \pep{282}.} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 12 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 13 | \indexii{Errors}{logging} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 14 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 15 | \versionadded{2.3} |
| 16 | This module defines functions and classes which implement a flexible |
| 17 | error logging system for applications. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 18 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 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. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 26 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 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 |
Fred Drake | c23e019 | 2003-01-28 22:09:16 +0000 | [diff] [blame] | 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 |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 36 | explicit level argument. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 37 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 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. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 45 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 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. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 49 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 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 |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 55 | that message (such as end users, support desk staff, system administrators, |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 56 | developers). Handlers are passed \class{LogRecord} instances intended for |
| 57 | particular destinations. Each logger can have zero, one or more handlers |
Fred Drake | 6b3b046 | 2004-04-09 18:26:40 +0000 | [diff] [blame] | 58 | associated with it (via the \method{addHandler()} method of \class{Logger}). |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 59 | In addition to any handlers directly associated with a logger, |
Fred Drake | c23e019 | 2003-01-28 22:09:16 +0000 | [diff] [blame] | 60 | \emph{all handlers associated with all ancestors of the logger} are |
| 61 | called to dispatch the message. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 62 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 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. |
Fred Drake | c23e019 | 2003-01-28 22:09:16 +0000 | [diff] [blame] | 65 | If a handler decides to actually dispatch an event, the \method{emit()} method |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 66 | is used to send the message to its destination. Most user-defined subclasses |
Fred Drake | c23e019 | 2003-01-28 22:09:16 +0000 | [diff] [blame] | 67 | of \class{Handler} will need to override this \method{emit()}. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 68 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 69 | In addition to the base \class{Handler} class, many useful subclasses |
| 70 | are provided: |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 71 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 72 | \begin{enumerate} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 73 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 74 | \item \class{StreamHandler} instances send error messages to |
| 75 | streams (file-like objects). |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 76 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 77 | \item \class{FileHandler} instances send error messages to disk |
| 78 | files. |
| 79 | |
Johannes Gijsbers | f164322 | 2004-11-07 16:11:35 +0000 | [diff] [blame] | 80 | \item \class{BaseRotatingHandler} is tha base class for handlers that |
| 81 | rotate log files at a certain point. It is not meant to be instantiated |
Vinay Sajip | edde492 | 2004-11-11 13:54:48 +0000 | [diff] [blame] | 82 | directly. Instead, use \class{RotatingFileHandler} or |
| 83 | \class{TimedRotatingFileHandler}. |
Johannes Gijsbers | f164322 | 2004-11-07 16:11:35 +0000 | [diff] [blame] | 84 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 85 | \item \class{RotatingFileHandler} instances send error messages to disk |
| 86 | files, with support for maximum log file sizes and log file rotation. |
| 87 | |
Johannes Gijsbers | 4f802ac | 2004-11-07 14:14:27 +0000 | [diff] [blame] | 88 | \item \class{TimedRotatingFileHandler} instances send error messages to |
| 89 | disk files rotating the log file at certain timed intervals. |
| 90 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 91 | \item \class{SocketHandler} instances send error messages to |
| 92 | TCP/IP sockets. |
| 93 | |
| 94 | \item \class{DatagramHandler} instances send error messages to UDP |
| 95 | sockets. |
| 96 | |
| 97 | \item \class{SMTPHandler} instances send error messages to a |
| 98 | designated email address. |
| 99 | |
| 100 | \item \class{SysLogHandler} instances send error messages to a |
Fred Drake | 68e6d57 | 2003-01-28 22:02:35 +0000 | [diff] [blame] | 101 | \UNIX{} syslog daemon, possibly on a remote machine. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 102 | |
| 103 | \item \class{NTEventLogHandler} instances send error messages to a |
| 104 | Windows NT/2000/XP event log. |
| 105 | |
| 106 | \item \class{MemoryHandler} instances send error messages to a |
| 107 | buffer in memory, which is flushed whenever specific criteria are |
| 108 | met. |
| 109 | |
| 110 | \item \class{HTTPHandler} instances send error messages to an |
Fred Drake | 68e6d57 | 2003-01-28 22:02:35 +0000 | [diff] [blame] | 111 | HTTP server using either \samp{GET} or \samp{POST} semantics. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 112 | |
| 113 | \end{enumerate} |
| 114 | |
| 115 | The \class{StreamHandler} and \class{FileHandler} classes are defined |
| 116 | in the core logging package. The other handlers are defined in a sub- |
| 117 | module, \module{logging.handlers}. (There is also another sub-module, |
| 118 | \module{logging.config}, for configuration functionality.) |
| 119 | |
| 120 | Logged messages are formatted for presentation through instances of the |
| 121 | \class{Formatter} class. They are initialized with a format string |
| 122 | suitable for use with the \% operator and a dictionary. |
| 123 | |
| 124 | For formatting multiple messages in a batch, instances of |
| 125 | \class{BufferingFormatter} can be used. In addition to the format string |
| 126 | (which is applied to each message in the batch), there is provision for |
| 127 | header and trailer format strings. |
| 128 | |
| 129 | When filtering based on logger level and/or handler level is not enough, |
| 130 | instances of \class{Filter} can be added to both \class{Logger} and |
Fred Drake | c23e019 | 2003-01-28 22:09:16 +0000 | [diff] [blame] | 131 | \class{Handler} instances (through their \method{addFilter()} method). |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 132 | Before deciding to process a message further, both loggers and handlers |
| 133 | consult all their filters for permission. If any filter returns a false |
| 134 | value, the message is not processed further. |
| 135 | |
| 136 | The basic \class{Filter} functionality allows filtering by specific logger |
| 137 | name. If this feature is used, messages sent to the named logger and its |
| 138 | children are allowed through the filter, and all others dropped. |
| 139 | |
| 140 | In addition to the classes described above, there are a number of module- |
| 141 | level functions. |
| 142 | |
| 143 | \begin{funcdesc}{getLogger}{\optional{name}} |
| 144 | Return a logger with the specified name or, if no name is specified, return |
Vinay Sajip | 17952b7 | 2004-08-31 10:21:51 +0000 | [diff] [blame] | 145 | a logger which is the root logger of the hierarchy. If specified, the name |
| 146 | is typically a dot-separated hierarchical name like \var{"a"}, \var{"a.b"} |
| 147 | or \var{"a.b.c.d"}. Choice of these names is entirely up to the developer |
| 148 | who is using logging. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 149 | |
| 150 | All calls to this function with a given name return the same logger instance. |
| 151 | This means that logger instances never need to be passed between different |
| 152 | parts of an application. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 153 | \end{funcdesc} |
| 154 | |
Vinay Sajip | c6646c0 | 2004-09-22 12:55:16 +0000 | [diff] [blame] | 155 | \begin{funcdesc}{getLoggerClass}{} |
| 156 | Return either the standard \class{Logger} class, or the last class passed to |
| 157 | \function{setLoggerClass()}. This function may be called from within a new |
| 158 | class definition, to ensure that installing a customised \class{Logger} class |
| 159 | will not undo customisations already applied by other code. For example: |
| 160 | |
| 161 | \begin{verbatim} |
| 162 | class MyLogger(logging.getLoggerClass()): |
| 163 | # ... override behaviour here |
| 164 | \end{verbatim} |
| 165 | |
| 166 | \end{funcdesc} |
| 167 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 168 | \begin{funcdesc}{debug}{msg\optional{, *args\optional{, **kwargs}}} |
| 169 | Logs a message with level \constant{DEBUG} on the root logger. |
| 170 | The \var{msg} is the message format string, and the \var{args} are the |
| 171 | arguments which are merged into \var{msg}. The only keyword argument in |
| 172 | \var{kwargs} which is inspected is \var{exc_info} which, if it does not |
Vinay Sajip | 1dc5b1e | 2004-10-03 19:10:05 +0000 | [diff] [blame] | 173 | evaluate as false, causes exception information to be added to the logging |
| 174 | message. If an exception tuple (in the format returned by |
| 175 | \function{sys.exc_info()}) is provided, it is used; otherwise, |
| 176 | \function{sys.exc_info()} is called to get the exception information. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 177 | \end{funcdesc} |
| 178 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 179 | \begin{funcdesc}{info}{msg\optional{, *args\optional{, **kwargs}}} |
| 180 | Logs a message with level \constant{INFO} on the root logger. |
| 181 | The arguments are interpreted as for \function{debug()}. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 182 | \end{funcdesc} |
| 183 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 184 | \begin{funcdesc}{warning}{msg\optional{, *args\optional{, **kwargs}}} |
| 185 | Logs a message with level \constant{WARNING} on the root logger. |
| 186 | The arguments are interpreted as for \function{debug()}. |
| 187 | \end{funcdesc} |
| 188 | |
| 189 | \begin{funcdesc}{error}{msg\optional{, *args\optional{, **kwargs}}} |
| 190 | Logs a message with level \constant{ERROR} on the root logger. |
| 191 | The arguments are interpreted as for \function{debug()}. |
| 192 | \end{funcdesc} |
| 193 | |
| 194 | \begin{funcdesc}{critical}{msg\optional{, *args\optional{, **kwargs}}} |
| 195 | Logs a message with level \constant{CRITICAL} on the root logger. |
| 196 | The arguments are interpreted as for \function{debug()}. |
| 197 | \end{funcdesc} |
| 198 | |
| 199 | \begin{funcdesc}{exception}{msg\optional{, *args}} |
| 200 | Logs a message with level \constant{ERROR} on the root logger. |
| 201 | The arguments are interpreted as for \function{debug()}. Exception info |
| 202 | is added to the logging message. This function should only be called |
| 203 | from an exception handler. |
| 204 | \end{funcdesc} |
| 205 | |
Vinay Sajip | 739d49e | 2004-09-24 11:46:44 +0000 | [diff] [blame] | 206 | \begin{funcdesc}{log}{level, msg\optional{, *args\optional{, **kwargs}}} |
| 207 | Logs a message with level \var{level} on the root logger. |
| 208 | The other arguments are interpreted as for \function{debug()}. |
| 209 | \end{funcdesc} |
| 210 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 211 | \begin{funcdesc}{disable}{lvl} |
| 212 | Provides an overriding level \var{lvl} for all loggers which takes |
| 213 | precedence over the logger's own level. When the need arises to |
| 214 | temporarily throttle logging output down across the whole application, |
| 215 | this function can be useful. |
| 216 | \end{funcdesc} |
| 217 | |
| 218 | \begin{funcdesc}{addLevelName}{lvl, levelName} |
| 219 | Associates level \var{lvl} with text \var{levelName} in an internal |
| 220 | dictionary, which is used to map numeric levels to a textual |
| 221 | representation, for example when a \class{Formatter} formats a message. |
| 222 | This function can also be used to define your own levels. The only |
| 223 | constraints are that all levels used must be registered using this |
| 224 | function, levels should be positive integers and they should increase |
| 225 | in increasing order of severity. |
| 226 | \end{funcdesc} |
| 227 | |
| 228 | \begin{funcdesc}{getLevelName}{lvl} |
| 229 | Returns the textual representation of logging level \var{lvl}. If the |
| 230 | level is one of the predefined levels \constant{CRITICAL}, |
| 231 | \constant{ERROR}, \constant{WARNING}, \constant{INFO} or \constant{DEBUG} |
| 232 | then you get the corresponding string. If you have associated levels |
| 233 | with names using \function{addLevelName()} then the name you have associated |
Vinay Sajip | a13c60b | 2004-07-03 11:45:53 +0000 | [diff] [blame] | 234 | with \var{lvl} is returned. If a numeric value corresponding to one of the |
| 235 | defined levels is passed in, the corresponding string representation is |
| 236 | returned. Otherwise, the string "Level \%s" \% lvl is returned. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 237 | \end{funcdesc} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 238 | |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 239 | \begin{funcdesc}{makeLogRecord}{attrdict} |
| 240 | Creates and returns a new \class{LogRecord} instance whose attributes are |
| 241 | defined by \var{attrdict}. This function is useful for taking a pickled |
| 242 | \class{LogRecord} attribute dictionary, sent over a socket, and reconstituting |
| 243 | it as a \class{LogRecord} instance at the receiving end. |
| 244 | \end{funcdesc} |
| 245 | |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 246 | \begin{funcdesc}{basicConfig}{} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 247 | Does basic configuration for the logging system by creating a |
| 248 | \class{StreamHandler} with a default \class{Formatter} and adding it to |
| 249 | the root logger. The functions \function{debug()}, \function{info()}, |
| 250 | \function{warning()}, \function{error()} and \function{critical()} will call |
| 251 | \function{basicConfig()} automatically if no handlers are defined for the |
| 252 | root logger. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 253 | \end{funcdesc} |
| 254 | |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 255 | \begin{funcdesc}{shutdown}{} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 256 | Informs the logging system to perform an orderly shutdown by flushing and |
| 257 | closing all handlers. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 258 | \end{funcdesc} |
| 259 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 260 | \begin{funcdesc}{setLoggerClass}{klass} |
| 261 | Tells the logging system to use the class \var{klass} when instantiating a |
| 262 | logger. The class should define \method{__init__()} such that only a name |
| 263 | argument is required, and the \method{__init__()} should call |
| 264 | \method{Logger.__init__()}. This function is typically called before any |
| 265 | loggers are instantiated by applications which need to use custom logger |
| 266 | behavior. |
| 267 | \end{funcdesc} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 268 | |
Fred Drake | 68e6d57 | 2003-01-28 22:02:35 +0000 | [diff] [blame] | 269 | |
| 270 | \begin{seealso} |
| 271 | \seepep{282}{A Logging System} |
| 272 | {The proposal which described this feature for inclusion in |
| 273 | the Python standard library.} |
Fred Drake | 1151479 | 2004-01-08 14:59:02 +0000 | [diff] [blame] | 274 | \seelink{http://www.red-dove.com/python_logging.html} |
| 275 | {Original Python \module{logging} package} |
| 276 | {This is the original source for the \module{logging} |
| 277 | package. The version of the package available from this |
Vinay Sajip | a13c60b | 2004-07-03 11:45:53 +0000 | [diff] [blame] | 278 | site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x, |
| 279 | which do not include the \module{logging} package in the standard |
Fred Drake | 1151479 | 2004-01-08 14:59:02 +0000 | [diff] [blame] | 280 | library.} |
Fred Drake | 68e6d57 | 2003-01-28 22:02:35 +0000 | [diff] [blame] | 281 | \end{seealso} |
| 282 | |
| 283 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 284 | \subsection{Logger Objects} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 285 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 286 | Loggers have the following attributes and methods. Note that Loggers are |
| 287 | never instantiated directly, but always through the module-level function |
| 288 | \function{logging.getLogger(name)}. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 289 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 290 | \begin{datadesc}{propagate} |
| 291 | If this evaluates to false, logging messages are not passed by this |
| 292 | logger or by child loggers to higher level (ancestor) loggers. The |
| 293 | constructor sets this attribute to 1. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 294 | \end{datadesc} |
| 295 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 296 | \begin{methoddesc}{setLevel}{lvl} |
| 297 | Sets the threshold for this logger to \var{lvl}. Logging messages |
| 298 | which are less severe than \var{lvl} will be ignored. When a logger is |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 299 | created, the level is set to \constant{NOTSET} (which causes all messages |
| 300 | to be processed in the root logger, or delegation to the parent in non-root |
| 301 | loggers). |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 302 | \end{methoddesc} |
| 303 | |
| 304 | \begin{methoddesc}{isEnabledFor}{lvl} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 305 | Indicates if a message of severity \var{lvl} would be processed by |
| 306 | this logger. This method checks first the module-level level set by |
| 307 | \function{logging.disable(lvl)} and then the logger's effective level as |
| 308 | determined by \method{getEffectiveLevel()}. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 309 | \end{methoddesc} |
| 310 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 311 | \begin{methoddesc}{getEffectiveLevel}{} |
| 312 | Indicates the effective level for this logger. If a value other than |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 313 | \constant{NOTSET} has been set using \method{setLevel()}, it is returned. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 314 | Otherwise, the hierarchy is traversed towards the root until a value |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 315 | other than \constant{NOTSET} is found, and that value is returned. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 316 | \end{methoddesc} |
| 317 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 318 | \begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}} |
| 319 | Logs a message with level \constant{DEBUG} on this logger. |
| 320 | The \var{msg} is the message format string, and the \var{args} are the |
| 321 | arguments which are merged into \var{msg}. The only keyword argument in |
| 322 | \var{kwargs} which is inspected is \var{exc_info} which, if it does not |
Vinay Sajip | 1dc5b1e | 2004-10-03 19:10:05 +0000 | [diff] [blame] | 323 | evaluate as false, causes exception information to be added to the logging |
| 324 | message. If an exception tuple (as provided by \function{sys.exc_info()}) |
| 325 | is provided, it is used; otherwise, \function{sys.exc_info()} is called |
| 326 | to get the exception information. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 327 | \end{methoddesc} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 328 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 329 | \begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}} |
| 330 | Logs a message with level \constant{INFO} on this logger. |
| 331 | The arguments are interpreted as for \method{debug()}. |
| 332 | \end{methoddesc} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 333 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 334 | \begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}} |
| 335 | Logs a message with level \constant{WARNING} on this logger. |
| 336 | The arguments are interpreted as for \method{debug()}. |
| 337 | \end{methoddesc} |
| 338 | |
| 339 | \begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}} |
| 340 | Logs a message with level \constant{ERROR} on this logger. |
| 341 | The arguments are interpreted as for \method{debug()}. |
| 342 | \end{methoddesc} |
| 343 | |
| 344 | \begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}} |
| 345 | Logs a message with level \constant{CRITICAL} on this logger. |
| 346 | The arguments are interpreted as for \method{debug()}. |
| 347 | \end{methoddesc} |
| 348 | |
| 349 | \begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}} |
Vinay Sajip | 1cf56d0 | 2004-08-04 08:36:44 +0000 | [diff] [blame] | 350 | Logs a message with integer level \var{lvl} on this logger. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 351 | The other arguments are interpreted as for \method{debug()}. |
| 352 | \end{methoddesc} |
| 353 | |
| 354 | \begin{methoddesc}{exception}{msg\optional{, *args}} |
| 355 | Logs a message with level \constant{ERROR} on this logger. |
| 356 | The arguments are interpreted as for \method{debug()}. Exception info |
| 357 | is added to the logging message. This method should only be called |
| 358 | from an exception handler. |
| 359 | \end{methoddesc} |
| 360 | |
| 361 | \begin{methoddesc}{addFilter}{filt} |
| 362 | Adds the specified filter \var{filt} to this logger. |
| 363 | \end{methoddesc} |
| 364 | |
| 365 | \begin{methoddesc}{removeFilter}{filt} |
| 366 | Removes the specified filter \var{filt} from this logger. |
| 367 | \end{methoddesc} |
| 368 | |
| 369 | \begin{methoddesc}{filter}{record} |
| 370 | Applies this logger's filters to the record and returns a true value if |
| 371 | the record is to be processed. |
| 372 | \end{methoddesc} |
| 373 | |
| 374 | \begin{methoddesc}{addHandler}{hdlr} |
| 375 | Adds the specified handler \var{hdlr} to this logger. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 376 | \end{methoddesc} |
| 377 | |
| 378 | \begin{methoddesc}{removeHandler}{hdlr} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 379 | Removes the specified handler \var{hdlr} from this logger. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 380 | \end{methoddesc} |
| 381 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 382 | \begin{methoddesc}{findCaller}{} |
| 383 | Finds the caller's source filename and line number. Returns the filename |
| 384 | and line number as a 2-element tuple. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 385 | \end{methoddesc} |
| 386 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 387 | \begin{methoddesc}{handle}{record} |
| 388 | Handles a record by passing it to all handlers associated with this logger |
| 389 | and its ancestors (until a false value of \var{propagate} is found). |
| 390 | This method is used for unpickled records received from a socket, as well |
| 391 | as those created locally. Logger-level filtering is applied using |
| 392 | \method{filter()}. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 393 | \end{methoddesc} |
| 394 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 395 | \begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info} |
| 396 | This is a factory method which can be overridden in subclasses to create |
| 397 | specialized \class{LogRecord} instances. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 398 | \end{methoddesc} |
| 399 | |
Vinay Sajip | a13c60b | 2004-07-03 11:45:53 +0000 | [diff] [blame] | 400 | \subsection{Basic example \label{minimal-example}} |
| 401 | |
| 402 | The \module{logging} package provides a lot of flexibility, and its |
| 403 | configuration can appear daunting. This section demonstrates that simple |
| 404 | use of the logging package is possible. |
| 405 | |
| 406 | The simplest example shows logging to the console: |
| 407 | |
| 408 | \begin{verbatim} |
| 409 | import logging |
| 410 | |
| 411 | logging.debug('A debug message') |
| 412 | logging.info('Some information') |
| 413 | logging.warning('A shot across the bows') |
| 414 | \end{verbatim} |
| 415 | |
| 416 | If you run the above script, you'll see this: |
| 417 | \begin{verbatim} |
| 418 | WARNING:root:A shot across the bows |
| 419 | \end{verbatim} |
| 420 | |
| 421 | Because no particular logger was specified, the system used the root logger. |
| 422 | The debug and info messages didn't appear because by default, the root |
| 423 | logger is configured to only handle messages with a severity of WARNING |
| 424 | or above. The message format is also a configuration default, as is the output |
| 425 | destination of the messages - \code{sys.stderr}. The severity level, |
| 426 | the message format and destination can be easily changed, as shown in |
| 427 | the example below: |
| 428 | |
| 429 | \begin{verbatim} |
| 430 | import logging |
| 431 | |
| 432 | logging.basicConfig(level=logging.DEBUG, |
Vinay Sajip | e3c330b | 2004-07-07 15:59:49 +0000 | [diff] [blame] | 433 | format='%(asctime)s %(levelname)s %(message)s', |
| 434 | filename='/tmp/myapp.log', |
| 435 | filemode='w') |
Vinay Sajip | a13c60b | 2004-07-03 11:45:53 +0000 | [diff] [blame] | 436 | logging.debug('A debug message') |
| 437 | logging.info('Some information') |
| 438 | logging.warning('A shot across the bows') |
| 439 | \end{verbatim} |
| 440 | |
| 441 | The \method{basicConfig()} method is used to change the configuration |
| 442 | defaults, which results in output (written to \code{/tmp/myapp.log}) |
| 443 | which should look something like the following: |
| 444 | |
| 445 | \begin{verbatim} |
| 446 | 2004-07-02 13:00:08,743 DEBUG A debug message |
| 447 | 2004-07-02 13:00:08,743 INFO Some information |
| 448 | 2004-07-02 13:00:08,743 WARNING A shot across the bows |
| 449 | \end{verbatim} |
| 450 | |
| 451 | This time, all messages with a severity of DEBUG or above were handled, |
| 452 | and the format of the messages was also changed, and output went to the |
| 453 | specified file rather than the console. |
| 454 | |
| 455 | Formatting uses standard Python string formatting - see section |
| 456 | \ref{typesseq-strings}. The format string takes the following |
| 457 | common specifiers. For a complete list of specifiers, consult the |
| 458 | \class{Formatter} documentation. |
| 459 | |
| 460 | \begin{tableii}{l|l}{code}{Format}{Description} |
| 461 | \lineii{\%(name)s} {Name of the logger (logging channel).} |
| 462 | \lineii{\%(levelname)s}{Text logging level for the message |
| 463 | (\code{'DEBUG'}, \code{'INFO'}, |
| 464 | \code{'WARNING'}, \code{'ERROR'}, |
| 465 | \code{'CRITICAL'}).} |
| 466 | \lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord} |
| 467 | was created. By default this is of the form |
| 468 | ``2003-07-08 16:49:45,896'' (the numbers after the |
| 469 | comma are millisecond portion of the time).} |
| 470 | \lineii{\%(message)s} {The logged message.} |
| 471 | \end{tableii} |
| 472 | |
| 473 | To change the date/time format, you can pass an additional keyword parameter, |
| 474 | \var{datefmt}, as in the following: |
| 475 | |
| 476 | \begin{verbatim} |
| 477 | import logging |
| 478 | |
| 479 | logging.basicConfig(level=logging.DEBUG, |
Vinay Sajip | e3c330b | 2004-07-07 15:59:49 +0000 | [diff] [blame] | 480 | format='%(asctime)s %(levelname)-8s %(message)s', |
| 481 | datefmt='%a, %d %b %Y %H:%M:%S', |
| 482 | filename='/temp/myapp.log', |
| 483 | filemode='w') |
Vinay Sajip | a13c60b | 2004-07-03 11:45:53 +0000 | [diff] [blame] | 484 | logging.debug('A debug message') |
| 485 | logging.info('Some information') |
| 486 | logging.warning('A shot across the bows') |
| 487 | \end{verbatim} |
| 488 | |
| 489 | which would result in output like |
| 490 | |
| 491 | \begin{verbatim} |
| 492 | Fri, 02 Jul 2004 13:06:18 DEBUG A debug message |
| 493 | Fri, 02 Jul 2004 13:06:18 INFO Some information |
| 494 | Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows |
| 495 | \end{verbatim} |
| 496 | |
| 497 | The date format string follows the requirements of \function{strftime()} - |
| 498 | see the documentation for the \refmodule{time} module. |
| 499 | |
| 500 | If, instead of sending logging output to the console or a file, you'd rather |
| 501 | use a file-like object which you have created separately, you can pass it |
| 502 | to \function{basicConfig()} using the \var{stream} keyword argument. Note |
| 503 | that if both \var{stream} and \var{filename} keyword arguments are passed, |
| 504 | the \var{stream} argument is ignored. |
| 505 | |
Vinay Sajip | b4bf62f | 2004-07-21 14:40:11 +0000 | [diff] [blame] | 506 | Of course, you can put variable information in your output. To do this, |
| 507 | simply have the message be a format string and pass in additional arguments |
| 508 | containing the variable information, as in the following example: |
| 509 | |
| 510 | \begin{verbatim} |
| 511 | import logging |
| 512 | |
| 513 | logging.basicConfig(level=logging.DEBUG, |
| 514 | format='%(asctime)s %(levelname)-8s %(message)s', |
| 515 | datefmt='%a, %d %b %Y %H:%M:%S', |
| 516 | filename='/temp/myapp.log', |
| 517 | filemode='w') |
Vinay Sajip | 93ae4c1 | 2004-10-22 21:43:15 +0000 | [diff] [blame] | 518 | logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs') |
Vinay Sajip | b4bf62f | 2004-07-21 14:40:11 +0000 | [diff] [blame] | 519 | \end{verbatim} |
| 520 | |
| 521 | which would result in |
| 522 | |
| 523 | \begin{verbatim} |
Vinay Sajip | 93ae4c1 | 2004-10-22 21:43:15 +0000 | [diff] [blame] | 524 | Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs |
Vinay Sajip | b4bf62f | 2004-07-21 14:40:11 +0000 | [diff] [blame] | 525 | \end{verbatim} |
| 526 | |
Vinay Sajip | 93ae4c1 | 2004-10-22 21:43:15 +0000 | [diff] [blame] | 527 | \subsection{Logging to multiple destinations \label{multiple-destinations}} |
| 528 | |
| 529 | Let's say you want to log to console and file with different message formats |
| 530 | and in differing circumstances. Say you want to log messages with levels |
| 531 | of DEBUG and higher to file, and those messages at level INFO and higher to |
| 532 | the console. Let's also assume that the file should contain timestamps, but |
| 533 | the console messages should not. Here's how you can achieve this: |
| 534 | |
| 535 | \begin{verbatim} |
| 536 | import logging |
| 537 | |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 538 | # set up logging to file - see previous section for more details |
Vinay Sajip | 93ae4c1 | 2004-10-22 21:43:15 +0000 | [diff] [blame] | 539 | logging.basicConfig(level=logging.DEBUG, |
| 540 | format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', |
| 541 | datefmt='%m-%d %H:%M', |
| 542 | filename='/temp/myapp.log', |
| 543 | filemode='w') |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 544 | # define a Handler which writes INFO messages or higher to the sys.stderr |
Vinay Sajip | 93ae4c1 | 2004-10-22 21:43:15 +0000 | [diff] [blame] | 545 | console = logging.StreamHandler() |
| 546 | console.setLevel(logging.INFO) |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 547 | # set a format which is simpler for console use |
Vinay Sajip | 93ae4c1 | 2004-10-22 21:43:15 +0000 | [diff] [blame] | 548 | formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 549 | # tell the handler to use this format |
Vinay Sajip | 93ae4c1 | 2004-10-22 21:43:15 +0000 | [diff] [blame] | 550 | console.setFormatter(formatter) |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 551 | # add the handler to the root logger |
Vinay Sajip | 93ae4c1 | 2004-10-22 21:43:15 +0000 | [diff] [blame] | 552 | logging.getLogger('').addHandler(console) |
| 553 | |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 554 | # Now, we can log to the root logger, or any other logger. First the root... |
Vinay Sajip | 93ae4c1 | 2004-10-22 21:43:15 +0000 | [diff] [blame] | 555 | logging.info('Jackdaws love my big sphinx of quartz.') |
| 556 | |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 557 | # Now, define a couple of other loggers which might represent areas in your |
| 558 | # application: |
Vinay Sajip | 93ae4c1 | 2004-10-22 21:43:15 +0000 | [diff] [blame] | 559 | |
| 560 | logger1 = logging.getLogger('myapp.area1') |
| 561 | logger2 = logging.getLogger('myapp.area2') |
| 562 | |
| 563 | logger1.debug('Quick zephyrs blow, vexing daft Jim.') |
| 564 | logger1.info('How quickly daft jumping zebras vex.') |
| 565 | logger2.warning('Jail zesty vixen who grabbed pay from quack.') |
| 566 | logger2.error('The five boxing wizards jump quickly.') |
| 567 | \end{verbatim} |
| 568 | |
| 569 | When you run this, on the console you will see |
| 570 | |
| 571 | \begin{verbatim} |
| 572 | root : INFO Jackdaws love my big sphinx of quartz. |
| 573 | myapp.area1 : INFO How quickly daft jumping zebras vex. |
| 574 | myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack. |
| 575 | myapp.area2 : ERROR The five boxing wizards jump quickly. |
| 576 | \end{verbatim} |
| 577 | |
| 578 | and in the file you will see something like |
| 579 | |
| 580 | \begin{verbatim} |
| 581 | 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz. |
| 582 | 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. |
| 583 | 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex. |
| 584 | 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. |
| 585 | 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly. |
| 586 | \end{verbatim} |
| 587 | |
| 588 | As you can see, the DEBUG message only shows up in the file. The other |
| 589 | messages are sent to both destinations. |
| 590 | |
Vinay Sajip | 006483b | 2004-10-29 12:30:28 +0000 | [diff] [blame] | 591 | This example uses console and file handlers, but you can use any number and |
| 592 | combination of handlers you choose. |
| 593 | |
| 594 | \subsection{Sending and receiving logging events across a network |
| 595 | \label{network-logging}} |
| 596 | |
| 597 | Let's say you want to send logging events across a network, and handle them |
| 598 | at the receiving end. A simple way of doing this is attaching a |
| 599 | \class{SocketHandler} instance to the root logger at the sending end: |
| 600 | |
| 601 | \begin{verbatim} |
| 602 | import logging, logging.handlers |
| 603 | |
| 604 | rootLogger = logging.getLogger('') |
| 605 | rootLogger.setLevel(logging.DEBUG) |
| 606 | socketHandler = logging.handlers.SocketHandler('localhost', |
| 607 | logging.handlers.DEFAULT_TCP_LOGGING_PORT) |
| 608 | # don't bother with a formatter, since a socket handler sends the event as |
| 609 | # an unformatted pickle |
| 610 | rootLogger.addHandler(socketHandler) |
| 611 | |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 612 | # Now, we can log to the root logger, or any other logger. First the root... |
Vinay Sajip | 006483b | 2004-10-29 12:30:28 +0000 | [diff] [blame] | 613 | logging.info('Jackdaws love my big sphinx of quartz.') |
| 614 | |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 615 | # Now, define a couple of other loggers which might represent areas in your |
| 616 | # application: |
Vinay Sajip | 006483b | 2004-10-29 12:30:28 +0000 | [diff] [blame] | 617 | |
| 618 | logger1 = logging.getLogger('myapp.area1') |
| 619 | logger2 = logging.getLogger('myapp.area2') |
| 620 | |
| 621 | logger1.debug('Quick zephyrs blow, vexing daft Jim.') |
| 622 | logger1.info('How quickly daft jumping zebras vex.') |
| 623 | logger2.warning('Jail zesty vixen who grabbed pay from quack.') |
| 624 | logger2.error('The five boxing wizards jump quickly.') |
| 625 | \end{verbatim} |
| 626 | |
| 627 | At the receiving end, you can set up a receiver using the |
| 628 | \module{SocketServer} module. Here is a basic working example: |
| 629 | |
| 630 | \begin{verbatim} |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 631 | import cPickle |
| 632 | import logging |
| 633 | import logging.handlers |
| 634 | import SocketServer |
| 635 | import struct |
Vinay Sajip | 006483b | 2004-10-29 12:30:28 +0000 | [diff] [blame] | 636 | |
Vinay Sajip | 006483b | 2004-10-29 12:30:28 +0000 | [diff] [blame] | 637 | |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 638 | class LogRecordStreamHandler(SocketServer.StreamRequestHandler): |
| 639 | """Handler for a streaming logging request. |
| 640 | |
| 641 | This basically logs the record using whatever logging policy is |
| 642 | configured locally. |
Vinay Sajip | 006483b | 2004-10-29 12:30:28 +0000 | [diff] [blame] | 643 | """ |
| 644 | |
| 645 | def handle(self): |
| 646 | """ |
| 647 | Handle multiple requests - each expected to be a 4-byte length, |
| 648 | followed by the LogRecord in pickle format. Logs the record |
| 649 | according to whatever policy is configured locally. |
| 650 | """ |
| 651 | while 1: |
| 652 | chunk = self.connection.recv(4) |
| 653 | if len(chunk) < 4: |
| 654 | break |
| 655 | slen = struct.unpack(">L", chunk)[0] |
| 656 | chunk = self.connection.recv(slen) |
| 657 | while len(chunk) < slen: |
| 658 | chunk = chunk + self.connection.recv(slen - len(chunk)) |
| 659 | obj = self.unPickle(chunk) |
| 660 | record = logging.makeLogRecord(obj) |
| 661 | self.handleLogRecord(record) |
| 662 | |
| 663 | def unPickle(self, data): |
| 664 | return cPickle.loads(data) |
| 665 | |
| 666 | def handleLogRecord(self, record): |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 667 | # if a name is specified, we use the named logger rather than the one |
| 668 | # implied by the record. |
Vinay Sajip | 006483b | 2004-10-29 12:30:28 +0000 | [diff] [blame] | 669 | if self.server.logname is not None: |
| 670 | name = self.server.logname |
| 671 | else: |
| 672 | name = record.name |
| 673 | logger = logging.getLogger(name) |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 674 | # N.B. EVERY record gets logged. This is because Logger.handle |
| 675 | # is normally called AFTER logger-level filtering. If you want |
| 676 | # to do filtering, do it at the client end to save wasting |
| 677 | # cycles and network bandwidth! |
Vinay Sajip | 006483b | 2004-10-29 12:30:28 +0000 | [diff] [blame] | 678 | logger.handle(record) |
| 679 | |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 680 | class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer): |
| 681 | """simple TCP socket-based logging receiver suitable for testing. |
Vinay Sajip | 006483b | 2004-10-29 12:30:28 +0000 | [diff] [blame] | 682 | """ |
| 683 | |
| 684 | allow_reuse_address = 1 |
| 685 | |
| 686 | def __init__(self, host='localhost', |
Fred Drake | 048840c | 2004-10-29 14:35:42 +0000 | [diff] [blame] | 687 | port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, |
| 688 | handler=LogRecordStreamHandler): |
| 689 | SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler) |
Vinay Sajip | 006483b | 2004-10-29 12:30:28 +0000 | [diff] [blame] | 690 | self.abort = 0 |
| 691 | self.timeout = 1 |
| 692 | self.logname = None |
| 693 | |
| 694 | def serve_until_stopped(self): |
| 695 | import select |
| 696 | abort = 0 |
| 697 | while not abort: |
| 698 | rd, wr, ex = select.select([self.socket.fileno()], |
| 699 | [], [], |
| 700 | self.timeout) |
| 701 | if rd: |
| 702 | self.handle_request() |
| 703 | abort = self.abort |
| 704 | |
| 705 | def main(): |
| 706 | logging.basicConfig( |
Vinay Sajip | edde492 | 2004-11-11 13:54:48 +0000 | [diff] [blame] | 707 | format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s") |
Vinay Sajip | 006483b | 2004-10-29 12:30:28 +0000 | [diff] [blame] | 708 | tcpserver = LogRecordSocketReceiver() |
| 709 | print "About to start TCP server..." |
| 710 | tcpserver.serve_until_stopped() |
| 711 | |
| 712 | if __name__ == "__main__": |
| 713 | main() |
| 714 | \end{verbatim} |
| 715 | |
Vinay Sajip | edde492 | 2004-11-11 13:54:48 +0000 | [diff] [blame] | 716 | First run the server, and then the client. On the client side, nothing is |
| 717 | printed on the console; on the server side, you should see something like: |
Vinay Sajip | 006483b | 2004-10-29 12:30:28 +0000 | [diff] [blame] | 718 | |
| 719 | \begin{verbatim} |
| 720 | About to start TCP server... |
| 721 | 59 root INFO Jackdaws love my big sphinx of quartz. |
| 722 | 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. |
| 723 | 69 myapp.area1 INFO How quickly daft jumping zebras vex. |
| 724 | 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. |
| 725 | 69 myapp.area2 ERROR The five boxing wizards jump quickly. |
| 726 | \end{verbatim} |
| 727 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 728 | \subsection{Handler Objects} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 729 | |
Fred Drake | 68e6d57 | 2003-01-28 22:02:35 +0000 | [diff] [blame] | 730 | Handlers have the following attributes and methods. Note that |
| 731 | \class{Handler} is never instantiated directly; this class acts as a |
| 732 | base for more useful subclasses. However, the \method{__init__()} |
| 733 | method in subclasses needs to call \method{Handler.__init__()}. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 734 | |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 735 | \begin{methoddesc}{__init__}{level=\constant{NOTSET}} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 736 | Initializes the \class{Handler} instance by setting its level, setting |
| 737 | the list of filters to the empty list and creating a lock (using |
Raymond Hettinger | c75c3e0 | 2003-09-01 22:50:52 +0000 | [diff] [blame] | 738 | \method{createLock()}) for serializing access to an I/O mechanism. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 739 | \end{methoddesc} |
| 740 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 741 | \begin{methoddesc}{createLock}{} |
| 742 | Initializes a thread lock which can be used to serialize access to |
| 743 | underlying I/O functionality which may not be threadsafe. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 744 | \end{methoddesc} |
| 745 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 746 | \begin{methoddesc}{acquire}{} |
| 747 | Acquires the thread lock created with \method{createLock()}. |
| 748 | \end{methoddesc} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 749 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 750 | \begin{methoddesc}{release}{} |
| 751 | Releases the thread lock acquired with \method{acquire()}. |
| 752 | \end{methoddesc} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 753 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 754 | \begin{methoddesc}{setLevel}{lvl} |
| 755 | Sets the threshold for this handler to \var{lvl}. Logging messages which are |
| 756 | less severe than \var{lvl} will be ignored. When a handler is created, the |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 757 | level is set to \constant{NOTSET} (which causes all messages to be processed). |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 758 | \end{methoddesc} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 759 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 760 | \begin{methoddesc}{setFormatter}{form} |
| 761 | Sets the \class{Formatter} for this handler to \var{form}. |
| 762 | \end{methoddesc} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 763 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 764 | \begin{methoddesc}{addFilter}{filt} |
| 765 | Adds the specified filter \var{filt} to this handler. |
| 766 | \end{methoddesc} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 767 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 768 | \begin{methoddesc}{removeFilter}{filt} |
| 769 | Removes the specified filter \var{filt} from this handler. |
| 770 | \end{methoddesc} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 771 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 772 | \begin{methoddesc}{filter}{record} |
| 773 | Applies this handler's filters to the record and returns a true value if |
| 774 | the record is to be processed. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 775 | \end{methoddesc} |
| 776 | |
| 777 | \begin{methoddesc}{flush}{} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 778 | Ensure all logging output has been flushed. This version does |
| 779 | nothing and is intended to be implemented by subclasses. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 780 | \end{methoddesc} |
| 781 | |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 782 | \begin{methoddesc}{close}{} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 783 | Tidy up any resources used by the handler. This version does |
| 784 | nothing and is intended to be implemented by subclasses. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 785 | \end{methoddesc} |
| 786 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 787 | \begin{methoddesc}{handle}{record} |
| 788 | Conditionally emits the specified logging record, depending on |
| 789 | filters which may have been added to the handler. Wraps the actual |
| 790 | emission of the record with acquisition/release of the I/O thread |
| 791 | lock. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 792 | \end{methoddesc} |
| 793 | |
Vinay Sajip | a13c60b | 2004-07-03 11:45:53 +0000 | [diff] [blame] | 794 | \begin{methoddesc}{handleError}{record} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 795 | This method should be called from handlers when an exception is |
Vinay Sajip | a13c60b | 2004-07-03 11:45:53 +0000 | [diff] [blame] | 796 | encountered during an \method{emit()} call. By default it does nothing, |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 797 | which means that exceptions get silently ignored. This is what is |
| 798 | mostly wanted for a logging system - most users will not care |
| 799 | about errors in the logging system, they are more interested in |
| 800 | application errors. You could, however, replace this with a custom |
Vinay Sajip | a13c60b | 2004-07-03 11:45:53 +0000 | [diff] [blame] | 801 | handler if you wish. The specified record is the one which was being |
| 802 | processed when the exception occurred. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 803 | \end{methoddesc} |
| 804 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 805 | \begin{methoddesc}{format}{record} |
| 806 | Do formatting for a record - if a formatter is set, use it. |
| 807 | Otherwise, use the default formatter for the module. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 808 | \end{methoddesc} |
| 809 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 810 | \begin{methoddesc}{emit}{record} |
| 811 | Do whatever it takes to actually log the specified logging record. |
| 812 | This version is intended to be implemented by subclasses and so |
| 813 | raises a \exception{NotImplementedError}. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 814 | \end{methoddesc} |
| 815 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 816 | \subsubsection{StreamHandler} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 817 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 818 | The \class{StreamHandler} class sends logging output to streams such as |
| 819 | \var{sys.stdout}, \var{sys.stderr} or any file-like object (or, more |
| 820 | precisely, any object which supports \method{write()} and \method{flush()} |
Raymond Hettinger | 2ef85a7 | 2003-01-25 21:46:53 +0000 | [diff] [blame] | 821 | methods). |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 822 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 823 | \begin{classdesc}{StreamHandler}{\optional{strm}} |
| 824 | Returns a new instance of the \class{StreamHandler} class. If \var{strm} is |
| 825 | specified, the instance will use it for logging output; otherwise, |
| 826 | \var{sys.stderr} will be used. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 827 | \end{classdesc} |
| 828 | |
| 829 | \begin{methoddesc}{emit}{record} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 830 | If a formatter is specified, it is used to format the record. |
| 831 | The record is then written to the stream with a trailing newline. |
| 832 | If exception information is present, it is formatted using |
| 833 | \function{traceback.print_exception()} and appended to the stream. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 834 | \end{methoddesc} |
| 835 | |
| 836 | \begin{methoddesc}{flush}{} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 837 | Flushes the stream by calling its \method{flush()} method. Note that |
| 838 | the \method{close()} method is inherited from \class{Handler} and |
| 839 | so does nothing, so an explicit \method{flush()} call may be needed |
| 840 | at times. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 841 | \end{methoddesc} |
| 842 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 843 | \subsubsection{FileHandler} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 844 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 845 | The \class{FileHandler} class sends logging output to a disk file. |
Fred Drake | 68e6d57 | 2003-01-28 22:02:35 +0000 | [diff] [blame] | 846 | It inherits the output functionality from \class{StreamHandler}. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 847 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 848 | \begin{classdesc}{FileHandler}{filename\optional{, mode}} |
| 849 | Returns a new instance of the \class{FileHandler} class. The specified |
| 850 | file is opened and used as the stream for logging. If \var{mode} is |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 851 | not specified, \constant{'a'} is used. By default, the file grows |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 852 | indefinitely. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 853 | \end{classdesc} |
| 854 | |
| 855 | \begin{methoddesc}{close}{} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 856 | Closes the file. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 857 | \end{methoddesc} |
| 858 | |
| 859 | \begin{methoddesc}{emit}{record} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 860 | Outputs the record to the file. |
| 861 | \end{methoddesc} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 862 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 863 | \subsubsection{RotatingFileHandler} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 864 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 865 | The \class{RotatingFileHandler} class supports rotation of disk log files. |
| 866 | |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 867 | \begin{classdesc}{RotatingFileHandler}{filename\optional{, mode\optional{, |
| 868 | maxBytes\optional{, backupCount}}}} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 869 | Returns a new instance of the \class{RotatingFileHandler} class. The |
| 870 | specified file is opened and used as the stream for logging. If |
Fred Drake | 68e6d57 | 2003-01-28 22:02:35 +0000 | [diff] [blame] | 871 | \var{mode} is not specified, \code{'a'} is used. By default, the |
Vinay Sajip | a13c60b | 2004-07-03 11:45:53 +0000 | [diff] [blame] | 872 | file grows indefinitely. |
Andrew M. Kuchling | 7cf4d9b | 2003-09-26 13:45:18 +0000 | [diff] [blame] | 873 | |
| 874 | You can use the \var{maxBytes} and |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 875 | \var{backupCount} values to allow the file to \dfn{rollover} at a |
| 876 | predetermined size. When the size is about to be exceeded, the file is |
Andrew M. Kuchling | 7cf4d9b | 2003-09-26 13:45:18 +0000 | [diff] [blame] | 877 | closed and a new file is silently opened for output. Rollover occurs |
| 878 | whenever the current log file is nearly \var{maxBytes} in length; if |
| 879 | \var{maxBytes} is zero, rollover never occurs. If \var{backupCount} |
| 880 | is non-zero, the system will save old log files by appending the |
| 881 | extensions ".1", ".2" etc., to the filename. For example, with |
| 882 | a \var{backupCount} of 5 and a base file name of |
| 883 | \file{app.log}, you would get \file{app.log}, |
| 884 | \file{app.log.1}, \file{app.log.2}, up to \file{app.log.5}. The file being |
| 885 | written to is always \file{app.log}. When this file is filled, it is |
| 886 | closed and renamed to \file{app.log.1}, and if files \file{app.log.1}, |
| 887 | \file{app.log.2}, etc. exist, then they are renamed to \file{app.log.2}, |
Vinay Sajip | a13c60b | 2004-07-03 11:45:53 +0000 | [diff] [blame] | 888 | \file{app.log.3} etc. respectively. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 889 | \end{classdesc} |
| 890 | |
| 891 | \begin{methoddesc}{doRollover}{} |
| 892 | Does a rollover, as described above. |
| 893 | \end{methoddesc} |
| 894 | |
| 895 | \begin{methoddesc}{emit}{record} |
Johannes Gijsbers | f164322 | 2004-11-07 16:11:35 +0000 | [diff] [blame] | 896 | Outputs the record to the file, catering for rollover as described previously. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 897 | \end{methoddesc} |
| 898 | |
Johannes Gijsbers | 4f802ac | 2004-11-07 14:14:27 +0000 | [diff] [blame] | 899 | \subsubsection{TimedRotatingFileHandler} |
| 900 | |
| 901 | The \class{TimedRotatingFileHandler} class supports rotation of disk log files |
| 902 | at certain timed intervals. |
| 903 | |
| 904 | \begin{classdesc}{TimedRotatingFileHandler}{filename |
| 905 | \optional{,when |
| 906 | \optional{,interval |
| 907 | \optional{,backupCount}}}} |
| 908 | |
| 909 | Returns a new instance of the \class{TimedRotatingFileHandler} class. The |
| 910 | specified file is opened and used as the stream for logging. On rotating |
| 911 | it also sets the filename suffix. Rotating happens based on the product |
Vinay Sajip | edde492 | 2004-11-11 13:54:48 +0000 | [diff] [blame] | 912 | of \var{when} and \var{interval}. |
Johannes Gijsbers | 4f802ac | 2004-11-07 14:14:27 +0000 | [diff] [blame] | 913 | |
| 914 | You can use the \var{when} to specify the type of \var{interval}. The |
| 915 | list of possible values is, note that they are not case sensitive: |
| 916 | |
| 917 | \begin{tableii}{l|l}{}{Value}{Type of interval} |
| 918 | \lineii{S}{Seconds} |
| 919 | \lineii{M}{Minutes} |
| 920 | \lineii{H}{Hours} |
| 921 | \lineii{D}{Days} |
| 922 | \lineii{W}{Week day (0=Monday)} |
| 923 | \lineii{midnight}{Roll over at midnight} |
| 924 | \end{tableii} |
| 925 | |
| 926 | If \var{backupCount} is non-zero, the system will save old log files by |
| 927 | appending the extensions ".1", ".2" etc., to the filename. For example, |
| 928 | with a \var{backupCount} of 5 and a base file name of \file{app.log}, |
| 929 | you would get \file{app.log}, \file{app.log.1}, \file{app.log.2}, up to |
| 930 | \file{app.log.5}. The file being written to is always \file{app.log}. |
| 931 | When this file is filled, it is closed and renamed to \file{app.log.1}, |
| 932 | and if files \file{app.log.1}, \file{app.log.2}, etc. exist, then they |
| 933 | are renamed to \file{app.log.2}, \file{app.log.3} etc. respectively. |
| 934 | \end{classdesc} |
| 935 | |
| 936 | \begin{methoddesc}{doRollover}{} |
| 937 | Does a rollover, as described above. |
| 938 | \end{methoddesc} |
| 939 | |
| 940 | \begin{methoddesc}{emit}{record} |
| 941 | Outputs the record to the file, catering for rollover as described |
| 942 | above. |
| 943 | \end{methoddesc} |
| 944 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 945 | \subsubsection{SocketHandler} |
| 946 | |
| 947 | The \class{SocketHandler} class sends logging output to a network |
| 948 | socket. The base class uses a TCP socket. |
| 949 | |
| 950 | \begin{classdesc}{SocketHandler}{host, port} |
| 951 | Returns a new instance of the \class{SocketHandler} class intended to |
| 952 | communicate with a remote machine whose address is given by \var{host} |
| 953 | and \var{port}. |
| 954 | \end{classdesc} |
| 955 | |
| 956 | \begin{methoddesc}{close}{} |
| 957 | Closes the socket. |
| 958 | \end{methoddesc} |
| 959 | |
| 960 | \begin{methoddesc}{handleError}{} |
| 961 | \end{methoddesc} |
| 962 | |
| 963 | \begin{methoddesc}{emit}{} |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 964 | Pickles the record's attribute dictionary and writes it to the socket in |
| 965 | binary format. If there is an error with the socket, silently drops the |
| 966 | packet. If the connection was previously lost, re-establishes the connection. |
Fred Drake | 6b3b046 | 2004-04-09 18:26:40 +0000 | [diff] [blame] | 967 | To unpickle the record at the receiving end into a \class{LogRecord}, use the |
| 968 | \function{makeLogRecord()} function. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 969 | \end{methoddesc} |
| 970 | |
| 971 | \begin{methoddesc}{handleError}{} |
| 972 | Handles an error which has occurred during \method{emit()}. The |
| 973 | most likely cause is a lost connection. Closes the socket so that |
| 974 | we can retry on the next event. |
| 975 | \end{methoddesc} |
| 976 | |
| 977 | \begin{methoddesc}{makeSocket}{} |
| 978 | This is a factory method which allows subclasses to define the precise |
| 979 | type of socket they want. The default implementation creates a TCP |
| 980 | socket (\constant{socket.SOCK_STREAM}). |
| 981 | \end{methoddesc} |
| 982 | |
| 983 | \begin{methoddesc}{makePickle}{record} |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 984 | Pickles the record's attribute dictionary in binary format with a length |
| 985 | prefix, and returns it ready for transmission across the socket. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 986 | \end{methoddesc} |
| 987 | |
| 988 | \begin{methoddesc}{send}{packet} |
Raymond Hettinger | 2ef85a7 | 2003-01-25 21:46:53 +0000 | [diff] [blame] | 989 | Send a pickled string \var{packet} to the socket. This function allows |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 990 | for partial sends which can happen when the network is busy. |
| 991 | \end{methoddesc} |
| 992 | |
| 993 | \subsubsection{DatagramHandler} |
| 994 | |
| 995 | The \class{DatagramHandler} class inherits from \class{SocketHandler} |
| 996 | to support sending logging messages over UDP sockets. |
| 997 | |
| 998 | \begin{classdesc}{DatagramHandler}{host, port} |
| 999 | Returns a new instance of the \class{DatagramHandler} class intended to |
| 1000 | communicate with a remote machine whose address is given by \var{host} |
| 1001 | and \var{port}. |
| 1002 | \end{classdesc} |
| 1003 | |
| 1004 | \begin{methoddesc}{emit}{} |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 1005 | Pickles the record's attribute dictionary and writes it to the socket in |
| 1006 | binary format. If there is an error with the socket, silently drops the |
| 1007 | packet. |
Fred Drake | 6b3b046 | 2004-04-09 18:26:40 +0000 | [diff] [blame] | 1008 | To unpickle the record at the receiving end into a \class{LogRecord}, use the |
| 1009 | \function{makeLogRecord()} function. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1010 | \end{methoddesc} |
| 1011 | |
| 1012 | \begin{methoddesc}{makeSocket}{} |
| 1013 | The factory method of \class{SocketHandler} is here overridden to create |
| 1014 | a UDP socket (\constant{socket.SOCK_DGRAM}). |
| 1015 | \end{methoddesc} |
| 1016 | |
| 1017 | \begin{methoddesc}{send}{s} |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 1018 | Send a pickled string to a socket. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1019 | \end{methoddesc} |
| 1020 | |
| 1021 | \subsubsection{SysLogHandler} |
| 1022 | |
| 1023 | The \class{SysLogHandler} class supports sending logging messages to a |
Fred Drake | 68e6d57 | 2003-01-28 22:02:35 +0000 | [diff] [blame] | 1024 | remote or local \UNIX{} syslog. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1025 | |
| 1026 | \begin{classdesc}{SysLogHandler}{\optional{address\optional{, facility}}} |
| 1027 | Returns a new instance of the \class{SysLogHandler} class intended to |
Fred Drake | 68e6d57 | 2003-01-28 22:02:35 +0000 | [diff] [blame] | 1028 | communicate with a remote \UNIX{} machine whose address is given by |
| 1029 | \var{address} in the form of a \code{(\var{host}, \var{port})} |
| 1030 | tuple. If \var{address} is not specified, \code{('localhost', 514)} is |
| 1031 | used. The address is used to open a UDP socket. If \var{facility} is |
| 1032 | not specified, \constant{LOG_USER} is used. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1033 | \end{classdesc} |
| 1034 | |
| 1035 | \begin{methoddesc}{close}{} |
| 1036 | Closes the socket to the remote host. |
| 1037 | \end{methoddesc} |
| 1038 | |
| 1039 | \begin{methoddesc}{emit}{record} |
| 1040 | The record is formatted, and then sent to the syslog server. If |
| 1041 | exception information is present, it is \emph{not} sent to the server. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1042 | \end{methoddesc} |
| 1043 | |
| 1044 | \begin{methoddesc}{encodePriority}{facility, priority} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1045 | Encodes the facility and priority into an integer. You can pass in strings |
| 1046 | or integers - if strings are passed, internal mapping dictionaries are used |
| 1047 | to convert them to integers. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1048 | \end{methoddesc} |
| 1049 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1050 | \subsubsection{NTEventLogHandler} |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1051 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1052 | The \class{NTEventLogHandler} class supports sending logging messages |
| 1053 | to a local Windows NT, Windows 2000 or Windows XP event log. Before |
| 1054 | you can use it, you need Mark Hammond's Win32 extensions for Python |
| 1055 | installed. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1056 | |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 1057 | \begin{classdesc}{NTEventLogHandler}{appname\optional{, |
| 1058 | dllname\optional{, logtype}}} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1059 | Returns a new instance of the \class{NTEventLogHandler} class. The |
| 1060 | \var{appname} is used to define the application name as it appears in the |
| 1061 | event log. An appropriate registry entry is created using this name. |
| 1062 | The \var{dllname} should give the fully qualified pathname of a .dll or .exe |
| 1063 | which contains message definitions to hold in the log (if not specified, |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 1064 | \code{'win32service.pyd'} is used - this is installed with the Win32 |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1065 | extensions and contains some basic placeholder message definitions. |
| 1066 | Note that use of these placeholders will make your event logs big, as the |
| 1067 | entire message source is held in the log. If you want slimmer logs, you have |
| 1068 | to pass in the name of your own .dll or .exe which contains the message |
| 1069 | definitions you want to use in the event log). The \var{logtype} is one of |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 1070 | \code{'Application'}, \code{'System'} or \code{'Security'}, and |
| 1071 | defaults to \code{'Application'}. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1072 | \end{classdesc} |
| 1073 | |
| 1074 | \begin{methoddesc}{close}{} |
| 1075 | At this point, you can remove the application name from the registry as a |
| 1076 | source of event log entries. However, if you do this, you will not be able |
| 1077 | to see the events as you intended in the Event Log Viewer - it needs to be |
| 1078 | able to access the registry to get the .dll name. The current version does |
| 1079 | not do this (in fact it doesn't do anything). |
| 1080 | \end{methoddesc} |
| 1081 | |
| 1082 | \begin{methoddesc}{emit}{record} |
| 1083 | Determines the message ID, event category and event type, and then logs the |
| 1084 | message in the NT event log. |
| 1085 | \end{methoddesc} |
| 1086 | |
| 1087 | \begin{methoddesc}{getEventCategory}{record} |
| 1088 | Returns the event category for the record. Override this if you |
| 1089 | want to specify your own categories. This version returns 0. |
| 1090 | \end{methoddesc} |
| 1091 | |
| 1092 | \begin{methoddesc}{getEventType}{record} |
| 1093 | Returns the event type for the record. Override this if you want |
| 1094 | to specify your own types. This version does a mapping using the |
| 1095 | handler's typemap attribute, which is set up in \method{__init__()} |
| 1096 | to a dictionary which contains mappings for \constant{DEBUG}, |
| 1097 | \constant{INFO}, \constant{WARNING}, \constant{ERROR} and |
| 1098 | \constant{CRITICAL}. If you are using your own levels, you will either need |
| 1099 | to override this method or place a suitable dictionary in the |
| 1100 | handler's \var{typemap} attribute. |
| 1101 | \end{methoddesc} |
| 1102 | |
| 1103 | \begin{methoddesc}{getMessageID}{record} |
| 1104 | Returns the message ID for the record. If you are using your |
| 1105 | own messages, you could do this by having the \var{msg} passed to the |
| 1106 | logger being an ID rather than a format string. Then, in here, |
| 1107 | you could use a dictionary lookup to get the message ID. This |
| 1108 | version returns 1, which is the base message ID in |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 1109 | \file{win32service.pyd}. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1110 | \end{methoddesc} |
| 1111 | |
| 1112 | \subsubsection{SMTPHandler} |
| 1113 | |
| 1114 | The \class{SMTPHandler} class supports sending logging messages to an email |
| 1115 | address via SMTP. |
| 1116 | |
| 1117 | \begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject} |
| 1118 | Returns a new instance of the \class{SMTPHandler} class. The |
| 1119 | instance is initialized with the from and to addresses and subject |
| 1120 | line of the email. The \var{toaddrs} should be a list of strings without |
| 1121 | domain names (That's what the \var{mailhost} is for). To specify a |
| 1122 | non-standard SMTP port, use the (host, port) tuple format for the |
| 1123 | \var{mailhost} argument. If you use a string, the standard SMTP port |
| 1124 | is used. |
| 1125 | \end{classdesc} |
| 1126 | |
| 1127 | \begin{methoddesc}{emit}{record} |
| 1128 | Formats the record and sends it to the specified addressees. |
| 1129 | \end{methoddesc} |
| 1130 | |
| 1131 | \begin{methoddesc}{getSubject}{record} |
| 1132 | If you want to specify a subject line which is record-dependent, |
| 1133 | override this method. |
| 1134 | \end{methoddesc} |
| 1135 | |
| 1136 | \subsubsection{MemoryHandler} |
| 1137 | |
| 1138 | The \class{MemoryHandler} supports buffering of logging records in memory, |
| 1139 | periodically flushing them to a \dfn{target} handler. Flushing occurs |
| 1140 | whenever the buffer is full, or when an event of a certain severity or |
| 1141 | greater is seen. |
| 1142 | |
| 1143 | \class{MemoryHandler} is a subclass of the more general |
| 1144 | \class{BufferingHandler}, which is an abstract class. This buffers logging |
| 1145 | records in memory. Whenever each record is added to the buffer, a |
| 1146 | check is made by calling \method{shouldFlush()} to see if the buffer |
| 1147 | should be flushed. If it should, then \method{flush()} is expected to |
| 1148 | do the needful. |
| 1149 | |
| 1150 | \begin{classdesc}{BufferingHandler}{capacity} |
| 1151 | Initializes the handler with a buffer of the specified capacity. |
| 1152 | \end{classdesc} |
| 1153 | |
| 1154 | \begin{methoddesc}{emit}{record} |
| 1155 | Appends the record to the buffer. If \method{shouldFlush()} returns true, |
| 1156 | calls \method{flush()} to process the buffer. |
| 1157 | \end{methoddesc} |
| 1158 | |
| 1159 | \begin{methoddesc}{flush}{} |
Raymond Hettinger | 2ef85a7 | 2003-01-25 21:46:53 +0000 | [diff] [blame] | 1160 | You can override this to implement custom flushing behavior. This version |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1161 | just zaps the buffer to empty. |
| 1162 | \end{methoddesc} |
| 1163 | |
| 1164 | \begin{methoddesc}{shouldFlush}{record} |
| 1165 | Returns true if the buffer is up to capacity. This method can be |
| 1166 | overridden to implement custom flushing strategies. |
| 1167 | \end{methoddesc} |
| 1168 | |
| 1169 | \begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel |
Neal Norwitz | 6fa635d | 2003-02-18 14:20:07 +0000 | [diff] [blame] | 1170 | \optional{, target}}} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1171 | Returns a new instance of the \class{MemoryHandler} class. The |
| 1172 | instance is initialized with a buffer size of \var{capacity}. If |
| 1173 | \var{flushLevel} is not specified, \constant{ERROR} is used. If no |
| 1174 | \var{target} is specified, the target will need to be set using |
| 1175 | \method{setTarget()} before this handler does anything useful. |
| 1176 | \end{classdesc} |
| 1177 | |
| 1178 | \begin{methoddesc}{close}{} |
| 1179 | Calls \method{flush()}, sets the target to \constant{None} and |
| 1180 | clears the buffer. |
| 1181 | \end{methoddesc} |
| 1182 | |
| 1183 | \begin{methoddesc}{flush}{} |
| 1184 | For a \class{MemoryHandler}, flushing means just sending the buffered |
| 1185 | records to the target, if there is one. Override if you want |
Raymond Hettinger | 2ef85a7 | 2003-01-25 21:46:53 +0000 | [diff] [blame] | 1186 | different behavior. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1187 | \end{methoddesc} |
| 1188 | |
| 1189 | \begin{methoddesc}{setTarget}{target} |
| 1190 | Sets the target handler for this handler. |
| 1191 | \end{methoddesc} |
| 1192 | |
| 1193 | \begin{methoddesc}{shouldFlush}{record} |
| 1194 | Checks for buffer full or a record at the \var{flushLevel} or higher. |
| 1195 | \end{methoddesc} |
| 1196 | |
| 1197 | \subsubsection{HTTPHandler} |
| 1198 | |
| 1199 | The \class{HTTPHandler} class supports sending logging messages to a |
Fred Drake | 68e6d57 | 2003-01-28 22:02:35 +0000 | [diff] [blame] | 1200 | Web server, using either \samp{GET} or \samp{POST} semantics. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1201 | |
| 1202 | \begin{classdesc}{HTTPHandler}{host, url\optional{, method}} |
| 1203 | Returns a new instance of the \class{HTTPHandler} class. The |
| 1204 | instance is initialized with a host address, url and HTTP method. |
Fred Drake | 68e6d57 | 2003-01-28 22:02:35 +0000 | [diff] [blame] | 1205 | If no \var{method} is specified, \samp{GET} is used. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1206 | \end{classdesc} |
| 1207 | |
| 1208 | \begin{methoddesc}{emit}{record} |
| 1209 | Sends the record to the Web server as an URL-encoded dictionary. |
| 1210 | \end{methoddesc} |
| 1211 | |
| 1212 | \subsection{Formatter Objects} |
| 1213 | |
| 1214 | \class{Formatter}s have the following attributes and methods. They are |
| 1215 | responsible for converting a \class{LogRecord} to (usually) a string |
| 1216 | which can be interpreted by either a human or an external system. The |
| 1217 | base |
| 1218 | \class{Formatter} allows a formatting string to be specified. If none is |
Fred Drake | 8efc74d | 2004-04-15 06:18:48 +0000 | [diff] [blame] | 1219 | supplied, the default value of \code{'\%(message)s'} is used. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1220 | |
| 1221 | A Formatter can be initialized with a format string which makes use of |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 1222 | knowledge of the \class{LogRecord} attributes - such as the default value |
| 1223 | mentioned above making use of the fact that the user's message and |
Fred Drake | 6b3b046 | 2004-04-09 18:26:40 +0000 | [diff] [blame] | 1224 | arguments are pre-formatted into a \class{LogRecord}'s \var{message} |
Anthony Baxter | a6b7d34 | 2003-07-08 08:40:20 +0000 | [diff] [blame] | 1225 | attribute. This format string contains standard python \%-style |
| 1226 | mapping keys. See section \ref{typesseq-strings}, ``String Formatting |
| 1227 | Operations,'' for more information on string formatting. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1228 | |
Fred Drake | 6b3b046 | 2004-04-09 18:26:40 +0000 | [diff] [blame] | 1229 | Currently, the useful mapping keys in a \class{LogRecord} are: |
Anthony Baxter | a6b7d34 | 2003-07-08 08:40:20 +0000 | [diff] [blame] | 1230 | |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 1231 | \begin{tableii}{l|l}{code}{Format}{Description} |
| 1232 | \lineii{\%(name)s} {Name of the logger (logging channel).} |
| 1233 | \lineii{\%(levelno)s} {Numeric logging level for the message |
| 1234 | (\constant{DEBUG}, \constant{INFO}, |
| 1235 | \constant{WARNING}, \constant{ERROR}, |
| 1236 | \constant{CRITICAL}).} |
| 1237 | \lineii{\%(levelname)s}{Text logging level for the message |
| 1238 | (\code{'DEBUG'}, \code{'INFO'}, |
| 1239 | \code{'WARNING'}, \code{'ERROR'}, |
| 1240 | \code{'CRITICAL'}).} |
| 1241 | \lineii{\%(pathname)s} {Full pathname of the source file where the logging |
| 1242 | call was issued (if available).} |
| 1243 | \lineii{\%(filename)s} {Filename portion of pathname.} |
| 1244 | \lineii{\%(module)s} {Module (name portion of filename).} |
| 1245 | \lineii{\%(lineno)d} {Source line number where the logging call was issued |
| 1246 | (if available).} |
Fred Drake | 6b3b046 | 2004-04-09 18:26:40 +0000 | [diff] [blame] | 1247 | \lineii{\%(created)f} {Time when the \class{LogRecord} was created (as |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 1248 | returned by \function{time.time()}).} |
Fred Drake | 6b3b046 | 2004-04-09 18:26:40 +0000 | [diff] [blame] | 1249 | \lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord} |
| 1250 | was created. By default this is of the form |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 1251 | ``2003-07-08 16:49:45,896'' (the numbers after the |
| 1252 | comma are millisecond portion of the time).} |
| 1253 | \lineii{\%(msecs)d} {Millisecond portion of the time when the |
| 1254 | \class{LogRecord} was created.} |
| 1255 | \lineii{\%(thread)d} {Thread ID (if available).} |
| 1256 | \lineii{\%(process)d} {Process ID (if available).} |
| 1257 | \lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.} |
Anthony Baxter | a6b7d34 | 2003-07-08 08:40:20 +0000 | [diff] [blame] | 1258 | \end{tableii} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1259 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1260 | \begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}} |
| 1261 | Returns a new instance of the \class{Formatter} class. The |
| 1262 | instance is initialized with a format string for the message as a whole, |
| 1263 | as well as a format string for the date/time portion of a message. If |
Neal Norwitz | dd3afa7 | 2003-07-08 16:26:34 +0000 | [diff] [blame] | 1264 | no \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1265 | is specified, the ISO8601 date format is used. |
| 1266 | \end{classdesc} |
| 1267 | |
| 1268 | \begin{methoddesc}{format}{record} |
| 1269 | The record's attribute dictionary is used as the operand to a |
| 1270 | string formatting operation. Returns the resulting string. |
| 1271 | Before formatting the dictionary, a couple of preparatory steps |
| 1272 | are carried out. The \var{message} attribute of the record is computed |
| 1273 | using \var{msg} \% \var{args}. If the formatting string contains |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 1274 | \code{'(asctime)'}, \method{formatTime()} is called to format the |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1275 | event time. If there is exception information, it is formatted using |
| 1276 | \method{formatException()} and appended to the message. |
| 1277 | \end{methoddesc} |
| 1278 | |
| 1279 | \begin{methoddesc}{formatTime}{record\optional{, datefmt}} |
| 1280 | This method should be called from \method{format()} by a formatter which |
| 1281 | wants to make use of a formatted time. This method can be overridden |
| 1282 | in formatters to provide for any specific requirement, but the |
Raymond Hettinger | 2ef85a7 | 2003-01-25 21:46:53 +0000 | [diff] [blame] | 1283 | basic behavior is as follows: if \var{datefmt} (a string) is specified, |
Fred Drake | c23e019 | 2003-01-28 22:09:16 +0000 | [diff] [blame] | 1284 | it is used with \function{time.strftime()} to format the creation time of the |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1285 | record. Otherwise, the ISO8601 format is used. The resulting |
| 1286 | string is returned. |
| 1287 | \end{methoddesc} |
| 1288 | |
| 1289 | \begin{methoddesc}{formatException}{exc_info} |
| 1290 | Formats the specified exception information (a standard exception tuple |
Fred Drake | c23e019 | 2003-01-28 22:09:16 +0000 | [diff] [blame] | 1291 | as returned by \function{sys.exc_info()}) as a string. This default |
| 1292 | implementation just uses \function{traceback.print_exception()}. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1293 | The resulting string is returned. |
| 1294 | \end{methoddesc} |
| 1295 | |
| 1296 | \subsection{Filter Objects} |
| 1297 | |
| 1298 | \class{Filter}s can be used by \class{Handler}s and \class{Logger}s for |
| 1299 | more sophisticated filtering than is provided by levels. The base filter |
| 1300 | class only allows events which are below a certain point in the logger |
| 1301 | hierarchy. For example, a filter initialized with "A.B" will allow events |
| 1302 | logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", |
| 1303 | "B.A.B" etc. If initialized with the empty string, all events are passed. |
| 1304 | |
| 1305 | \begin{classdesc}{Filter}{\optional{name}} |
| 1306 | Returns an instance of the \class{Filter} class. If \var{name} is specified, |
| 1307 | it names a logger which, together with its children, will have its events |
| 1308 | allowed through the filter. If no name is specified, allows every event. |
| 1309 | \end{classdesc} |
| 1310 | |
| 1311 | \begin{methoddesc}{filter}{record} |
| 1312 | Is the specified record to be logged? Returns zero for no, nonzero for |
| 1313 | yes. If deemed appropriate, the record may be modified in-place by this |
| 1314 | method. |
| 1315 | \end{methoddesc} |
| 1316 | |
| 1317 | \subsection{LogRecord Objects} |
| 1318 | |
Fred Drake | 6b3b046 | 2004-04-09 18:26:40 +0000 | [diff] [blame] | 1319 | \class{LogRecord} instances are created every time something is logged. They |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1320 | contain all the information pertinent to the event being logged. The |
| 1321 | main information passed in is in msg and args, which are combined |
| 1322 | using msg \% args to create the message field of the record. The record |
| 1323 | also includes information such as when the record was created, the |
| 1324 | source line where the logging call was made, and any exception |
| 1325 | information to be logged. |
| 1326 | |
Fred Drake | 6b3b046 | 2004-04-09 18:26:40 +0000 | [diff] [blame] | 1327 | \class{LogRecord} has no methods; it's just a repository for |
| 1328 | information about the logging event. The only reason it's a class |
| 1329 | rather than a dictionary is to facilitate extension. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1330 | |
| 1331 | \begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args, |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 1332 | exc_info} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1333 | Returns an instance of \class{LogRecord} initialized with interesting |
| 1334 | information. The \var{name} is the logger name; \var{lvl} is the |
| 1335 | numeric level; \var{pathname} is the absolute pathname of the source |
| 1336 | file in which the logging call was made; \var{lineno} is the line |
| 1337 | number in that file where the logging call is found; \var{msg} is the |
| 1338 | user-supplied message (a format string); \var{args} is the tuple |
| 1339 | which, together with \var{msg}, makes up the user message; and |
| 1340 | \var{exc_info} is the exception tuple obtained by calling |
| 1341 | \function{sys.exc_info() }(or \constant{None}, if no exception information |
| 1342 | is available). |
| 1343 | \end{classdesc} |
| 1344 | |
| 1345 | \subsection{Thread Safety} |
| 1346 | |
| 1347 | The logging module is intended to be thread-safe without any special work |
| 1348 | needing to be done by its clients. It achieves this though using threading |
| 1349 | locks; there is one lock to serialize access to the module's shared data, |
| 1350 | and each handler also creates a lock to serialize access to its underlying |
| 1351 | I/O. |
| 1352 | |
| 1353 | \subsection{Configuration} |
| 1354 | |
| 1355 | |
Fred Drake | 94ffbb7 | 2004-04-08 19:44:31 +0000 | [diff] [blame] | 1356 | \subsubsection{Configuration functions% |
| 1357 | \label{logging-config-api}} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1358 | |
Fred Drake | 9a5b6a6 | 2003-07-08 15:38:40 +0000 | [diff] [blame] | 1359 | The following functions allow the logging module to be |
| 1360 | configured. Before they can be used, you must import |
| 1361 | \module{logging.config}. Their use is optional --- you can configure |
| 1362 | the logging module entirely by making calls to the main API (defined |
| 1363 | in \module{logging} itself) and defining handlers which are declared |
Raymond Hettinger | 6f3eaa6 | 2003-06-27 21:43:39 +0000 | [diff] [blame] | 1364 | either in \module{logging} or \module{logging.handlers}. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1365 | |
| 1366 | \begin{funcdesc}{fileConfig}{fname\optional{, defaults}} |
| 1367 | Reads the logging configuration from a ConfigParser-format file named |
| 1368 | \var{fname}. This function can be called several times from an application, |
| 1369 | allowing an end user the ability to select from various pre-canned |
| 1370 | configurations (if the developer provides a mechanism to present the |
| 1371 | choices and load the chosen configuration). Defaults to be passed to |
| 1372 | ConfigParser can be specified in the \var{defaults} argument. |
| 1373 | \end{funcdesc} |
| 1374 | |
| 1375 | \begin{funcdesc}{listen}{\optional{port}} |
| 1376 | Starts up a socket server on the specified port, and listens for new |
| 1377 | configurations. If no port is specified, the module's default |
| 1378 | \constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurations |
| 1379 | will be sent as a file suitable for processing by \function{fileConfig()}. |
| 1380 | Returns a \class{Thread} instance on which you can call \method{start()} |
| 1381 | to start the server, and which you can \method{join()} when appropriate. |
| 1382 | To stop the server, call \function{stopListening()}. |
| 1383 | \end{funcdesc} |
| 1384 | |
| 1385 | \begin{funcdesc}{stopListening}{} |
| 1386 | Stops the listening server which was created with a call to |
| 1387 | \function{listen()}. This is typically called before calling \method{join()} |
| 1388 | on the return value from \function{listen()}. |
| 1389 | \end{funcdesc} |
| 1390 | |
Fred Drake | 94ffbb7 | 2004-04-08 19:44:31 +0000 | [diff] [blame] | 1391 | \subsubsection{Configuration file format% |
| 1392 | \label{logging-config-fileformat}} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1393 | |
Fred Drake | 6b3b046 | 2004-04-09 18:26:40 +0000 | [diff] [blame] | 1394 | The configuration file format understood by \function{fileConfig()} is |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1395 | based on ConfigParser functionality. The file must contain sections |
| 1396 | called \code{[loggers]}, \code{[handlers]} and \code{[formatters]} |
| 1397 | which identify by name the entities of each type which are defined in |
| 1398 | the file. For each such entity, there is a separate section which |
| 1399 | identified how that entity is configured. Thus, for a logger named |
| 1400 | \code{log01} in the \code{[loggers]} section, the relevant |
| 1401 | configuration details are held in a section |
| 1402 | \code{[logger_log01]}. Similarly, a handler called \code{hand01} in |
| 1403 | the \code{[handlers]} section will have its configuration held in a |
| 1404 | section called \code{[handler_hand01]}, while a formatter called |
| 1405 | \code{form01} in the \code{[formatters]} section will have its |
| 1406 | configuration specified in a section called |
| 1407 | \code{[formatter_form01]}. The root logger configuration must be |
| 1408 | specified in a section called \code{[logger_root]}. |
| 1409 | |
| 1410 | Examples of these sections in the file are given below. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1411 | |
| 1412 | \begin{verbatim} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1413 | [loggers] |
| 1414 | keys=root,log02,log03,log04,log05,log06,log07 |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1415 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1416 | [handlers] |
| 1417 | keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09 |
| 1418 | |
| 1419 | [formatters] |
| 1420 | keys=form01,form02,form03,form04,form05,form06,form07,form08,form09 |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1421 | \end{verbatim} |
| 1422 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1423 | The root logger must specify a level and a list of handlers. An |
| 1424 | example of a root logger section is given below. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1425 | |
| 1426 | \begin{verbatim} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1427 | [logger_root] |
| 1428 | level=NOTSET |
| 1429 | handlers=hand01 |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1430 | \end{verbatim} |
| 1431 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1432 | The \code{level} entry can be one of \code{DEBUG, INFO, WARNING, |
| 1433 | ERROR, CRITICAL} or \code{NOTSET}. For the root logger only, |
| 1434 | \code{NOTSET} means that all messages will be logged. Level values are |
| 1435 | \function{eval()}uated in the context of the \code{logging} package's |
| 1436 | namespace. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1437 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1438 | The \code{handlers} entry is a comma-separated list of handler names, |
| 1439 | which must appear in the \code{[handlers]} section. These names must |
| 1440 | appear in the \code{[handlers]} section and have corresponding |
| 1441 | sections in the configuration file. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1442 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1443 | For loggers other than the root logger, some additional information is |
| 1444 | required. This is illustrated by the following example. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1445 | |
| 1446 | \begin{verbatim} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1447 | [logger_parser] |
| 1448 | level=DEBUG |
| 1449 | handlers=hand01 |
| 1450 | propagate=1 |
| 1451 | qualname=compiler.parser |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1452 | \end{verbatim} |
| 1453 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1454 | The \code{level} and \code{handlers} entries are interpreted as for |
| 1455 | the root logger, except that if a non-root logger's level is specified |
| 1456 | as \code{NOTSET}, the system consults loggers higher up the hierarchy |
| 1457 | to determine the effective level of the logger. The \code{propagate} |
| 1458 | entry is set to 1 to indicate that messages must propagate to handlers |
| 1459 | higher up the logger hierarchy from this logger, or 0 to indicate that |
| 1460 | messages are \strong{not} propagated to handlers up the hierarchy. The |
| 1461 | \code{qualname} entry is the hierarchical channel name of the logger, |
Vinay Sajip | a13c60b | 2004-07-03 11:45:53 +0000 | [diff] [blame] | 1462 | that is to say the name used by the application to get the logger. |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1463 | |
| 1464 | Sections which specify handler configuration are exemplified by the |
| 1465 | following. |
| 1466 | |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1467 | \begin{verbatim} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1468 | [handler_hand01] |
| 1469 | class=StreamHandler |
| 1470 | level=NOTSET |
| 1471 | formatter=form01 |
| 1472 | args=(sys.stdout,) |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1473 | \end{verbatim} |
| 1474 | |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1475 | The \code{class} entry indicates the handler's class (as determined by |
| 1476 | \function{eval()} in the \code{logging} package's namespace). The |
| 1477 | \code{level} is interpreted as for loggers, and \code{NOTSET} is taken |
| 1478 | to mean "log everything". |
| 1479 | |
| 1480 | The \code{formatter} entry indicates the key name of the formatter for |
| 1481 | this handler. If blank, a default formatter |
| 1482 | (\code{logging._defaultFormatter}) is used. If a name is specified, it |
| 1483 | must appear in the \code{[formatters]} section and have a |
| 1484 | corresponding section in the configuration file. |
| 1485 | |
| 1486 | The \code{args} entry, when \function{eval()}uated in the context of |
| 1487 | the \code{logging} package's namespace, is the list of arguments to |
| 1488 | the constructor for the handler class. Refer to the constructors for |
| 1489 | the relevant handlers, or to the examples below, to see how typical |
| 1490 | entries are constructed. |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1491 | |
| 1492 | \begin{verbatim} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1493 | [handler_hand02] |
| 1494 | class=FileHandler |
| 1495 | level=DEBUG |
| 1496 | formatter=form02 |
| 1497 | args=('python.log', 'w') |
| 1498 | |
| 1499 | [handler_hand03] |
| 1500 | class=handlers.SocketHandler |
| 1501 | level=INFO |
| 1502 | formatter=form03 |
| 1503 | args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT) |
| 1504 | |
| 1505 | [handler_hand04] |
| 1506 | class=handlers.DatagramHandler |
| 1507 | level=WARN |
| 1508 | formatter=form04 |
| 1509 | args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT) |
| 1510 | |
| 1511 | [handler_hand05] |
| 1512 | class=handlers.SysLogHandler |
| 1513 | level=ERROR |
| 1514 | formatter=form05 |
| 1515 | args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER) |
| 1516 | |
| 1517 | [handler_hand06] |
Vinay Sajip | 20f42c4 | 2004-07-12 15:48:04 +0000 | [diff] [blame] | 1518 | class=handlers.NTEventLogHandler |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1519 | level=CRITICAL |
| 1520 | formatter=form06 |
| 1521 | args=('Python Application', '', 'Application') |
| 1522 | |
| 1523 | [handler_hand07] |
Vinay Sajip | 20f42c4 | 2004-07-12 15:48:04 +0000 | [diff] [blame] | 1524 | class=handlers.SMTPHandler |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1525 | level=WARN |
| 1526 | formatter=form07 |
| 1527 | args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject') |
| 1528 | |
| 1529 | [handler_hand08] |
Vinay Sajip | 20f42c4 | 2004-07-12 15:48:04 +0000 | [diff] [blame] | 1530 | class=handlers.MemoryHandler |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1531 | level=NOTSET |
| 1532 | formatter=form08 |
| 1533 | target= |
| 1534 | args=(10, ERROR) |
| 1535 | |
| 1536 | [handler_hand09] |
Vinay Sajip | 20f42c4 | 2004-07-12 15:48:04 +0000 | [diff] [blame] | 1537 | class=handlers.HTTPHandler |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1538 | level=NOTSET |
| 1539 | formatter=form09 |
| 1540 | args=('localhost:9022', '/log', 'GET') |
Skip Montanaro | 649698f | 2002-11-14 03:57:19 +0000 | [diff] [blame] | 1541 | \end{verbatim} |
Neal Norwitz | cd5c8c2 | 2003-01-25 21:29:41 +0000 | [diff] [blame] | 1542 | |
| 1543 | Sections which specify formatter configuration are typified by the following. |
| 1544 | |
| 1545 | \begin{verbatim} |
| 1546 | [formatter_form01] |
| 1547 | format=F1 %(asctime)s %(levelname)s %(message)s |
| 1548 | datefmt= |
| 1549 | \end{verbatim} |
| 1550 | |
| 1551 | The \code{format} entry is the overall format string, and the |
| 1552 | \code{datefmt} entry is the \function{strftime()}-compatible date/time format |
| 1553 | string. If empty, the package substitutes ISO8601 format date/times, which |
| 1554 | is almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S". |
| 1555 | The ISO8601 format also specifies milliseconds, which are appended to the |
| 1556 | result of using the above format string, with a comma separator. An example |
| 1557 | time in ISO8601 format is \code{2003-01-23 00:29:50,411}. |