学习 python logging(1): 基本用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39469761/article/details/85643916

简介

日志在编程中是十分重要,可以帮助我们跟踪事件、应用的运行情况、查问题、统计数据等。在记录日志时,通常表示某件事情的发生。

python 中 logging 模块提供记录的基础方法:

debug, info,warning, error, critical

这五个方法的严重等级依次增加,对应关系:

LEVEL value used time
DEBUG 10 分析问题的时候
INFO 20 确定程序是否在按预想的运行
WARNING 30 程序运行超出预设,但是,程序还可以运行
ERROR 40 有严重的错误,程序无法正常运行一些方法
CRITICAL 50 一个严重的错误,导致程序无法继续运行了

默认等级为 WARNING,只有高于你所指定的等级,才会被日志模块输出。

基本使用

  1. 直接打印
import logging
logging.info('info log')
logging.warning('warning log')

运行之后看到的是 WARNING:root:warning log ,因为默认等级是 WARNING, 所以 info log 是不会显示的。

  1. 将日志记录到文件中
import logging
logging.basicConfig(filename='logging_example.log',level=logging.DEBUG)
logging.debug('Write debug to file')
logging.info('Write info to file')
logging.warning('Write warning to file')

可以在日志文件中看到:

DEBUG:root:Write debug to file
INFO:root:Write info to file
WARNING:root:Write warning to file
DEBUG:root:Write debug to file
INFO:root:Write info to file
WARNING:root:Write warning to file

参考:

  1. https://docs.python.org/3/howto/logging.html#logging-basic-tutorial
  2. https://docs.python.org/3/library/logging.html
  3. https://docs.python.org/3/howto/logging-cookbook.html#logging-cookbook

猜你喜欢

转载自blog.csdn.net/qq_39469761/article/details/85643916