我在python脚本的全局部分中定义了python logger,如下所示:
import logging
import logging.handlers
FORMAT = '%(asctime)-15s %(threadName)s %(levelname)s %(message)s'
logfile = app.config['CONTROLROOM_WORKER_LOG_PATH']
loghandler = logging.handlers.TimedRotatingFileHandler(logfile, when='midnight', interval=1, backupCount=10, encoding=None, delay=False, utc=False)
fmt = logging.Formatter(FORMAT)
loghandler.setFormatter(fmt)
logger = logging.getLogger('controlroom_worker')
logger.setLevel(logging.INFO)
logger.addHandler(loghandler)
但我遇到的问题如下:
有时,即使执行了逻辑,也会忽略某些逻辑的事先某些逻辑的记录器语句(即未记录)。当需要打印很多东西时,这种行为会被放大。
90%的时间,所有打印的内容都会打印两次!虽然我已经看过一些情况,其中的东西被打印3次。记录示例:
2017-12-08 17:51:10,823 config_notifier INFO Done notifying changes.
2017-12-08 17:51:10,823 config_notifier INFO Done notifying changes.
2017-12-08 17:51:15,829 config_notifier INFO Notifying changes.
2017-12-08 17:51:15,829 config_notifier INFO Notifying changes.
2017-12-08 17:51:15,829 config_notifier INFO Notifying changes.
2017-12-08 17:51:15,943 config_notifier INFO Committed !!!
2017-12-08 17:51:15,943 config_notifier INFO Committed !!!
2017-12-08 17:51:15,943 config_notifier INFO Committed !!!
2017-12-08 17:51:15,943 config_notifier INFO Done notifying changes.
2017-12-08 17:51:15,943 config_notifier INFO Done notifying changes.
2017-12-08 17:51:20,949 config_notifier INFO Notifying changes.
2017-12-08 17:51:20,949 config_notifier INFO Notifying changes.
2017-12-08 17:51:21,052 config_notifier INFO Committed !!!
2017-12-08 17:51:21,052 config_notifier INFO Committed !!!
2017-12-08 17:51:21,052 config_notifier INFO Done notifying changes.
2017-12-08 17:51:21,052 config_notifier INFO Done notifying changes.
2017-12-08 17:51:21,052 config_notifier INFO Done notifying changes.
2017-12-08 17:51:26,057 config_notifier INFO Notifying changes.
2017-12-08 17:51:26,057 config_notifier INFO Notifying changes.
查看两次或三次打印的内容是什么?
这里有一些有趣的事情:
除了使用logging
包之外,我还尝试通过简单地写入文件并在需要日志时写入文件来进行日志记录:
manual_logger=open("manual_log.txt", "a+")
manual_logger.write("Some message here" + "\n")
这个手动记录器总是只记录一次的每个日志语句(正如预期的那样),但是也会因某些日志被完全错过而受到影响:
Done notifying changes.
Notifying changes.
Committed !!!
Done notifying changes.
Notifying changes.
Committed !!!
Done notifying changes.
Notifying changes.
Committed !!!
Done notifying changes.
Notifying changes.
Committed !!!
如何解决这些问题?他们让我发疯了。
答案 0 :(得分:0)
尝试确保日志配置代码仅从主脚本中的if __name__ == '__main__':
子句调用,而不是其他任何地方。特别是,只有在导入模块时才应该调用它,只有当它作为主脚本运行时才会被调用。