RNikoopour RNikoopour - 2 months ago 5
Python Question

Have Parent Class Use Child Class Logger Name

I'm trying to set up some logging and I'm running into a problem. Whenever a child class uses a parent class function, the parent class function logger name is used instead of the child class's logger name.

Let's say I have the following two classes:

Parent Class:

import logging
logger = logging.getLogger('ParentClass')

class ParentClass:
def __init___(self):
logger.info('This is inside ParentClass')


Child Class:

import logging
logger = logging.getLogger('ChildClass')

class ChildClass(ParentClass):
def foo(self):
logger.info('This is inside ChildClass')


Then I run the following script:

import logging
import ParentClass
import ChildClass

# Pretend I set up logging to "example.log"
foo1 = ParentClass.ParentClass()
foo2 = ChildClass.ChildClass()
foo2.foo()


My Log file ends up looking like:

INFO:ParentClass:This is inside ParentClass #(<-- this comes from foo1 init)
INFO:ParentClass:This is inside ParentClass #(<-- this comes from foo2 init)
INFO:ChildClass:This is inside ChildClass #(<-- this comes from foo2 foo)


What I'm looking for is the __init__ call for ChildClass to log under the ChildClass logger like this:

INFO:ParentClass:This is inside ParentClass #(<-- this comes from foo1 init)
INFO:ChildClass:This is inside ParentClass #(<-- this comes from foo2 init)
INFO:ChildClass:This is inside ChildClass #(<-- this comes from foo2 foo)


Is there anyway to do this without passing the name of the logger I want to use to the ParentClass?

Answer

Each of your classes is using its own logger for its own code because you're accessing the logger via a global variable in each of your two modules. If you want the logger tied to the classes instead of the modules, try making it a class variable, and accessing it via self:

class ParentClass:
    logger = logging.getLogger('ParentClass') # class variable
    def __init___(self):
        self.logger.info('This is inside ParentClass')

class ChildClass(ParentClass):
    logger = logging.getLogger('ChildClass') # override parent class variable
    def foo(self):
        self.logger.info('This is inside ChildClass')