python logging模块
1.logging模块提供了四个组件
logger:日志类,有两个功能
1)配置日志的等级,处理器handler,过滤器filter
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.addFilter(filter)
2)写日志
logger.info()
handler:处理器类,实际写日志的类
常用的处理器有StreamHandler和FileHandler
StreamHandler将日志输出到stream,如sys.stdout,sys.stderr
FileHandler将日志输出到文件
处理器类可以配置自己的等级,过滤器
一个logger可以配置多个处理器类
filter:过滤器类,过滤日志等级,内容
使用示例如下:
class InfoFilter(logging.Filter):
def filter(self,rec):
reurn rec.levelno==logging.INFO
logger.addFilter(InfoFilter())
formatter:内容格式化类,格式化输出的内容
格式化配置,使用%(<dict key>)s的形式,具体有哪些关键字,可以参照官网的介绍。
使用示例如下:
fmt='%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'
formatter=logging.Formatter(fmt)
handler.setFormatter(formatter)
2.logger对象
使用logging.getLogger(name=None)函数找到一个logger对象,当name指定的logger不存在时,会自动创建一个该名称的对象,保存在logging.manage的loggerDict中。
3.logging日志输出流程
logger输出日志的流程:
1)用户代码调用打印日志函数(logging.info(),logging.debug()等)
2)若希望打印的日志级别不够,则流程停止。否则进入步骤3
3)建立一个LogRecord对象,该对象代表打印的日志
4)判断这条日志是否被filter过滤掉,如果被过滤,流程停止。否则进入步骤5
5)logger将LogRecord传递到它定义的handlers,进行处理
6)判断当前logger的propagate属性,为0,则流程停止,否则进入步骤7
7)判断当前logger有无父logger,如果没有,流程停止,否则设置当前logger为它的父logger,继续执行步骤5
注:logger对象是有继承关系的,如名为a.b,a.c的logger都是名为a的子logger,并且所有的logger对象都继承自root,如果子对象没有添加handler等配置,会从父对象继承,这样可以通过继承关系来复用配置。
handler处理日志的过程:
1)如果当前LogRecord的级别小于handler所设置的LogLevel,则停止流程,否则进入步骤2
2)判断当前LogRecord是否被handler设置的filter过滤,如果被过滤,流程停止,否则日志输出到最终目的地。
4.logging使用示例
logging有三种配置方式
1)代码定义logger,handler等
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import logging.config handler = logging.StreamHandler()
fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s' formatter = logging.Formatter(fmt) # 实例化formatter
handler.setFormatter(formatter) # 为handler添加formatter logger = logging.getLogger('tst') # 获取名为tst的logger
logger.addHandler(handler) # 为logger添加handler
logger.setLevel(logging.DEBUG) logger.info('first info message')
logger.debug('first debug message')
2)logging配置文件
loggin.conf采用了模式匹配的方式进行配置,正则表达式是r'^[(.*)]$',从而匹配出所有的组件。对于同一个组件具有多个实例的情况使用逗号‘,’进行分隔。对于一个实例的配置采用componentName_instanceName配置块。使用这种方式还是蛮简单的。
logging.conf
[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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
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')
3)logging配置字典
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import logging.config LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'test': {
'handlers': ['console'],
'level': 'ERROR',
},
},
}
logging.config.dictConfig(LOGGING)
logger = logging.getLogger('test')
logger.info('info message dict')
logger.warn('warn message dict')
logger.error('error message dict')
logger.critical('critical message dict')
python 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 logging模块
python logging模块 原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python ...
- Python logging 模块学习
logging example Level When it's used Numeric value DEBUG Detailed information, typically of interest ...
- python logging—模块
python logging模块 python logging提供了标准的日志接口,python logging日志分为5个等级: debug(), info(), warning(), error( ...
- Python logging模块无法正常输出日志
废话少说,先上代码 File:logger.conf [formatters] keys=default [formatter_default] format=%(asctime)s - %(name ...
- 0x03 Python logging模块之Formatter格式
目录 logging模块之Formatter格式 Formater对象 日志输出格式化字符串 LogRecoder对象 时间格式化字符串 logging模块之Formatter格式 在记录日志是,日志 ...
- 0x01 Python logging模块
目录 Python logging 模块 前言 logging模块提供的特性 logging模块的设计过程 logger的继承 logger在逻辑上的继承结构 logging.basicConfig( ...
- Python Logging模块的简单使用
前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...
随机推荐
- hashmap 读取
hashTable hashSet 都差不多 以hashmap为例,底层是一个散列表 数组,然后数组存出一个entry对象,对象中有两个泛型属性,一个可以指向自身类型的引用,这样就可以在每一个数组的位 ...
- jQuery lazyload 懒加载
Lazy Load 是一个用 JavaScript 编写的 jQuery 插件. 它可以延迟加载长页面中的图片. 在浏览器可视区域外的图片不会被载入, 直到用户将页面滚动到它们所在的位置. 这与图片预 ...
- Spring @Scheduled应用解析
最近,遇到的一个需求,需要执行定时任务,每个一定时间需要执行某个方法 因为项目是SpringMVC的项目,所以使用的是Spring @Scheduled(由于quartz应用起来太麻烦,所以没有采用) ...
- JSP 甜点
JSP cookies Cookies是存储在客户机的文本文件,它们保存了大量轨迹信息.在servlet技术基础上,JSP显然能够提供对HTTP cookies的支持. 通常有三个步骤来识别回头客: ...
- AC自动机及trie图 pascal
; type data=record sum,failed:longint; son:array ['a'..'z'] of longint; end; ..maxn] of data; que:.. ...
- adb获取不了设备List of devices attached
方法/步骤: 首先找到手机的安装完之后的“设备的硬件id”,第一步右击我的电脑,然后找到设备管理器打开. 在设备管理器中,找到ADB driver然后点开. 然后在详细信息中,点开硬件ID,查看到我的 ...
- Azure自动化实例: 复制blog用于备份
在Azure 自动化:使用PowerShell Credential连接到Azure, 之后, 我在项目中遇到了实现blog备份的任务, 现将其作为一个实例写下来: 1. 首先,创建自动化帐户, 在资 ...
- python-selenium之firefox、Chrome、Ie运行
测试脚本是否支持在不同浏览器运行firefox浏览器运行脚本 from selenium import webdriver driver=webdriver.Firefox() driver.get( ...
- eclipse常用插件
1. eclipse安装主题插件:http://www.eclipsecolorthemes.org/ 2. eclipse terminal插件:在eclipse中集成终端,使用非常方便,不用单独打 ...
- Matlab绘图函数一览
要查看Matlab所有绘图函数,请从Matlab主界面菜单查看“绘图目录”,或从Matlab帮助文档查看“Types of MATLAB Plots”(在线版本).本文的图和英文解释摘自Matlab帮 ...