官方手册:
https://docs.python.org/3/library/logging.html
一、基础教程
1、说明
要执行的任务 | 完成任务的最佳工具 |
显示控制台输出,用于命令行脚本或程序的常规使用 | print() |
报告程序正常运行期间发生的事件(例如,用于状态监视或故障调查) | logging.info() logging.debug() |
发出有关特定运行时事件的错误 | warnings.warn()在库代码中,如果可以避免出现此问题,则应修改客户端应用程序以消除警告 logging.warning()如果客户端应用程序无法处理这种情况,但仍应注意该事件 |
报告有关特定运行时事件的错误 | 引发异常 |
报告抑制错误而不会引发异常(例如长时间运行的服务器进程中的错误处理程序) | logging.error() logging.exception() logging.critical() |
事件级别和严重性(严重程度从高到低)
事件级别 | 情况说明 |
DEBUG | 详细信息,通常仅在诊断问题时才需要 |
INFO | 确认一切正常 |
WARNING | 表示发生了意外情况,或者表示在不久的将来出现了某些问题(例如“磁盘空间不足”)。该软件仍按预期运行。 |
ERROR | 由于存在更严重的问题,该软件无法执行某些功能。 |
CRITICAL | 严重错误,表明程序本身可能无法继续运行。 |
默认级别为WARNING,即仅跟踪比此级别更高级别的事件,除非将日志记录程序包配置为执行其他操作。
2、用例
(1)级别说明
import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
'''
WARNING:root:Watch out!
'''
info不会出现,因为默认级别为WARNING,INFO低于WARNING
(2)记录到文件 logging.basicConfig()
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')
logging.error('And non-ASCII stuff, too')
运行结果:
(3)显示日期消息
import logging
logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('is when this event was logged.')
'''
2020-10-08 11:12:24,274 is when this event was logged.
'''
对日期格式进行设置:
import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
'''
10/08/2020 11:13:14 AM is when this event was logged.
'''
目前基础教程已经够用了,高级教程在官方文档中有,不再搬运。日后需要再继续。