python日志浅析
输出日志对于追踪问题比较重要。
默认logger(root)
python使用logging模块来处理日志。通常下面的用法就能满足常规需求:
import logging
logging.debug('some debug level info....')#debug级别消息
logging.info('some info level info...')#info级别消息
logging.warn('some warning level info...')#warning级别消息
logging.critical('some critical level info...')#critical级别消息
logging.error('some error level info...')#error级别消息
输出类似:
[2015-01-07 10:11:34,579](DEBUG)root : adsfaf
即:
[时间](级别)logger名称:消息
默认输出到console。
自定义logger
如果某个模块有个性的需求,比如,记录到文件,或者发送邮件。那么问题来了,怎么破?
如果发生了某种严重的情况,想要发送邮件的话,需要自己定义一个logger,并设置好级别(setLevel(logging.CRITICAL))以及处理器(logging.handlers.SMTPHandler),demo如下:
import logging
logger = logging.getLogger('email_logger')
logger.setLevel(logging.CRITICAL)
mail_handler= logging.handlers.SMTPHandler('your_mail_host_ip','from_addr','to_addr','critical and above level msg from xxx ') logging.info('blablabla...')
logging.error('notice please, an error happens when ...')
记录文件,需要有文件处理器(logging.FileHandler)。demo如下:
import logging
logger = logging.getLogger('file_logger')
logger.addHandler(logging.FileHandler('all.log'))
logger.info('some info...')
还需要其他的handler?参考这里。
配置型logger
是否已经厌倦了写代码的方式来自定义logger?好吧,它可以有更多的配置。可以参考这里。
三种方式:
1. 上面已经提到了
2. 通过fileConfig读取配置文件
以下来自官方demo
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')
配置文件:
[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
输出:
$ 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 = xxx,xxxx [handlers] keys = xxx,xxx [formatters] keys =xxx,xxx
赋值部分
logger赋值
[logger_xxx]
level = DEBUG/INFO/WARN/CRITICAL/ERROR
handlers = [handlers]里定义的handler
qualname = logger名
propagate = 1/0 #是否将log丢给上一级处理
handler赋值
[handler_xxx]
class = StreamHander/FileHander/handlers.SMTPHandler...
args = 传递给上面class的参数
level = DEBUG/INFO/WARN/CRITICAL/ERROR #是否处理,可以和logger的不同
formatter = [formatters]中定义的格式器
比较有用的一个handlers配置
[handler_rotateFileHandler]
class=handlers.RotatingFileHandler
args=('xxx.log', 'a', 2000000, 9)#日志超过2000000 d的时候,重新另外生成一个文件,保存9天的记录
...
formatter赋值
[formatter_xxx]
format = %(var)s # var:asctime/name/levelname/message/ip/user/module/process/thread...
logging.config.fileConfig的特别说明:
disable_existing_loggers是一个可选参数,默认为True。它会阻止在fileConfig语句前面的logger的正常执行。其设计目的是为了反向兼容。
要使得所有的logger都有效,要么在配置文件中,将前面的logger给配置进去。
要么将它改为False。
3. 通过dictConfig读取配置dict
django 就使用了这种方式,配置dict如下:
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'filters': {
'special': {
'()': 'project.logging.SpecialFilter',
'foo': 'bar',
}
},
'handlers': {
'null': {
'level':'DEBUG',
'class':'django.utils.log.NullHandler',
},
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
'formatter': 'simple'
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'filters': ['special']
}
},
'loggers': {
'django': {
'handlers':['null'],
'propagate': True,
'level':'INFO',
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': False,
},
'myproject.custom': {
'handlers': ['console', 'mail_admins'],
'level': 'INFO',
'filters': ['special']
}
}
}
转载请注明,本文来自Tommy.Yu的博客。谢谢!
python日志浅析的更多相关文章
- 浅析python日志重复输出问题
浅析python日志重复输出问题 问题起源: 在学习了python的函数式编程后,又接触到了logging这样一个强大的日志模块.为了减少重复代码,应该不少同学和我一样便迫不及待的写了一个自己的日 ...
- Python日志输出——logging模块
Python日志输出——logging模块 标签: loggingpythonimportmodulelog4j 2012-03-06 00:18 31605人阅读 评论(8) 收藏 举报 分类: P ...
- python日志模块logging
python日志模块logging 1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...
- python 日志打印之logging使用介绍
python 日志打印之logging使用介绍 by:授客QQ:1033553122 测试环境: Python版本:Python 2.7 简单的将日志打印到屏幕 import logging lo ...
- python 日志的配置,python对日志封装成类,日志的调用
# python 日志的配置,python对日志封装成类,日志的调用 import logging # 使用logging模块: class CLog: # --------------------- ...
- python日志模块logging学习
介绍 Python本身带有logging模块,其默认支持直接输出到控制台(屏幕),或者通过配置输出到文件中.同时支持TCP.HTTP.GET/POST.SMTP.Socket等协议,将日志信息发送到网 ...
- Python 日志输出中添加上下文信息
Python日志输出中添加上下文信息 除了传递给日志记录函数的参数(如msg)外,有时候我们还想在日志输出中包含一些额外的上下文信息.比如,在一个网络应用中,可能希望在日志中记录客户端的特定信息,如: ...
- python日志模块笔记
前言 在应用中记录日志是程序开发的重要一环,也是调试的重要工具.但却很容易让人忽略.之前用flask写的一个服务就因为没有处理好日志的问题导致线上的错误难以察觉,修复错误的定位也很困难.最近恰好有时间 ...
- Python日志产生器
Python日志产生器 写在前面 有的时候,可能就是我们做实时数据收集的时候,会有一个头疼的问题就是,你会发现,你可能一下子,没有日志的数据源.所以,我们可以简单使用python脚本来实现产生实时的数 ...
随机推荐
- 为什么可以用while(cin)?
为什么可以用while(cin)? /** * @brief The quick-and-easy status check. * * This allows you to write const ...
- Visual Studio低版本升级到Visual Studio 2012出现Warning LNK4075
Warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/SAFESEH' specification
- Object.prototype.toString.call() 区分对象类型
判断一个对象的类型: /** * 判断对象是否为数组 * @param {Object} source 待判断的对象 * @return {Boolean} true|false */ Object. ...
- App Store
App store最新审核标准(2015.3)公布 http://www.cnii.com.cn/mobileinternet/2015-03/24/content_1550301.htm iOS提交 ...
- A股博弈笔记
A股博弈笔记 @2014/11/07 A股行情最近甚嚣尘上,似乎是牛市的前奏,指数虽然见涨,但赔钱的股民估计也不少,本人就是其中一个,是我在逆势而行吗? 试图追逐价值投资的方式,而钟情于蓝筹股,本来也 ...
- jquery access方法 有什么用
Jquery设置对象属性的有几种方法1.获取属性attr(name) 2.设置属性attr(name,value)3.批量设置属性attr(properties)4.为所有匹配的元素设置一个计算的属性 ...
- bootstrapValidator.js 做表单验证
有这样的一个场景,我们在提交form表单的时候 可能要做一些验证,比如判断是不是为空,电话的格式验证,邮箱的格式验证等等,手写起来也是可以得. 但是今天我介绍一个bootstrap插件简化开发.就是b ...
- smarty string_format用法 取小数点后2位
<{if $d.ul_pv}> <{$d.sum/$d.ul_pv|string_format:'%.2f'}> <{else}> 0.00 <{/if}&g ...
- 【AngularJS】—— 4 表达式
前面了解了AngularJS的基本用法,这里就跟着PDF一起学习下表达式的相关内容. 在AngularJS中的表达式,与js中并不完全相同. 首先它的表达式要放在{{}}才能使用,其次相对于javas ...
- 【AngularJS】—— 5 表单
这部分,我们写一个表单程序,使用angularjs的检测并完成表单属性的获取与拷贝. 在AngularJS中,也支持html5中多种控件的自动检测,如:text.number.url.email.ra ...