Python日志记录不会关闭

编程入门 行业动态 更新时间:2024-10-25 17:20:54
本文介绍了Python日志记录不会关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在学习python日志记录模块,但是在完成日志记录后一直无法关闭.这是一个示例-

I have been learning the python logging module but have been having problems getting the logging to shutdown after it's done. Here is an example -

import logging log = logging.getLogger() log.setLevel(logging.INFO) handler = logging.FileHandler('test.log') handler.setLevel(logging.INFO) formatter = logging.Formatter( fmt='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) handler.setFormatter(formatter) log.addHandler(handler) log.info('log file is open') logging.shutdown() log.info('log file should be closed')

但是在logging.shutdown()之后,模块仍在进行日志记录,因为日志文件如下所示-

But the module is stilling logging after the logging.shutdown() as the log file looks like this -

# cat test.log 2014-07-17 19:39:35 INFO: log file is open 2014-07-17 19:39:35 INFO: log file should be closed

根据文档,此命令应通过刷新和关闭所有处理程序来执行有序关闭".我应该做些其他事情来关闭日志文件吗?

According to the documentation this command should "perform an orderly shutdown by flushing and closing all handlers". Should I be doing something else to close the log file ?

推荐答案

因此,我发现使用shutdown()不能完全删除用于日志记录的文件处理程序.最好的方法似乎是手动删除文件处理程序-

So I found that the file handler for logging is not completely going away by using shutdown(). The best way seems to be to manually remove the file handler -

def main(): log = logging.getLogger() log.setLevel(logging.INFO) fh = logging.FileHandler(filename='test.log') fh.setLevel(logging.INFO) formatter = logging.Formatter( fmt='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) fh.setFormatter(formatter) log.addHandler(fh) log.info('-------Start--------') log.info('this function is doing something') log.info('this function is finished') log.removeHandler(fh) <--------------------------Add this line del log,fh

更多推荐

Python日志记录不会关闭

本文发布于:2023-11-25 04:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628279.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日志   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!