输出日志对于追踪问题比较重要。

默认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日志浅析的更多相关文章

  1. 浅析python日志重复输出问题

    浅析python日志重复输出问题 问题起源: ​ 在学习了python的函数式编程后,又接触到了logging这样一个强大的日志模块.为了减少重复代码,应该不少同学和我一样便迫不及待的写了一个自己的日 ...

  2. Python日志输出——logging模块

    Python日志输出——logging模块 标签: loggingpythonimportmodulelog4j 2012-03-06 00:18 31605人阅读 评论(8) 收藏 举报 分类: P ...

  3. python日志模块logging

    python日志模块logging   1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...

  4. python 日志打印之logging使用介绍

    python 日志打印之logging使用介绍 by:授客QQ:1033553122 测试环境: Python版本:Python 2.7   简单的将日志打印到屏幕 import logging lo ...

  5. python 日志的配置,python对日志封装成类,日志的调用

    # python 日志的配置,python对日志封装成类,日志的调用 import logging # 使用logging模块: class CLog: # --------------------- ...

  6. python日志模块logging学习

    介绍 Python本身带有logging模块,其默认支持直接输出到控制台(屏幕),或者通过配置输出到文件中.同时支持TCP.HTTP.GET/POST.SMTP.Socket等协议,将日志信息发送到网 ...

  7. Python 日志输出中添加上下文信息

    Python日志输出中添加上下文信息 除了传递给日志记录函数的参数(如msg)外,有时候我们还想在日志输出中包含一些额外的上下文信息.比如,在一个网络应用中,可能希望在日志中记录客户端的特定信息,如: ...

  8. python日志模块笔记

    前言 在应用中记录日志是程序开发的重要一环,也是调试的重要工具.但却很容易让人忽略.之前用flask写的一个服务就因为没有处理好日志的问题导致线上的错误难以察觉,修复错误的定位也很困难.最近恰好有时间 ...

  9. Python日志产生器

    Python日志产生器 写在前面 有的时候,可能就是我们做实时数据收集的时候,会有一个头疼的问题就是,你会发现,你可能一下子,没有日志的数据源.所以,我们可以简单使用python脚本来实现产生实时的数 ...

随机推荐

  1. HDU 1326 Box of Bricks(水~平均高度求最少移动砖)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1326 题目大意: 给n堵墙,每个墙的高度不同,求最少移动多少块转使得墙的的高度相同. 解题思路: 找到 ...

  2. hdu 1873 看病要排队(优先级队列)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1873 题目大意: 三个医生看病,病人排队看病,病人有优先级,优先级高的提前看病,同样的优先级按先后.I ...

  3. JSON FX

    https://github.com/mckamey/jsonfx-v1#svn/trunk/JsonFx/JsonFx.Json

  4. Mastering C# structs

    http://www.developerfusion.com/article/84519/mastering-structs-in-c/

  5. 使用System Sound Services 播放音效(最简单,比较底层),调用AudioServicesPlaySystemSound()

    1.适用范围:一些很小的提示或警告音频. 2.使用限制: 声音长度不能超过30秒 声音文件必须是PCM或IMA4(IMA/ADPCM)格式.(有时候可播放一些特殊的.mp3) 打包成.caf..aif ...

  6. Mac安装Brew

    安装命令如下:curl -LsSf http://github.com/mxcl/homebrew/tarball/master | sudo tar xvz -C/usr/local --strip ...

  7. How to convert any valid date string to a DateTime.

    DateTimeFormatInfo pattern = new DateTimeFormatInfo() { ShortDatePattern = "your date pattern&q ...

  8. 为你的Visual Studio单独设置代理服务器

    http://blog.sina.com.cn/s/blog_58c506600101tycn.html 最近,因为国内访问Visual Studio Online(微软的免费代码托管服务,以前叫Te ...

  9. I got a plan in 2014

    工作快3年了,始终逃脱不出一种混日子打酱油的赶脚,一切都似乎是在虚度. 最近好像有患上很严重的拖延症,工作上总是分散精力,无法聚集自己的事情. 开始这个博客,希望记录一些有用文字,不管是工作.生活,还 ...

  10. Oracle 中count(1) 和count(*) 的区别

    count()与count(*)比较: 如果你的数据表没有主键,那么count()比count(*)快 如果有主键的话,那主键(联合主键)作为count的条件也比count(*)要快 如果你的表只有一 ...