Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 500
learnereveryday Avatar asked Mar 25 '26 21:03

learnereveryday


1 Answers

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'
like image 126
blues Avatar answered Mar 27 '26 11:03

blues



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!