python logging模块学习(转)
前言
日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法。本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表。
另外,Python的HOWTOs文档很详细,连日志该怎么用都写了,所以有英文阅读能力的同学建议去阅读一下。
Logging模块构成
组成
主要分为四个部分:
- Loggers:提供应用程序直接使用的接口
- Handlers:将Loggers产生的日志传到指定位置
- Filters:对输出日志进行过滤
- Formatters:控制输出格式
日志级别
| Level | Numeric value | When it’s used |
|---|---|---|
| DEBUG | 10 | Detailed information, typically of interest only when diagnosing problems. |
| INFO | 20 | Confirmation that things are working as expected. |
| WARNING | 30 | An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
| ERROR | 40 | Due to a more serious problem, the software has not been able to perform some function. |
| CRITICAL | 50 | A serious error, indicating that the program itself may be unable to continue running. |
| NOSET | 0 | getattr(logging, loglevel.upper()) |
默认级别是WARNING,可以使用打印到屏幕上的方式记录,也可以记录到文件中。
模块使用示例
简单例子
打印输出
In [5]: import logging
In [6]: logging.warning("FBI warning")
WARNING:root:FBI warning
In [7]: logging.info("information")
# 没有打印是因为默认级别是warning
输出到文件中
In [4]: import logging
In [5]: logging.basicConfig(filename='example.log', level=logging.DEBUG)
In [6]: logging.debug("debug")
In [7]: logging.warning('warning')
In [8]: logging.info('info')
In [9]: ls
C++ STL/ a.py example.log parser/ test.sh*
In [10]: cat example.log
DEBUG:root:debug
WARNING:root:warning
INFO:root:info
In [14]: logging.warning('new warning')
# 注意这种是直接往后面添加,也就是add的,若是想覆盖内容可以更改文件写入方式
In [15]: cat example.log
DEBUG:root:debug
WARNING:root:warning
INFO:root:info
WARNING:root:new warning
# 覆盖的方式写入例子
(test) ➜ test ipython
WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
Python 2.7.11 (default, Jun 17 2016, 20:01:51)
Type "copyright", "credits" or "license" for more information.
IPython 4.2.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import logging
In [2]: logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
In [3]: logging.warning('FBI warning')
In [4]: ls
C++ STL/ a.py example.log parser/ test.sh*
In [5]: cat example.log
WARNING:root:FBI warning
In [6]: quit
(test) ➜ test ipython
WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
Python 2.7.11 (default, Jun 17 2016, 20:01:51)
Type "copyright", "credits" or "license" for more information.
IPython 4.2.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import logging
In [2]: logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
In [3]: logging.warning('warning')
In [4]: cat example.log
WARNING:root:warning
变量的使用
和print语句中使用变量一样,如:
In [5]: logging.warning('%s before you %s', 'Look', 'leap!')
In [6]: cat example.log
WARNING:root:warning
WARNING:root:Look before you leap!
输出格式
可以在basicConfig中设置,参数名称可以参见链接,可以设置时间什么的,如:
In [2]: import logging
In [3]: logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG)
In [4]: logging.warning('And this, too')
2016-12-06 15:40:43,577:WARNING:And this, too
进阶使用
当想项目中使用logging模块的时候肯定不能在这样一句句的写了,一般可能会抽象出一个模块来,这样比较有效一些。logging模块提供了四个类(Loggers,Formatters,Filtters,Handlers)来实现不同的功能,与此对应的我们如果想封装一个函数,也就要针对这几个功能来自定义一下。
想自定义的话思路也很简单,首先实例化一个相应的对象,然后进行一些设置,可以简单看一下下面的例子:
import logging
# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
# 输出是:
$ python simple_logging_module.py
2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
2005-03-19 15:10:26,620 - simple_example - INFO - info message
2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
2005-03-19 15:10:26,697 - simple_example - ERROR - error message
2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
从配置文件导入配置
模块内容:
import logging
import logging.config
logging.config.fileConfig('logging.conf')
# create logger
logger = logging.getLogger('simpleExample')
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
# 输出
$ python simple_logging_config.py
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
配置文件内容:
[loggers]
keys=root,simpleExample
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
同时也可以使用YAML格式的配置文件,如:
version: 1
formatters:
simple:
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
loggers:
simpleExample:
level: DEBUG
handlers: [console]
propagate: no
root:
level: DEBUG
handlers: [console]
PS
Logging模块使用也会有很多坑,常见的是日志重复打印的问题,大家可以搜一下,这里提供一些链接供参考:
- http://www.jianshu.com/p/25f70905ae9d
- https://yinzo.github.io/14610807170718.html
- http://python.jobbole.com/86887/
参考
- https://docs.python.org/2/library/logging.html
- https://docs.python.org/2/howto/logging.html#logging-basic-tutorial
转自http://www.cnblogs.com/wswang/p/6138304.html
python logging模块学习(转)的更多相关文章
- Python logging 模块学习
logging example Level When it's used Numeric value DEBUG Detailed information, typically of interest ...
- python logging模块使用流程
#!/usr/local/bin/python # -*- coding:utf-8 -*- import logging logging.debug('debug message') logging ...
- (转)python logging模块
python logging模块 原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python ...
- python logging模块使用教程
简单使用 #!/usr/local/bin/python # -*- coding:utf-8 -*- import logging logging.debug('debug message') lo ...
- python logging模块【转载】
转自:https://www.cnblogs.com/dahu-daqing/p/7040764.html 参考:老顽童log模块,讲的很细致,基本上拿到手就可以直接用了,很赞 1 logging模块 ...
- python logging模块可能会令人困惑的地方
python logging模块主要是python提供的通用日志系统,使用的方法其实挺简单的,这块就不多介绍.下面主要会讲到在使用python logging模块的时候,涉及到多个python文件的调 ...
- python logging模块使用
近来再弄一个小项目,已经到收尾阶段了.希望加入写log机制来增加程序出错后的判断分析.尝试使用了python logging模块. #-*- coding:utf-8 -*- import loggi ...
- 读懂掌握 Python logging 模块源码 (附带一些 example)
搜了一下自己的 Blog 一直缺乏一篇 Python logging 模块的深度使用的文章.其实这个模块非常常用,也有非常多的滥用.所以看看源码来详细记录一篇属于 logging 模块的文章. 整个 ...
- python - argparse 模块学习
python - argparse 模块学习 设置一个解析器 使用argparse的第一步就是创建一个解析器对象,并告诉它将会有些什么参数.那么当你的程序运行时,该解析器就可以用于处理命令行参数. 解 ...
随机推荐
- [JSOI2012][bzoj4332] 分零食 [FFT]
题面 传送门 思路 首先,这个数据如果没有这么大,我们还是可以做朋友的...... 设$dp\left[i\right]\left[j\right]$代表前j个零食分给了前i个人的方案数 那么dp方程 ...
- Position 属性的学习理解
position 当时在学习的时候也没有进入深入的研究,主要是因为平时自己用的不是很多.今天看到了篇解释不错的文章就整理,学习下. http://www.cnblogs.com/bokin/archi ...
- Java EE 学习(1):什么是Java EE
转载: http://www.jb51.net/article/13059.htm 经常听朋友说什么J2EE,终于知道点什么是J2EE了,汗一个,上网搜了下这个说的比较详细了,J2EE,Java2平台 ...
- Eclipse SVN冲突详细解决方案
大家一起开发,难免有时会同时修改同一个文件,这样就要学会解决冲突.当大家更新代码,发现以下情况的时候,就说明你的修改的文件和服务器的文件产生了冲突(一般是别人也改了同一个文件). 1)和服务 ...
- 【HDOJ5975】Aninteresting game(BIT原理)
题意:给定n个区间,第i个区间的范围是[i-lowbit(i)+1,i].一共有q组询问,询问有两种: 1 x y:询问sigma lowbit(i) (x<=i<=y) 2.x:询问有几 ...
- 【HDOJ5510】Bazinga(KMP)
题意:给定n个由小写字母组成的字符串,第i个字符串为a[i],求最大的j满足存在1<=i<j,a[i]不是a[j]的子串,无解输出-1 T<=50,n<=500,len[i]& ...
- 全面解析Vue.nextTick实现原理
vue中有一个较为特殊的API,nextTick.根据官方文档的解释,它可以在DOM更新完毕之后执行一个回调,用法如下: // 修改数据 vm.msg = 'Hello' // DOM 还没有更新 V ...
- 使用python将ppm格式转换成jpg【转】
转自:http://blog.csdn.net/hitbeauty/article/details/48465017 最近有个很火的文章,叫 有没有一段代码,让你觉得人类的智慧也可以璀璨无比? 自己试 ...
- Android下设置CPU核心数和频率
现在的Android手机双核.四核变得非常普遍,同时CPU频率经常轻松上2G,功耗肯定会显著增加.而大多数的ARM架构的CPU采用的是对称多处理(SMP)的方式处理多CPU.这就意味着每个CPU核心是 ...
- LeetCode OJ-- LRU Cache ***@
https://oj.leetcode.com/problems/lru-cache/ 涨姿势的一道题,相当于实现一种数据结构,实现最近最少使用数据结构. // 用来记录 前后节点都是什么 类似链表上 ...