pydoc > logging

📛 NAME

logging

🚀 Quick Reference

Use CaseCommandDescription
📝 Basic console logginglogging.basicConfig(level=logging.INFO)Configure root logger to print to stderr with default format
📁 Log to filelogging.basicConfig(filename='app.log', level=logging.DEBUG)Write log messages to a file
đŸˇī¸ Get a loggerlogger = logging.getLogger(__name__)Retrieve or create a logger for the current module
đŸ–¨ī¸ Log messageslogger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critical')
Log messages at different severity levels
âš ī¸ Exception logginglogging.exception('Exception occurred')Log an error with traceback information
🎨 Custom formatlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')Set a custom log record format
đŸ”ĸ Get level namelogging.getLevelName(logging.DEBUG)Returns 'DEBUG'
đŸšĢ Disable logginglogging.disable(logging.CRITICAL)Suppress all messages at or below the specified level
➕ Add a handlerlogger.addHandler(logging.FileHandler('debug.log'))Attach a file handler to a logger
🔌 LoggerAdapteradapter = logging.LoggerAdapter(logger, {'user': 'john'})Add contextual info to log messages

📚 MODULE REFERENCE

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.

📖 DESCRIPTION

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!

đŸ“Ļ PACKAGE CONTENTS

đŸ›ī¸ CLASSES

builtins.object

Filterer(builtins.object)

🔧 class BufferingFormatter(builtins.object)

BufferingFormatter(linefmt=None)

A formatter suitable for formatting a number of records.

Methods defined here:

Data descriptors defined here:

📄 class FileHandler(StreamHandler)

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:

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__

đŸŽ›ī¸ class Filter(builtins.object)

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:

Data descriptors defined here:

📝 class Formatter(builtins.object)

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:

Methods defined here:

Static methods defined here:

Data descriptors defined here:

Data and other attributes:

âš™ī¸ class Handler(Filterer)

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:

Data descriptors defined here: name

Methods inherited from Filterer: addFilter, filter, removeFilter

Data descriptors inherited from Filterer: __dict__, __weakref__

📋 class LogRecord(builtins.object)

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:

Data descriptors defined here:

đŸ“ĸ class Logger(Filterer)

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:

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__

🔌 class LoggerAdapter(builtins.object)

LoggerAdapter(logger, extra=None)

An adapter for loggers which makes it easier to specify contextual information in logging output.

Methods defined here:

Readonly properties: name

Data descriptors: __dict__, __weakref__, manager

đŸšĢ class NullHandler(Handler)

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:

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__

🌊 class StreamHandler(Handler)

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:

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__

âš™ī¸ FUNCTIONS

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:

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.

📊 DATA

â„šī¸ VERSION

0.5.1.2

📅 DATE

07 February 2010

👤 AUTHOR

Vinay Sajip <vinay_sajip AT red-dove.com>

📁 FILE

/usr/lib/python3.10/logging/__init__.py

logging
📛 NAME 🚀 Quick Reference 📚 MODULE REFERENCE 📖 DESCRIPTION đŸ“Ļ PACKAGE CONTENTS đŸ›ī¸ CLASSES
🔧 class BufferingFormatter(builtins.object) 📄 class FileHandler(StreamHandler) đŸŽ›ī¸ class Filter(builtins.object) 📝 class Formatter(builtins.object) âš™ī¸ class Handler(Filterer) 📋 class LogRecord(builtins.object) đŸ“ĸ class Logger(Filterer) 🔌 class LoggerAdapter(builtins.object) đŸšĢ class NullHandler(Handler) 🌊 class StreamHandler(Handler)
âš™ī¸ FUNCTIONS 📊 DATA â„šī¸ VERSION 📅 DATE 👤 AUTHOR 📁 FILE

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)
Valid XHTML 1.0 Transitional!Valid CSS!
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format

^_top_^