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
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.
getLogger
callI've simplified the example to demonstrate the key concept. Should work across files and with a config file.