python 日志

日志级别严重性

  • DEBUG:细节信息,仅当诊断问题的时候适用
  • INFO:确认程序按预期运行
  • WARNING:表明有已经或即将发生的意外。程序仍按预期进行。
  • ERROR:由于严重的问题,程序的某些功能已经不能正常执行
  • CRITICAL:严重的错误,表明程序已不能继续进行
import logging
logging.warning('watch out')
logging.info('it is ok')
WARNING:root:watch out   # 默认的级别是warning 只会追踪该级别及以上的事件,除非更改日志配置

日志配置

记录日志到文件中

logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)

记录变量数据

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

更改消息显示的格式

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')
DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too

在消息中显示日期和时间

logging.basicConfig(format='%(asctime)s %(message)s') logging.warning('is when this event was logged.')
2024-04-17 23:01:48,365 is when this event was logged.
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')

datefmt 参数的格式与 time.strftime() 支持的格式相同

04/17/2024 11:03:12 PM is when this event was logged.
posted @ 2025-02-02 22:35  且任荣枯  阅读(3)  评论(0编辑  收藏  举报