【发布时间】:2015-01-13 04:29:11
【问题描述】:
我从 python 文档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')
在模块开始时,日志记录工作正常,通过上面的配置文件,我可以看到调用来自哪个模块。
为什么使用 name 配置记录器不从根目录继承它的配置? 为什么在 logging.conf 文件中同时配置了 root 和 fileHandler 时,使用 root 配置时不起作用?
【问题讨论】:
-
旁注:为了获得“根”记录器,只需
logger = logging.getLogger()。