简体   繁体   中英

Pattern to subclass logging.Logger

Is there a common pattern to follow to correctly subclass logging.Logger ?

import logging

class MyLogger(logging.Logger):
    __init__(self, name):
        super().__init__(name=name)

Does not seem to work property, as MyLogger created this way has no reference to its parent. Although I could manually set its parent, but am afraid that maybe there are other protocols of loggging.Logger not satisfied as well by MyLogger ?

How are you creating your logger instance? The canonical way to do it is to never directly instantiate a Logger and instead use the Manager. The logging lib has setLoggerClass to tell the manager which class to use when creating Loggers. The manager also sets up parents:

import logging

class MyLogger(logging.Logger):
    def __init__(self, name):
        super().__init__(name=name)

logging.setLoggerClass(MyLogger)

logger = logging.getLogger('some_logger')
child_logger = logging.getLogger('some_logger.child')

print(type(logger)) # MyLogger
print(logger.parent) # shows the root logger
print(child_logger.parent) # shows 'some_logger'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM