简体   繁体   English

Python模块级日志记录配置

[英]Python module level logging configuration

I have read from python docs https://docs.python.org/3/howto/logging.html#advanced-logging-tutorial that the best way to configure module level logging is to name the logger: 我从python docs https://docs.python.org/3/howto/logging.html#advanced-logging-tutorial中了解到,配置模块级日志记录的最佳方法是命名记录器:

logger = logging.getLogger(__name__)  

I the main application logging works fine: 我的主应用程序日志记录工作正常:

if __name__ == '__main__':  
    logging.config.fileConfig('logging.conf')  
    # create logger  
    logger = logging.getLogger(__name__)  

However in another module when I set the logger in the module scope: 但是在另一个模块中,当我在模块范围内设置记录器时:

logger = logging.getLogger(__name__)  

the logger does not log anything. 记录器不记录任何内容。 When I create the logger within a method logging works fine: 当我在方法内创建记录器时,记录工作正常:

class TestDialog(QDialog, Ui_TestDialog):  
def __init__(self, fileName, parent=None):  
    super(TestDialog, self).__init__(parent)  
    self.logger = logging.getLogger(__name__)  
    logger.debug("--_init_() "+str(fileName))  

Then I would need to use the self.logger.. formatting to get a logger in all methods in the class - which I have never seen before. 然后,我将需要使用self.logger ..格式来获取类中所有方法的记录器-这是我以前从未见过的。 I tried to set the logging.conf to log where the call is comming from: 我试图将logging.conf设置为记录来自哪里的调用:

[loggers]
keys=root,fileLogger
...
[formatter_consoleFormatter]
format=%(asctime)s - %(module)s - %(lineno)d - %(name)s - %(levelname)s - %(message)s
datefmt=

However when the logger is set in the module scope logging still doesn't work even with this configuration. 但是,即使在模块作用域中设置了记录器,即使使用此配置,记录仍然无法进行。

I also tried: 我也尝试过:

logger = logging.getLogger('root')

at the start of a module, again no logger. 在模块开始时,再次没有记录器。 However If I use: 但是,如果我使用:

logger = logging.getLogger('fileLogger')

at the start of a module, logging works fine and with config file above I can see which module the call is comming from. 在模块开始时,日志记录工作正常,并且使用上面的配置文件,我可以看到调用来自哪个模块。

Why is configuring logger using name not inheriting it's config from root? 为什么使用名称配置记录器不从根继承它的配置? Why does configuring using root not work while using fileHandler does, when both root and fileHandler are configured in the logging.conf file? 当在logging.conf文件中同时配置了root和fileHandler时,为什么使用root进行配置时无法使用root进行配置?

To avoid surprises, use disable_existing_loggers=False in your fileConfig() call, as documented in this section of the docs. 为避免意外,请按照本节文档中所述在fileConfig()调用中使用disable_existing_loggers=False

You should never need to use a self.logger instance variable - module level loggers should be fine. 您永远不需要使用self.logger实例变量-模块级记录器应该可以。

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

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