Python Glossary Русский

all Python 3loggingfunction

logging.setLoggerClass()

loggers

Sets the class getLogger() will instantiate. This is how you plug in your own Logger subclass with extra methods.

Syntax

logging.setLoggerClass(klass)

It only affects loggers created after the call: getLogger() for an existing name returns the old object of the old class. So call it at the very start, before importing modules that create loggers. The class must subclass Logger or a TypeError is raised, and loggers are still obtained through getLogger(), not the constructor.

Examples

import logging, sys
class AppLogger(logging.getLoggerClass()):
    def notice(self, msg):
        self.log(25, msg)
early = logging.getLogger('early')
logging.setLoggerClass(AppLogger)
log = logging.getLogger('app')
logging.basicConfig(stream=sys.stdout, format='%(message)s')
log.notice('работает')  # → работает
print(type(early).__name__, type(log).__name__)  # → Logger AppLogger
import logging
try:
    logging.setLoggerClass(dict)
except TypeError as e:
    print(e)  # → logger not derived from logging.Logger: dict

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy