提问者:小点点

Python模块级日志记录配置


我读过python文档https://docs.python.org/3/howto/logging.html#advanced-日志记录教程:配置模块级日志记录的最佳方法是命名日志记录程序:

logger = logging.getLogger(__name__)  

我的主要应用程序日志工作正常:

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

但是在另一个模块中,当我在模块范围中设置记录器时:

logger = logging.getLogger(__name__)  

记录器不记录任何内容。当我在一个方法中创建记录器时,日志工作正常:

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))  

然后我需要使用self.logger..格式化来在类中的所有方法中获得一个记录器——这是我以前从未见过的。我试图将logging.conf设置为记录呼叫来自哪里:

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

但是,当在模块作用域中设置记录器时,即使使用此配置,日志记录仍然无法工作。

我也尝试过:

logger = logging.getLogger('root')

在模块开始时,同样没有记录器。但是,如果我使用:

logger = logging.getLogger('fileLogger')

在一个模块的开始,日志工作正常,上面的配置文件我可以看到调用来自哪个模块。

为什么使用name配置记录器并没有从root继承其配置?当在日志中同时配置root和fileHandler时,为什么使用root配置不起作用而使用fileHandler却起作用。配置文件?


共1个答案

匿名用户

为了避免意外,在fileConfig()调用中使用disable_existing_loggers=False,如本节文档中所述。

您不应该使用self。记录器实例变量-模块级记录器应正常。