我习惯于使用Java日志库(例如,log4j),它不需要任何编程设置,一个人把一个众所周知的文件名(例如,log4j.xml)放在一个预期的路径(例如,程序的初始目录)中,它会被自动挑选并用于设置诸如日志文件和格式之类的东西。
我知道在Python中实现同样的功能并不困难,但我不喜欢重复发明轮子,这样的功能在标准日志记录模块或其他地方已经可用了吗?
发布于 2020-11-19 22:55:41
我建议你看看Python Logging Cookbook和Logging HOWTO。
下面的代码示例来自HOWTO页面中的Logging to a file部分,可以用作起点。
import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')有关格式化的更详细控制,请查看“日志记录”模块中的Formatters。最后,如果您有兴趣拥有与log4j尽可能相似的日志,this module可能会让您感兴趣。
https://stackoverflow.com/questions/64913923
复制相似问题