简体   繁体   English

Python 在多个模块中自定义记录器,无需传递额外的 arguments

[英]Python custom logger in multiple modules without passing additional arguments

I have this custom Logger class which accepts 2 non-standard arguments test_name and start_time :我有这个自定义记录器 class 接受 2 个非标准 arguments test_namestart_time

class S_Logger(Logger):

    def __init__(self,
             test_name: str,
             start_time: str,
             log_name: str = 'main',
             *args, **kwargs) -> None:
    
    Logger.__init__(self, log_name, *args, **kwargs)
    self.test_name = test_name
    self.setLevel(logging.DEBUG)
    self.addHandler(S_StreamHandler())
    self.addHandler(S_FileHandler(test_name, start_time))

@classmethod
def get_logger(cls) -> logging.Logger:
    # That doesn't work, I have to specify handlers one more time...
    return logging.getLogger('main')

The first time I use that logger is in module exampleA.py, but then I would like to reuse the same logger with those same handlers in another module (exampleB.py) WITHOUT passing those 2 additional arguments.我第一次使用该记录器是在模块 exampleA.py 中,但后来我想在另一个模块(exampleB.py)中使用相同的处理程序重用相同的记录器,而不传递这两个额外的 arguments。 Is this possible?这可能吗?

module exampleA.py:模块示例A.py:

from source import S_Logger

class exampleA(object):

    def run(self):
        log = S_Logger(self.test_name, self.start_time)
        log.info('module A')

module exampleB.py:模块示例B.py:

from source import S_Logger

logger = S_Logger.get_logger()

class exampleB(object):

    def something(self):
        logger.info('module B')

Example output that I would like to achieve:我想实现的示例 output :

2022-09-21 15:00:00 INFO  line:10 of exampleA.py   >> Module A
2022-09-21 15:00:00 INFO  line:15 of exampleB.py   >> Module B

Try to add default value as you do with non-standard argument log_name .尝试像使用非标准参数log_name一样添加默认值。

class S_Logger(Logger):

    def __init__(self,
             test_name: str = 'default name',
             start_time: str = 'default time',
             log_name: str = 'main',
             *args, **kwargs) -> None:
    
    Logger.__init__(self, log_name, *args, **kwargs)
    self.test_name = test_name
    self.setLevel(logging.DEBUG)
    self.addHandler(S_StreamHandler())
    self.addHandler(S_FileHandler(test_name, start_time))

@classmethod
def get_logger(cls) -> logging.Logger:
    # That doesn't work, I have to specify handlers one more time...
    return logging.getLogger('main')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM