Python模块级日志记录配置

时间:2014-11-16 01:17:46

标签: python logging

我从python docs https://docs.python.org/3/howto/logging.html#advanced-logging-tutorial读到,配置模块级日志记录的最佳方法是命名记录器:

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

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

为什么使用名称配置记录器不从root继承它的配置? 当在logging.conf文件中配置root和fileHandler时,为什么在使用fileHandler时使用root进行配置不起作用?

1 个答案:

答案 0 :(得分:2)

为避免出现意外,请在disable_existing_loggers=False来电中使用fileConfig(),如文档this section中所述。

您永远不需要使用self.logger实例变量 - 模块级记录器应该没问题。