python logging模块

摘录自python logging模块官方教程

记录日志到文件

对于简单的日志使用来说日志功能提供了一系列便利的函数。它们是 debug()info()warning()error() 和 critical()

将日志事件记录到文件中:

import logging

logging.basicConfig(filename='example.log',level=logging.DEBUG)

logging.debug('This message should go to the log file')

logging.info('So should this')

logging.warning('And this, too')

对 basicConfig() 的调用应该在 debug() , info() 等的前面。因为它被设计为一次性的配置,只有第一次调用会进行操作,随后的调用不会产生有效操作。如果你希望每次运行重新开始,而不是记住先前运行的消息,则可以通过将上例中的调用更改为来指定 filemode 参数:

logging.basicConfig(filename='example.log',filemode='w',level=logging.DEBUG)

记录变量数据

要记录变量数据,请使用格式字符串作为事件描述消息,并将变量数据作为参数附加。 例如:

import logging

logging.warning('%s before you %s','Look','leap!')

更改显示消息的格式

import logging

logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.DEBUG)

logging.debug('This message should appear on the console')

logging.info('So should this')

logging.warning('And this, too')


在消息中显示日期/时间

要显示事件的日期和时间,你可以在格式字符串中放置 '%(asctime)s'

importlogging

logging.basicConfig(format='%(asctime)s %(message)s')

logging.warning('is when this event was logged.')

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容