概述
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
里面各个参数分别是时间,文件名,行号,日志级别,这样日志就完善了许多。