Python Logging with a common logger class mixin and class inheritance

前端 未结 1 1081
北海茫月
北海茫月 2021-02-08 10:13

I would like to create a Python logging class that can be inherited as a common means of logging configuration, yet seperately control the logging level of the base class from t

相关标签:
1条回答
  • 2021-02-08 11:04

    A metaclass would be more appropriate. When a class is defined it will get its own logger. Name mangling ensures each class uses its own logger.

    import logging
    import sys
    
    logging.basicConfig(stream=sys.stdout)
    
    class MetaBase(type):
        def __init__(cls, *args):
            super().__init__(*args)
    
            # Explicit name mangling
            logger_attribute_name = '_' + cls.__name__ + '__logger'
    
            # Logger name derived accounting for inheritance for the bonus marks
            logger_name = '.'.join([c.__name__ for c in cls.mro()[-2::-1]])
    
            setattr(cls, logger_attribute_name, logging.getLogger(logger_name))
    
    class Base(metaclass=MetaBase):
        def __init__(self):
            self.__logger.error('init base')
    
        def func_base(self):
            self.__logger.error('func base')
    
    class Parent(Base):
        def func_parent(self):
            self.__logger.error('func parent')
    
    p = Parent()
    p.func_base()
    p.func_parent()
    

    Results in:

    ERROR:Base:init base
    ERROR:Base:func base
    ERROR:Base.Parent:func parent
    

    This approach has a few additional benifites over mix in.

    • The logger for each class is created at class definition and accessed via a direct attribute reference. Avoids property and getLogger call
    • Subclasses only need to inherit base, no need to remember to add MixIn

    I've simplified the example to demonstrate the key concept. Should work across files and with a config file.

    0 讨论(0)
提交回复
热议问题