How to extend the logging.Logger Class?

前端 未结 2 1092
谎友^
谎友^ 2021-02-15 05:14

I would like to start with a basic logging class that inherits from Python\'s logging.Logger class. However, I am not sure about how I should be constructing my cla

2条回答
  •  一向
    一向 (楼主)
    2021-02-15 05:57

    This line

    self.logger = logging.getLogger("myApp")
    

    always retrieves a reference to the same logger, so you are adding an additional handler to it every time you instantiate MyLogger. The following would fix your current instance, since you call MyLogger with a different argument both times.

    self.logger = logging.getLogger(name)
    

    but note that you will still have the same problem if you pass the same name argument more than once.

    What your class needs to do is keep track of which loggers it has already configured.

    class MyLogger(object):
        loggers = set()
        def __init__(self, name, format="%(asctime)s | %(levelname)s | %(message)s", level=INFO):
            # Initial construct.
            self.format = format
            self.level = level
            self.name = name
    
            # Logger configuration.
            self.console_formatter = logging.Formatter(self.format)
            self.console_logger = logging.StreamHandler(sys.stdout)
            self.console_logger.setFormatter(self.console_formatter)
    
            # Complete logging config.
            self.logger = logging.getLogger(name)
            if name not in self.loggers:
                self.loggers.add(name)
                self.logger.setLevel(self.level)
                self.logger.addHandler(self.console_logger)
    

    This doesn't allow you to re-configure a logger at all, but I leave it as an exercise to figure out how to do that properly.

    The key thing to note, though, is that you can't have two separately configured loggers with the same name.


    Of course, the fact that logging.getLogger always returns a reference to the same object for a given name means that your class is working at odds with the logging module. Just configure your loggers once at program start-up, then get references as necessary with getLogger.

提交回复
热议问题