使用 FileHandler 的 Pythonlogging.get_Logger(name) 不会写入文件
如果我获取带有名称的记录器并添加 FileHandler,它不会写入文件。
这可以正常工作并正确写入文件:
log = logging.getLogger()
fh = logging.FileHandler(logfile)
log.addHandler(fh)
fh_fmt = logging.Formatter("%(asctime)s (%(levelname)s)\t: %(message)s")
fh.setFormatter(fh_fmt)
log.setLevel(logging.INFO)
这不会写入文件:
log = logging.getLogger(name)
fh = logging.FileHandler(logfile)
log.addHandler(fh)
fh_fmt = logging.Formatter("%(asctime)s (%(levelname)s)\t: %(message)s")
fh.setFormatter(fh_fmt)
log.setLevel(logging.INFO)
唯一的区别是我得到了一个“命名”记录器。
If I get the logger with a name and add a FileHandler it does not write to the file.
This works and writes correctly to the file:
log = logging.getLogger()
fh = logging.FileHandler(logfile)
log.addHandler(fh)
fh_fmt = logging.Formatter("%(asctime)s (%(levelname)s)\t: %(message)s")
fh.setFormatter(fh_fmt)
log.setLevel(logging.INFO)
This does not write to the file:
log = logging.getLogger(name)
fh = logging.FileHandler(logfile)
log.addHandler(fh)
fh_fmt = logging.Formatter("%(asctime)s (%(levelname)s)\t: %(message)s")
fh.setFormatter(fh_fmt)
log.setLevel(logging.INFO)
The only difference is that I get a 'named' logger.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个相当老的问题,但我相信我找到了潜在的问题和解决方案,至少使用较新版本的 Python 是这样。
第二个代码示例以
log =logging.getLogger(name)
开头,其中name
被假定为表示记录器名称的字符串。由于提供了名称,因此该日志
将不是是根记录器。根据 Logger.setLevel(level) 文档< /a> 对于 Python 3.6+,这告诉我们必须设置记录器的级别,以便它实际处理消息而不是将其传递给根记录器。
这是我编写的代码示例(在 Python 3.7 中)不起作用:
并且这个代码示例通过添加一行来工作:
注意:第一个代码示例确实创建了所选的日志文件,但不写入
'Start Configuration Log '
到文件中。This is a rather old question, but I believe I found the underlying problem and solution, at least with a newer version of Python.
The second code example starts with
log = logging.getLogger(name)
, wherename
is presumed to be a string representing the name of the logger. Since a name is provided, thislog
will not be the root logger. According to Logger.setLevel(level) docs for Python 3.6+,This tells us that we have to set the level of our logger so that it will actually process the messages instead of passing it to the root logger.
This is a code example I wrote (in Python 3.7) that does not work:
And this one works by adding one line:
Note: The first code example does create the chosen log file, but does not write
'Start Configuration Log'
to the file.