Python Logging模块-介绍与使用
2016-04-25 17:21
676 查看
概述
Logging模块是python自带的日志模块,提供了强大的API和配置系统,用于在项目中打印各级别的日志。日志级别
Logging模块提供了5种日志的级别,如下表所示:级别 | 说明 |
---|---|
DEBUG | 详细的信息,在进行诊断问题时使用 |
INFO | 正常运行的信息 |
WARNING | 警示发生了一些意外的情况,或者警示将会出现问题,比如磁盘空间不足。程序仍正常运行。 |
ERROR | 程序的某些功能已经不能正常使用 |
CRITICAL | 表示严重错误,程序已经不能继续跑了 |
默认的级别是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
里面各个参数分别是时间,文件名,行号,日志级别,这样日志就完善了许多。
相关文章推荐
- python环境变量自动配置脚本(setx使用)
- Python正则表达式指南
- python编码规范
- Python常用标准库操作
- python md5
- python的setdefault方法
- python读取excel文件生成sql文件
- python modules下载地址
- Python学习(二)基础语法
- python_笔记6_函数
- python读取鸢尾花数据集并进行训练测试集分割
- python ConfigParser模块详解
- 为什么在Python里推荐使用多进程而不是多线程?
- python_笔记5_set
- Python爬虫-用迅雷下载电影
- Windows上部署Python
- Windows上部署Python
- Python基础:函数
- python 字典为什么是无序的?
- python中常见的报错问题