Does python have a log?
Source code: Lib/logging/__init__.py Show This module defines functions and classes which implement a flexible event logging system for applications and libraries. The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging, so your application log can include your own messages integrated with messages from third-party modules. The simplest example: >>> import logging >>> logging.warning('Watch out!') WARNING:root:Watch out! The module provides a lot of functionality and flexibility. If you are unfamiliar with logging, the best way to get to grips with it is to view the tutorials (see the links above and on the right). The basic classes defined by the module, together with their functions, are listed below.
Logger Objects¶Loggers have the following attributes and methods. Note that Loggers should NEVER be instantiated directly, but always through the module-level function The logging. Logger ¶
propagate ¶If this attribute evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered. If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers. Spelling it out with an example: If the propagate attribute of the logger named The constructor sets this attribute to Note If you attach a handler to a logger and one or more of its ancestors, it may emit the same record multiple times. In general, you should not need to attach a handler to more than
one logger - if you just attach it to the appropriate logger which is highest in the logger hierarchy, then it will see all events logged by all descendant loggers, provided that their propagate setting is left set to setLevel (level)¶Sets the threshold for this logger to level. Logging messages which are less severe than level will be ignored; logging messages which have severity level or higher will be emitted by whichever handler or handlers service this logger, unless a handler’s level has been set to a higher severity level than level. When a logger is created, the level is set to The term ‘delegation to the parent’ means that if a logger has a level of NOTSET, its chain of ancestor loggers is traversed until either an ancestor with a level other than NOTSET is found, or the root is reached. If an ancestor is found with a level other than NOTSET, then that ancestor’s level is treated as the effective level of the logger where the ancestor search began, and is used to determine how a logging event is handled. If the root is reached, and it has a level of NOTSET, then all messages will be processed. Otherwise, the root’s level will be used as the effective level. See Logging Levels for a list of levels. Changed in version 3.2: The level parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as isEnabledFor (level)¶Indicates if a message of severity level would be processed by this logger. This method checks first the module-level level set by getEffectiveLevel ()¶Indicates the effective level for this logger. If a value other than getChild (suffix)¶Returns a logger which is a descendant to this logger, as determined by the suffix. Thus, New in version 3.2. debug (msg, *args, **kwargs)¶Logs a message with level There are four keyword arguments in kwargs which are inspected: exc_info, stack_info, stacklevel and extra. If exc_info
does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by The second
optional keyword argument is stack_info, which defaults to You can specify stack_info independently of exc_info, e.g. to just show how you got to a certain point in your code, even when no exceptions were raised. The stack frames are printed following a header line which says: Stack (most recent call last): This mimics the The third optional keyword argument is stacklevel, which defaults to The fourth keyword argument is extra which can be used to pass a dictionary which is used to populate the __dict__ of the FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s' logging.basicConfig(format=FORMAT) d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} logger = logging.getLogger('tcpserver') logger.warning('Protocol problem: %s', 'connection reset', extra=d) would print something like 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset The keys in the dictionary passed in extra should not clash with the keys used by the logging system. (See the section on LogRecord attributes for more information on which keys are used by the logging system.) If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts,
and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized If no handler is attached to this logger (or any of its ancestors, taking into account the relevant Changed in version 3.2: The stack_info parameter was added. Changed in version 3.5: The exc_info parameter can now accept exception instances. Changed in version 3.8: The stacklevel parameter was added. info (msg, *args,
**kwargs)¶Logs a message with level warning (msg, *args, **kwargs)¶Logs a message with level Note There is an obsolete method error (msg, *args,
**kwargs)¶Logs a message with level critical (msg, *args, **kwargs)¶Logs a message with level log (level, msg, *args, **kwargs)¶Logs a
message with integer level level on this logger. The other arguments are interpreted as for exception (msg, *args,
**kwargs)¶Logs a message with level addFilter (filter)¶Adds the specified filter filter to this logger. removeFilter (filter)¶Removes the specified filter filter from this logger. filter (record)¶Apply this logger’s filters to the record and return addHandler (hdlr)¶Adds the specified handler hdlr to this logger. removeHandler (hdlr)¶Removes the specified handler hdlr from this logger. findCaller (stack_info=False,
stacklevel=1)¶Finds the caller’s source filename and line number. Returns the filename, line number, function name and stack information as a 4-element tuple. The stack information is returned as The stacklevel parameter is
passed from code calling the handle (record)¶Handles a record by passing it to all handlers associated with this logger and its ancestors (until a false value of propagate is found). This method is used for unpickled records received from a socket, as well as those created locally. Logger-level
filtering is applied using makeRecord (name, level, fn, lno, msg, args, exc_info, func=None,
extra=None, sinfo=None)¶This is a factory method which can be overridden in subclasses to create specialized hasHandlers ()¶Checks to see if this logger has any handlers configured. This is done by looking for handlers in this logger and its parents in the logger hierarchy. Returns New in version 3.2. Changed in version 3.7: Loggers can now be pickled and unpickled. Logging Levels¶The numeric values of logging levels are given in the following table. These are primarily of interest if you want to define your own levels, and need them to have specific values relative to the predefined levels. If you define a level with the same numeric value, it overwrites the predefined value; the predefined name is lost.
Handler Objects¶Handlers have the following attributes and methods. Note that logging. Handler ¶
__init__ (level=NOTSET)¶Initializes the createLock ()¶Initializes a thread lock which can be used to serialize access to underlying I/O functionality which may not be threadsafe. acquire ()¶Acquires the thread lock created with release ()¶Releases the thread lock acquired with setLevel (level)¶Sets the threshold for this handler to level. Logging messages which are less severe than level will be ignored. When a handler is created, the level is set to See Logging Levels for a list of levels. Changed in version 3.2: The level parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as setFormatter (fmt)¶Sets the addFilter (filter)¶Adds the specified filter filter to this handler. removeFilter (filter)¶Removes the specified filter filter from this handler. filter (record)¶Apply this handler’s filters to the record and return flush ()¶Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses. close ()¶Tidy up any resources used by the handler. This version does no output but removes the handler from an internal list of handlers which is closed when handle (record)¶Conditionally emits the specified logging record, depending on filters which may have been added to the handler. Wraps the actual emission of the record with acquisition/release of the I/O thread lock. handleError (record)¶This method should be called from handlers when an
exception is encountered during an format (record)¶Do formatting for a record - if a formatter is set, use it. Otherwise, use the default formatter for the module. emit (record)¶Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a
For a list of handlers included as standard, see Formatter Objects¶
A Formatter can be initialized with a
format string which makes use of knowledge of the The useful mapping keys in a logging. Formatter (fmt=None, datefmt=None, style='%', validate=True, *,
defaults=None)¶Returns a new instance of the The style parameter can be one of ‘%’, ‘{’ or ‘$’ and determines how the format string will be merged with its data: using one of %-formatting,
The defaults parameter can be a dictionary with default values to use in custom fields. For example: Changed in version 3.2: The style parameter was added. Changed in version 3.8: The validate parameter was added. Incorrect or mismatched style and fmt will raise a Changed in version 3.10: The defaults parameter was added. format (record)¶The record’s attribute dictionary is used as the operand to a string formatting operation. Returns the resulting string. Before
formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using msg % args. If the formatting string contains If stack information is available,
it’s appended after the exception information, using formatTime (record,
datefmt=None)¶This method should be called from This function uses a user-configurable function to convert the creation time to a tuple. By default, Changed in version 3.3:
Previously, the default format was hard-coded as in this example: Changed in version 3.9: The formatException (exc_info)¶Formats the specified exception information (a standard exception tuple as returned by formatStack (stack_info)¶Formats the specified stack
information (a string as returned by logging. BufferingFormatter (linefmt=None)¶A base formatter class suitable for subclassing when you want to format a number of records. You can pass a
Return a header for a list of records. The base implementation just returns the empty string. You will need to override this method if you want specific behaviour, e.g. to show the count of records, a title or a separator line. Return a footer for a list of records. The base implementation just returns the empty string. You will need to override this method if you want specific behaviour, e.g. to show the count of records or a separator line. format (records)¶Return formatted text for a list of records. The base implementation just returns the empty string if there are no records; otherwise, it returns the concatenation of the header, each record formatted with the line formatter, and the footer. Filter Objects¶
logging. Filter (name='')¶Returns an instance of the
filter (record)¶Is the specified record to be logged? Returns zero for no, nonzero for yes. If deemed appropriate, the record may be modified in-place by this method. Note that filters attached to handlers are consulted before an event is emitted by the handler,
whereas filters attached to loggers are consulted whenever an event is logged (using You don’t actually need to subclass Changed in version 3.2: You don’t need to create specialized Although filters
are used primarily to filter records based on more sophisticated criteria than levels, they get to see every record which is processed by the handler or logger they’re attached to: this can be useful if you want to do things like counting how many records were processed by a particular logger or handler, or adding, changing or removing attributes in the LogRecord Objects¶
logging. LogRecord (name, level, pathname, lineno, msg, args, exc_info,
func=None, sinfo=None)¶Contains all the information pertinent to the event being logged. The primary information is passed in msg and args, which are combined using
getMessage ()¶Returns the message for this Changed in version 3.2: The creation of a
This functionality can be used to inject your own values into a old_factory = logging.getLogRecordFactory() def record_factory(*args, **kwargs): record = old_factory(*args, **kwargs) record.custom_attribute = 0xdecafbad return record logging.setLogRecordFactory(record_factory) With this pattern, multiple factories could be chained, and as long as they don’t overwrite each other’s attributes or unintentionally overwrite the standard attributes listed above, there should be no surprises. LogRecord attributes¶The LogRecord has a number of attributes, most of which are derived from the parameters to the constructor. (Note that the names do not always correspond exactly between the LogRecord constructor parameters and the LogRecord attributes.) These attributes can be used to merge data from the record into the format string. The following table lists (in alphabetical order) the attribute names, their meanings and the corresponding placeholder in a %-style format string. If you are using {}-formatting
( In the case of {}-formatting, you can
specify formatting flags by placing them after the attribute name, separated from it with a colon. For example: a placeholder of
Changed in version 3.1: processName was added. LoggerAdapter Objects¶
logging. LoggerAdapter (logger,
extra)¶Returns an instance of process (msg, kwargs)¶Modifies the message and/or keyword arguments passed to a logging call in order to insert contextual information. This implementation takes the object passed as extra to the constructor and adds it to kwargs using key ‘extra’. The return value is a (msg, kwargs) tuple which has the (possibly modified) versions of the arguments passed in. In addition to the above,
Changed in version 3.6: Attribute Thread Safety¶The logging module is intended to be thread-safe without any special work needing to be done by its clients. It achieves this though using threading locks; there is one lock to serialize access to the module’s shared data, and each handler also creates a lock to serialize access to its underlying I/O. If you are implementing asynchronous signal handlers using the Module-Level Functions¶In addition to the classes described above, there are a number of module-level functions. logging. getLogger (name=None)¶Return a logger with the specified name or, if name is All calls to this function with a given name return the same logger instance. This means that logger instances never need to be passed between different parts of an application. logging. getLoggerClass ()¶Return either the standard class MyLogger(logging.getLoggerClass()): # ... override behaviour here logging. getLogRecordFactory ()¶Return a callable which is used to create a New in version 3.2: This function has been provided, along with
See
logging. debug (msg, *args,
**kwargs)¶Logs a message with level There are three keyword arguments in kwargs which are inspected: exc_info which, if it does not evaluate as false, causes exception information to be added to the logging message. If an exception tuple (in the format returned by The second optional keyword argument is stack_info, which defaults to You can specify stack_info independently of exc_info, e.g. to just show how you got to a certain point in your code, even when no exceptions were raised. The stack frames are printed following a header line which says: Stack (most recent call last): This mimics the The third optional keyword argument is extra which can be used to pass a dictionary which is used to populate the __dict__ of the LogRecord created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages. For example: FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s' logging.basicConfig(format=FORMAT) d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} logging.warning('Protocol problem: %s', 'connection reset', extra=d) would print something like: 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset The keys in the dictionary passed in
extra should not clash with the keys used by the logging system. (See the If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the
While this might be annoying, this feature is intended
for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized This function (as well as Changed in version 3.2: The stack_info parameter was added. logging. info (msg, *args, **kwargs)¶Logs a message with level logging. warning (msg, *args, **kwargs)¶Logs a message with level Note There is an obsolete function logging. error (msg,
*args, **kwargs)¶Logs a message with level logging. critical (msg, *args, **kwargs)¶Logs a message with level logging. exception (msg, *args, **kwargs)¶Logs a message with level
logging. log (level, msg, *args,
**kwargs)¶Logs a message with level level on the root logger. The other arguments are interpreted as for logging. disable (level=CRITICAL)¶Provides an overriding level level for all loggers which takes precedence over the logger’s own level. When the need arises to temporarily throttle logging output down across the whole application, this function can
be useful. Its effect is to disable all logging calls of severity level and below, so that if you call it with a value of INFO, then all INFO and DEBUG events would be discarded, whereas those of severity WARNING and above would be processed according to the logger’s effective level. If Note that if you have defined any custom
logging level higher than Changed in version 3.7: The level parameter was defaulted to level logging. addLevelName (level, levelName)¶Associates level level with text levelName in an internal dictionary, which is used to map numeric levels to a textual representation, for example when a
Note If you are thinking of defining your own levels, please see the section on Custom Levels. logging. getLevelName (level)¶Returns the textual or numeric representation of logging level level. If level is one
of the predefined levels The level parameter also accepts a string representation of the level such as ‘INFO’. In such cases, this functions returns the corresponding numeric value of the level. If no matching numeric or string value is passed in, the string ‘Level %s’ % level is returned. Note Levels are internally integers (as they need to be compared in the logging logic). This function is used to convert between an integer level and the level name displayed in the formatted log output by
means of the Changed in version 3.4: In Python versions earlier than 3.4, this function could also be passed a text level, and would return the corresponding numeric value of the level. This undocumented behaviour was considered a mistake, and was removed in Python 3.4, but reinstated in 3.4.2 due to retain backward compatibility. logging. makeLogRecord (attrdict)¶Creates and returns a new logging. basicConfig (**kwargs)¶Does basic configuration for the logging system by creating a This function does nothing if the root logger already has handlers configured, unless the keyword argument force is set to Note This function should be called from the main thread before other threads are started. In versions of Python prior to 2.7.1 and 3.2, if this function is called from multiple threads, it is possible (in rare circumstances) that a handler will be added to the root logger more than once, leading to unexpected results such as messages being duplicated in the log. The following keyword arguments are supported.
Changed in version 3.2: The style argument was added. Changed in version 3.3: The handlers argument was added. Additional checks were added to catch situations where incompatible arguments are specified (e.g. handlers together with stream or filename, or stream together with filename). Changed in version 3.8: The force argument was added. Changed in version 3.9: The encoding and errors arguments were added. logging. shutdown ()¶Informs the logging system to perform an orderly shutdown by flushing and closing all handlers. This should be called at application exit and no further use of the logging system should be made after this call. When the logging module is imported, it registers this function as an exit handler (see logging. setLoggerClass (klass)¶Tells the logging system to use the class klass when instantiating a logger. The class should define logging. setLogRecordFactory (factory)¶Set a callable which is used to create a factory – The factory callable to be used to instantiate a log record. New in version 3.2: This function has been
provided, along with The factory has the following signature:
Module-Level Attributes¶logging. lastResort ¶A “handler of last resort” is available through this attribute. This is a
New in version 3.2. Integration with the warnings module¶The logging. captureWarnings (capture)¶This function is used to turn the capture of warnings by logging on and off. If capture is If capture is See also Modulelogging.config Configuration API for the logging module. Modulelogging.handlers Useful handlers included with the logging module. PEP 282 - A Logging SystemThe proposal which described this feature for inclusion in the Python standard library. Original Python logging packageThis is the original source for the |