The key benefit of having the logging API provided by a standard library moduleis that all Python modules can participate in logging, so your application logcan include your own messages integrated with messages from third-partymodules.
The key feature of this idiomatic usage is that the majority of code is simplycreating a module level logger with getLogger(__name__), and using thatlogger to do any needed logging. This is concise, while allowing downstreamcode fine-grained control if needed. Logged messages to the module-level loggerget forwarded to handlers of loggers in higher-level modules, all the way up tothe highest-level logger known as the root logger; this approach is known ashierarchical logging.
For logging to be useful, it needs to be configured: setting the levels anddestinations for each logger, potentially changing how specific modules log,often based on command-line arguments or application configuration. In mostcases, like the one above, only the root logger needs to be so configured, sinceall the lower level loggers at module level eventually forward their messages toits handlers. basicConfig() provides a quick way to configurethe root logger that handles many use cases.
The module provides a lot of functionality and flexibility. If you areunfamiliar with logging, the best way to get to grips with it is to view thetutorials (see the links above and on the right).
Loggers have the following attributes and methods. Note that Loggers shouldNEVER be instantiated directly, but always through the module-level functionlogging.getLogger(name). Multiple calls to getLogger() with the samename will always return a reference to the same Logger object.
If you attach a handler to a logger and one or more of itsancestors, it may emit the same record multiple times. In general, youshould not need to attach a handler to more than one logger - if you justattach it to the appropriate logger which is highest in the loggerhierarchy, then it will see all events logged by all descendant loggers,provided that their propagate setting is left set to True. A commonscenario is to attach handlers only to the root logger, and to letpropagation take care of the rest.
When a logger is created, the level is set to NOTSET (which causesall messages to be processed when the logger is the root logger, or delegationto the parent when the logger is a non-root logger). Note that the root loggeris created with level WARNING.
Indicates the effective level for this logger. If a value other thanNOTSET has been set using setLevel(), it is returned. Otherwise,the hierarchy is traversed towards the root until a value other thanNOTSET is found, and that value is returned. The value returned isan integer, typically one of logging.DEBUG, logging.INFOetc.
Returns a logger which is a descendant to this logger, as determined by the suffix.Thus, logging.getLogger('abc').getChild('def.ghi') would return the samelogger as would be returned by logging.getLogger('abc.def.ghi'). This is aconvenience method, useful when the parent logger is named using e.g. __name__rather than a literal string.
Logs a message with level DEBUG on this logger. The msg is themessage format string, and the args are the arguments which are merged intomsg using the string formatting operator. (Note that this means that you canuse keywords in the format string, together with a single dictionary argument.)No % formatting operation is performed on msg when no args are supplied.
If exc_info does not evaluate as false, it causes exception information to beadded to the logging message. If an exception tuple (in the format returned bysys.exc_info()) or an exception instance is provided, it is used;otherwise, sys.exc_info() is called to get the exception information.
The second optional keyword argument is stack_info, which defaults toFalse. If true, stack information is added to the loggingmessage, including the actual logging call. Note that this is not the samestack information as that displayed through specifying exc_info: Theformer is stack frames from the bottom of the stack up to the logging callin the current thread, whereas the latter is information about stack frameswhich have been unwound, following an exception, while searching forexception handlers.
You can specify stack_info independently of exc_info, e.g. to just showhow you got to a certain point in your code, even when no exceptions wereraised. The stack frames are printed following a header line which says:
The third optional keyword argument is stacklevel, which defaults to 1.If greater than 1, the corresponding number of stack frames are skippedwhen computing the line number and function name set in the LogRecordcreated for the logging event. This can be used in logging helpers so thatthe function name, filename and line number recorded are not the informationfor the helper function/method, but rather its caller. The name of thisparameter mirrors the equivalent one in the warnings module.
The fourth keyword argument is extra which can be used to pass adictionary which is used to populate the __dict__ of the LogRecordcreated for the logging event with user-defined attributes. These customattributes can then be used as you like. For example, they could beincorporated into logged messages. For example:
The keys in the dictionary passed in extra should not clash with the keys usedby the logging system. (See the section on LogRecord attributes for moreinformation on which keys are used by the logging system.)
While this might be annoying, this feature is intended for use in specializedcircumstances, such as multi-threaded servers where the same code executes inmany contexts, and interesting conditions which arise are dependent on thiscontext (such as remote client IP address and authenticated user name, in theabove example). In such circumstances, it is likely that specializedFormatters would be used with particular Handlers.
Logs a message with level ERROR on this logger. The arguments areinterpreted as for debug(). Exception info is added to the loggingmessage. This method should only be called from an exception handler.
The stacklevel parameter is passed from code calling the debug()and other APIs. If greater than 1, the excess is used to skip stack framesbefore determining the values to be returned. This will generally be usefulwhen calling logging APIs from helper/wrapper code, so that the informationin the event log refers not to the helper/wrapper code, but to the code thatcalls it.
Handles a record by passing it to all handlers associated with this logger andits ancestors (until a false value of propagate is found). This method is usedfor unpickled records received from a socket, as well as those created locally.Logger-level filtering is applied using filter().
The numeric values of logging levels are given in the following table. These areprimarily of interest if you want to define your own levels, and need them tohave specific values relative to the predefined levels. If you define a levelwith the same numeric value, it overwrites the predefined value; the predefinedname is lost.
When set on a logger, indicates thatancestor loggers are to be consultedto determine the effective level.If that still resolves toNOTSET, then all eventsare logged. When set on a handler,all events are handled.
Handlers have the following attributes and methods. Note that Handleris never instantiated directly; this class acts as a base for more usefulsubclasses. However, the __init__() method in subclasses needs to callHandler.__init__().
Sets the threshold for this handler to level. Logging messages which areless severe than level will be ignored. When a handler is created, thelevel is set to NOTSET (which causes all messages to beprocessed).
Tidy up any resources used by the handler. This version does no output butremoves the handler from an internal list of handlers which is closed whenshutdown() is called. Subclasses should ensure that this gets calledfrom overridden close() methods.
This method should be called from handlers when an exception is encounteredduring an emit() call. If the module-level attributeraiseExceptions is False, exceptions get silently ignored. This iswhat is mostly wanted for a logging system - most users will not care abouterrors in the logging system, they are more interested in applicationerrors. You could, however, replace this with a custom handler if you wish.The specified record is the one which was being processed when the exceptionoccurred. (The default value of raiseExceptions is True, as that ismore useful during development).
This method is called after a handler-level lock is acquired, whichis released after this method returns. When you override this method, notethat you should be careful when calling anything that invokes other parts ofthe logging API which might do locking, because that might result in adeadlock. Specifically:
Many logging APIs lock the module-level lock. If such an API is calledfrom this method, it could cause a deadlock if a configuration call ismade on another thread, because that thread will try to acquire themodule-level lock before the handler-level lock, whereas this threadtries to acquire the module-level lock after the handler-level lock(because in this method, the handler-level lock has already been acquired).
This function uses a user-configurable function to convert the creationtime to a tuple. By default, time.localtime() is used; to changethis for a particular formatter instance, set the converter attributeto a function with the same signature as time.localtime() ortime.gmtime(). To change it for all formatters, for example if youwant all logging times to be shown in GMT, set the converterattribute in the Formatter class.
Formats the specified exception information (a standard exception tuple asreturned by sys.exc_info()) as a string. This default implementationjust uses traceback.print_exception(). The resulting string isreturned.
A base formatter class suitable for subclassing when you want to format anumber of records. You can pass a Formatter instance which you wantto use to format each line (that corresponds to a single record). If notspecified, the default formatter (which just outputs the event message) isused as the line formatter.
c80f0f1006