learnereveryday
learnereveryday

Reputation: 191

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?

Upvotes: 2

Views: 1647

Answers (1)

blues
blues

Reputation: 5195

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'

Upvotes: 8

Related Questions