logging
| Use Case | Command | Description |
|---|---|---|
| đ Basic console logging | logging.basicConfig(level=logging.INFO) | Configure root logger to print to stderr with default format |
| đ Log to file | logging.basicConfig(filename='app.log', level=logging.DEBUG) | Write log messages to a file |
| đˇī¸ Get a logger | logger = logging.getLogger(__name__) | Retrieve or create a logger for the current module |
| đ¨ī¸ Log messages | logger.debug('debug')logger.info('info')logger.warning('warning')logger.error('error')logger.critical('critical') | Log messages at different severity levels |
| â ī¸ Exception logging | logging.exception('Exception occurred') | Log an error with traceback information |
| đ¨ Custom format | logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') | Set a custom log record format |
| đĸ Get level name | logging.getLevelName(logging.DEBUG) | Returns 'DEBUG' |
| đĢ Disable logging | logging.disable(logging.CRITICAL) | Suppress all messages at or below the specified level |
| â Add a handler | logger.addHandler(logging.FileHandler('debug.log')) | Attach a file handler to a logger |
| đ LoggerAdapter | adapter = logging.LoggerAdapter(logger, {'user': 'john'}) | Add contextual info to log messages |
https://docs.python.org/3.10/library/logging.html
The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above.
Logging package for Python. Based on PEP 282 and comments thereto in comp.lang.python.
Copyright (C) 2001-2019 Vinay Sajip. All Rights Reserved.
To use, simply import logging and log away!
builtins.object
BufferingFormatter(linefmt=None)
A formatter suitable for formatting a number of records.
Methods defined here:
__init__(self, linefmt=None)format(self, records)formatFooter(self, records)formatHeader(self, records)Data descriptors defined here:
__dict__ â dictionary for instance variables (if defined)__weakref__ â list of weak references to the object (if defined)
FileHandler(filename, mode='a', encoding=None, delay=False, errors=None)
A handler class which writes formatted logging records to disk files.
Method resolution order:
FileHandler
StreamHandler
Handler
Filterer
builtins.object
Methods defined here:
__init__(self, filename, mode='a', encoding=None, delay=False, errors=None)__repr__(self)close(self)emit(self, record)_closed=True, record will not be emitted (see Issue #42378).Methods inherited from StreamHandler: flush, setStream
Data inherited from StreamHandler: terminator = '\n'
Methods inherited from Handler: acquire, createLock, format, get_name, handle, handleError, release, setFormatter, setLevel, set_name
Data descriptors inherited from Handler: name
Methods inherited from Filterer: addFilter, filter, removeFilter
Data descriptors inherited from Filterer: __dict__, __weakref__
Filter(name='')
Filter instances are used to perform arbitrary filtering of LogRecords. Loggers and Handlers can optionally use Filter instances to filter records as desired. The base filter class only allows events which are below a certain point in the logger hierarchy. For example, a filter initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the empty string, all events are passed.
Methods defined here:
__init__(self, name='')filter(self, record)Data descriptors defined here:
__dict__ â dictionary for instance variables (if defined)__weakref__ â list of weak references to the object (if defined)
Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)
Formatter instances are used to convert a LogRecord to text.
Formatters need to know how a LogRecord is constructed. They are
responsible for converting a LogRecord to (usually) a string which can
be interpreted by either a human or an external system. The base Formatter
allows a formatting string to be specified. If none is supplied, the
style-dependent default value, "%(message)s", "{message}", or
"${message}", is used.
The Formatter can be initialized with a format string which makes use of knowledge of the LogRecord attributes. Currently, the useful attributes in a LogRecord are:
%(name)s â Name of the logger (logging channel)%(levelno)s â Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL)%(levelname)s â Text logging level for the message%(pathname)s â Full pathname of the source file where the logging call was issued (if available)%(filename)s â Filename portion of pathname%(module)s â Module (name portion of filename)%(lineno)d â Source line number where the logging call was issued (if available)%(funcName)s â Function name%(created)f â Time when the LogRecord was created (time.time() return value)%(asctime)s â Textual time when the LogRecord was created%(msecs)d â Millisecond portion of the creation time%(relativeCreated)d â Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded%(thread)d â Thread ID (if available)%(threadName)s â Thread name (if available)%(process)d â Process ID (if available)%(message)s â The result of record.getMessage(), computed just as the record is emittedMethods defined here:
__init__(self, fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)'%', '{' or '$' to specify formatting style.format(self, record)formatException(self, ei)traceback.print_exception().formatMessage(self, record)formatStack(self, stack_info)formatTime(self, record, datefmt=None)converter attribute can be set to a function like time.localtime() or time.gmtime().usesTime(self)Static methods defined here:
converter = localtime(...)Data descriptors defined here:
__dict__ â dictionary for instance variables (if defined)__weakref__ â list of weak references to the object (if defined)Data and other attributes:
default_msec_format = '%s,%03d'default_time_format = '%Y-%m-%d %H:%M:%S'
Handler(level=0)
Handler instances dispatch logging events to specific destinations.
The base handler class. Acts as a placeholder which defines the Handler
interface. Handlers can optionally use Formatter instances to format
records as desired. By default, no formatter is specified; in this case,
the 'raw' message as determined by record.message is logged.
Method resolution order:
Handler
Filterer
builtins.object
Methods defined here:
__init__(self, level=0)__repr__(self)acquire(self)close(self)_handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.createLock(self)emit(self, record)flush(self)format(self, record)get_name(self)handle(self, record)handleError(self, record)emit() call. If raiseExceptions is false, exceptions get silently ignored.release(self)setFormatter(self, fmt)setLevel(self, level)level must be an int or a str.set_name(self, name)Data descriptors defined here: name
Methods inherited from Filterer: addFilter, filter, removeFilter
Data descriptors inherited from Filterer: __dict__, __weakref__
LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None, **kwargs)
A LogRecord instance represents an event being logged.
LogRecord instances are created every time something is logged. They
contain all the information pertinent to the event being logged. The
main information passed in is in msg and args, which are combined
using str(msg) % args to create the message field of the record. The
record also includes information such as when the record was created,
the source line where the logging call was made, and any exception
information to be logged.
Methods defined here:
__init__(self, name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None, **kwargs)__repr__(self)getMessage(self)Data descriptors defined here:
__dict__ â dictionary for instance variables (if defined)__weakref__ â list of weak references to the object (if defined)
Logger(name, level=0)
Instances of the Logger class represent a single logging channel. A "logging channel" indicates an area of an application. Exactly how an "area" is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified by a unique string. Application areas can be nested (e.g. an area of "input processing" might include sub-areas "read CSV files", "read XLS files" and "read Gnumeric files"). To cater for this natural nesting, channel names are organized into a namespace hierarchy where levels are separated by periods, much like the Java or Python package namespace. There is no arbitrary limit to the depth of nesting.
Method resolution order:
Logger
Filterer
builtins.object
Methods defined here:
__init__(self, name, level=0)__reduce__(self)__repr__(self)addHandler(self, hdlr)callHandlers(self, record)critical(self, msg, *args, **kwargs)msg % args with severity 'CRITICAL'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.critical("Houston, we have a %s", "major disaster", exc_info=1)debug(self, msg, *args, **kwargs)msg % args with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)error(self, msg, *args, **kwargs)msg % args with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.error("Houston, we have a %s", "major problem", exc_info=1)exception(self, msg, *args, exc_info=True, **kwargs)fatal(self, msg, *args, **kwargs)findCaller(self, stack_info=False, stacklevel=1)getChild(self, suffix)logging.getLogger('abc').getChild('def.ghi') is the same as logging.getLogger('abc.def.ghi'). It's useful, for example, when the parent logger is named using __name__ rather than a literal string.getEffectiveLevel(self)handle(self, record)hasHandlers(self)info(self, msg, *args, **kwargs)msg % args with severity 'INFO'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.info("Houston, we have a %s", "interesting problem", exc_info=1)isEnabledFor(self, level)log(self, level, msg, *args, **kwargs)msg % args with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1)makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)removeHandler(self, hdlr)setLevel(self, level)level must be an int or a str.warn(self, msg, *args, **kwargs)warning(self, msg, *args, **kwargs)msg % args with severity 'WARNING'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)Data and other attributes: manager = <logging.Manager object>, root = <RootLogger root (WARNING)>
Methods inherited from Filterer: addFilter, filter, removeFilter
Data descriptors inherited from Filterer: __dict__, __weakref__
LoggerAdapter(logger, extra=None)
An adapter for loggers which makes it easier to specify contextual information in logging output.
Methods defined here:
__init__(self, logger, extra=None)adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))__repr__(self)critical(self, msg, *args, **kwargs)debug(self, msg, *args, **kwargs)error(self, msg, *args, **kwargs)exception(self, msg, *args, exc_info=True, **kwargs)getEffectiveLevel(self)hasHandlers(self)info(self, msg, *args, **kwargs)isEnabledFor(self, level)log(self, level, msg, *args, **kwargs)process(self, msg, kwargs)setLevel(self, level)warn(self, msg, *args, **kwargs)warning(self, msg, *args, **kwargs)Readonly properties: name
Data descriptors: __dict__, __weakref__, manager
NullHandler(level=0)
This handler does nothing. It's intended to be used to avoid the "No handlers could be found for logger XXX" one-off warning. This is important for library code, which may contain code to log events. If a user of the library does not configure logging, the one-off warning might be produced; to avoid this, the library developer simply needs to instantiate a NullHandler and add it to the top-level logger of the library module or package.
Method resolution order:
NullHandler
Handler
Filterer
builtins.object
Methods defined here:
createLock(self)emit(self, record)handle(self, record)Methods inherited from Handler: __init__, __repr__, acquire, close, flush, format, get_name, handleError, release, setFormatter, setLevel, set_name
Data descriptors inherited from Handler: name
Methods inherited from Filterer: addFilter, filter, removeFilter
Data descriptors inherited from Filterer: __dict__, __weakref__
StreamHandler(stream=None)
A handler class which writes logging records, appropriately formatted, to a stream. Note that this class does not close the stream, as sys.stdout or sys.stderr may be used.
Method resolution order:
StreamHandler
Handler
Filterer
builtins.object
Methods defined here:
__init__(self, stream=None)__repr__(self)emit(self, record)traceback.print_exception and appended to the stream.flush(self)setStream(self, stream)Data and other attributes: terminator = '\n'
Methods inherited from Handler: acquire, close, createLock, format, get_name, handle, handleError, release, setFormatter, setLevel, set_name
Data descriptors inherited from Handler: name
Methods inherited from Filterer: addFilter, filter, removeFilter
Data descriptors inherited from Filterer: __dict__, __weakref__
addLevelName(level, levelName)
Associate 'levelName' with 'level'. This is used when converting levels to text during message formatting.
basicConfig(**kwargs)
Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured, unless the keyword argument force is set to True. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package.
The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger. A number of optional keyword arguments may be specified:
filename â Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler.filemode â Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to 'a').format â Use the specified format string for the handler.datefmt â Use the specified date/time format.style â If a format string is specified, use this to specify the type of format string (possible values '%', '{', '$', defaults to '%').level â Set the root logger level to the specified level.stream â Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored.handlers â If specified, this should be an iterable of already created handlers, which will be added to the root handler. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function.force â If this keyword is specified as true, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments.encoding â If specified together with a filename, this encoding is passed to the created FileHandler, causing it to be used when the file is opened.errors â If specified together with a filename, this value is passed to the created FileHandler, causing it to be used when the file is opened in text mode. If not specified, the default value is backslashreplace.Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed.
.. versionchanged:: 3.2 Added the style parameter.
.. versionchanged:: 3.3 Added the handlers parameter. A ValueError is now thrown for incompatible arguments.
.. versionchanged:: 3.8 Added the force parameter.
.. versionchanged:: 3.9 Added the encoding and errors parameters.
captureWarnings(capture)
If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations.
critical(msg, *args, **kwargs)
Log a message with severity 'CRITICAL' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
debug(msg, *args, **kwargs)
Log a message with severity 'DEBUG' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
disable(level=50)
Disable all logging calls of severity 'level' and below.
error(msg, *args, **kwargs)
Log a message with severity 'ERROR' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
exception(msg, *args, exc_info=True, **kwargs)
Log a message with severity 'ERROR' on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format.
fatal(msg, *args, **kwargs)
Don't use this function, use critical() instead.
getLevelName(level)
Return the textual or numeric representation of logging level 'level'. If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, INFO, DEBUG) then you get the corresponding string. If you have associated levels with names using addLevelName then the name you have associated with 'level' is returned. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned. If a string representation of the level is passed in, the corresponding numeric value is returned. If no matching numeric or string value is passed in, the string 'Level %s' % level is returned.
getLogRecordFactory()
Return the factory to be used when instantiating a log record.
getLogger(name=None)
Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger.
getLoggerClass()
Return the class to be used when instantiating a logger.
info(msg, *args, **kwargs)
Log a message with severity 'INFO' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
log(level, msg, *args, **kwargs)
Log msg % args with the integer severity 'level' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
makeLogRecord(dict)
Make a LogRecord whose attributes are defined by the specified dictionary. This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance.
setLogRecordFactory(factory)
Set the factory to be used when instantiating a log record.
:param factory: A callable which will be called to instantiate a log record.
setLoggerClass(klass)
Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__().
shutdown(handlerList=[<weakref at 0x7ff8732be390; to '_StderrHandler' at 0x7ff8732cc4c0>])
Perform any cleanup actions in the logging system (e.g. flushing buffers). Should be called at application exit.
warn(msg, *args, **kwargs)
warning(msg, *args, **kwargs)
Log a message with severity 'WARNING' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
BASIC_FORMAT = '%(levelname)s:%(name)s:%(message)s'CRITICAL = 50DEBUG = 10ERROR = 40FATAL = 50INFO = 20NOTSET = 0WARN = 30WARNING = 30__all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', ...__status__ = 'production'lastResort = <_StderrHandler <stderr> (WARNING)>raiseExceptions = True0.5.1.2
07 February 2010
Vinay Sajip <vinay_sajip AT red-dove.com>
/usr/lib/python3.10/logging/__init__.py
Generated by phpman v4.9.27 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-18 19:09 @216.73.216.114
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format