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脚本来实现产生实时的数 ...
随机推荐
- 安装weinre在PC端调试移动端
1.使用node安装weinre. 2.启动weinre, weinre --httpPort 8081 --boundHost -all- 3.在浏览器打开 http://localhost:80 ...
- Euclidean Space
http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
- Robot Framework--03 案例及资源区
转自:http://blog.csdn.net/tulituqi/article/details/7585387 这个区域是我们案例结构设计的一个关键区域,这里可以清晰的看到我们整个工程的结构. 还记 ...
- winform的扩展的带有截图功能picturebox
using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using Sys ...
- 使用maven编译Java项目 http://www.tuicool.com/articles/YfIfIrq
使用maven编译Java项目 时间 2014-07-17 17:42:37 Way Lau's Blog 原文 http://www.waylau.com/build-java-project- ...
- EF: Raw SQL Queries
Raw SQL Queries Entity Framework allows you to query using LINQ with your entity classes. However, t ...
- Java生成html静态网页
public static void makeHtml() { try { URL url = new URL("http://www.baidu.com/"); //本实事例通过 ...
- XMLBEANS的使用总结
在本文中,我们将详细了解最好的数据对象XMLBean.从传统角度来说,在Java应用程序中使用XML,就是在从 XML文档向Java导入数据的技术或从数据模型层向XML导出数据技术之间架起了一座桥梁. ...
- mysql规范
1.命名规范 (1)库名.表名.(按现在的规范类似; PromoHayaoRecord),数据库名使用小写,字段名必须使用小写字母,并采用下划线分割.(2)库名.表名.字段名禁止超过32个字符.(3) ...
- select2
.select2-container .select2-choice { height: 34px; line-height: 34px; } .自定义 组件高度 在css 里面设置 .select2 ...