如何使用日志记录Python模块写入文件? [英] How to write to a file, using the logging Python module?

查看:831
本文介绍了如何使用日志记录Python模块写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中使用日志记录模块来写入文件?每次我尝试使用它时,它只会打印出消息.

How can I use the logging module in Python to write to a file? Every time I try to use it, it just prints out the message.

推荐答案

使用logging.basicConfig而不是logging.fileHandler()

logging.basicConfig(filename=logname,
                            filemode='a',
                            format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                            datefmt='%H:%M:%S',
                            level=logging.DEBUG)

logging.info("Running Urban Planning")

self.logger = logging.getLogger('urbanGUI')

按顺序,五个部分执行以下操作:

  1. 设置输出文件(filename=logname)
  2. 将其设置为追加而不是覆盖(filemode='a')
  3. 确定输出消息(format=...)的格式
  4. 确定输出时间(datefmt='%H:%M:%S')的格式
  5. 并确定它将接受的最低消息级别(level=logging.DEBUG).
  1. set the output file (filename=logname)
  2. set it to append rather than overwrite (filemode='a')
  3. determine the format of the output message (format=...)
  4. determine the format of the output time (datefmt='%H:%M:%S')
  5. and determine the minimum message level it will accept (level=logging.DEBUG).

这篇关于如何使用日志记录Python模块写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆