登录Python脚本无效:导致日志文件为空 [英] Logging in a Python script is not working: results in empty log files
问题描述
我有一个具有日志记录功能的脚本,并且它停止工作(日志记录,而不是脚本).我写了一个小例子来说明问题:
I had a script with logging capabilities, and it stopped working (the logging, not the script). I wrote a small example to illustrate the problem:
import logging
from os import remove
from os.path import exists
def setup_logger(logger_name, log_file, level=logging.WARNING):
# Erase log if already exists
if exists(log_file):
remove(log_file)
# Configure log file
l = logging.getLogger(logger_name)
formatter = logging.Formatter('%(message)s')
fileHandler = logging.FileHandler(log_file, mode='w')
fileHandler.setFormatter(formatter)
streamHandler = logging.StreamHandler()
streamHandler.setFormatter(formatter)
l.setLevel(level)
l.addHandler(fileHandler)
l.addHandler(streamHandler)
if __name__ == '__main__':
setup_logger('log_pl', '/home/myuser/test.log')
log_pl = logging.getLogger('log_pl')
log_pl.info('TEST')
log_pl.debug('TEST')
在脚本末尾,已创建文件test.log,但该文件为空.
At the end of the script, the file test.log is created, but it is empty.
我想念什么?
推荐答案
您的 setup_logger
函数将(默认)级别指定为 WARNING
Your setup_logger
function specifies a (default) level of WARNING
def setup_logger(logger_name, log_file, level=logging.WARNING):
...然后您以后记录两个事件,这些事件的级别比 WARNING
低,并且应该被忽略:
...and you later log two events that are at a lower level than WARNING
, and are ignored as they should be:
log_pl.info('TEST')
log_pl.debug('TEST')
如果将调用 setup_logger
函数的代码更改为:
If you change your code that calls your setup_logger
function to:
if __name__ == '__main__':
setup_logger('log_pl', '/home/myuser/test.log', logging.DEBUG)
...我希望它能如您所愿.
...I'd expect that it works as you'd like.
请参阅Logging HOWTO中的简单示例.页.
See the simple example in the Logging HOWTO page.
这篇关于登录Python脚本无效:导致日志文件为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!