Python Logging模块-介绍与使用

概述

Logging模块是python自带的日志模块,提供了强大的API和配置系统,用于在项目中打印各级别的日志。

日志级别

Logging模块提供了5种日志的级别,如下表所示:

级别说明
DEBUG详细的信息,在进行诊断问题时使用
INFO正常运行的信息
WARNING警示发生了一些意外的情况,或者警示将会出现问题,比如磁盘空间不足。程序仍正常运行。
ERROR程序的某些功能已经不能正常使用
CRITICAL表示严重错误,程序已经不能继续跑了

且他们的顺序是:CRITICAL>ERROR>WARNING>INFO>DEBUG
默认的级别是WARNING,意思是只有比WARNING高级别的日志才会打印或者记录下来。

使用

打印到屏幕上
import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

这样的话会输出到屏幕上:

Watch out! 

为什么不会输出I told you so呢?因为当前默认的级别是WARNING,INFO比它低,所以不会输出。

打印到文件
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')

这样将级别设置为DEBUG,则打开example.log可以看到

DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too

使用格式化的输出

logging.basicConfig(level=logging.INFO,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S',
                filename='example.log')
logging.warning('is when this event was logged.')

这会打印出

2016-04-25 16:00:36 test.py[line:39] INFO is when this event was logged

里面各个参数分别是时间,文件名,行号,日志级别,这样日志就完善了许多。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值