Passing logger between multiple classes in the same file

Viewed 72

I have the following Code:

class logger():
  def __init__():
    self.logger = logging.getLogger(__name__)
    self.logger.setLevel(logging.INFO)
    if not (self.logger.hasHandlers()):
        #self.logger.handlers.clear()
        file_handler=logging.FileHandler("qwerty.log")
        stream_handler=logging.StreamHandler()
        format_str = {"timestamp":"%(asctime)s"} #Some more stuff
        format_str = json.dumps(format_str)
        stream_formatter=logging.Formatter(format_str)
        file_formatter=logging.Formatter(format_str)
        file_handler.setFormatter(file_formatter)
        stream_handler.setFormatter(stream_formatter)
        self.logger.addHandler(file_handler)
        self.logger.addHandler(stream_handler) 

class ABC():
    def __init__():
        logger.__init__(self)
    def some_func():
        self.logger.info("Hi from ABC")
class XYZ(ABC):
    def __init__():
        ABC.__init__(self)
        logger.__init__(self) #why do I need to do this?
    def some_func():
        self.logger.info("Hi from XYZ")

class zxc():
    def __init__():
        logger.__init__(self)
        abc = ABC()
    def some_func():
        try:
           self.logger.info("Hi from ZXC")
           raise Exception
        except:
           self.logger.error("Some issue")

I have a logger class that I am currently initializing in the 3 different classes.

My first question is, in class XYZ why do I need to initialize logger again? The base class ABC has created an object of logger in it's init method, does this object not get inherited?

Also, is this the right way to pass/initialize the logger in different classes? Is there a better way to do this? A lot of articles show how to pass it between modules but my use-case is a little different.

Also another issue is that logger.error does not log any messages in the log file. I am not sure as to why because I don't see any errors either. These error logs are being displayed on the output console but not being written.

1 Answers

You should instantiate your logger object once on a global scope. That way you can set it up once and use it across your project with no issues.

Here is an example, with simplified code and other fixes:

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
if not logger.hasHandlers():
    # More setup code...
    pass


class ABC():
    def some_func(self):
        logger.info("Hi from ABC")


class XYZ(ABC):
    def some_func(self):
        logger.info("Hi from XYZ")


class ZXC():
    def some_func(self):
        try:
           logger.info("Hi from ZXC")
           raise Exception
        except:
           logger.error("Some issue")
Related