Logging 模块

简介

Python的 logging 模块提供了灵活的日志处理相关功能, 可以用来追踪程序运行的情况。

logging 模块提供了一系列标准的日志等级: DEBUG, INFO, WARNING, ERROR, CRITICAL, 顾名思义可以大致看出它们各自的使用情况。 logging 模块设置的默认等级时 WARNING, 这意味着默认情况下,日志级别为 WARNING, ERROR, CRITICAL 的日志会被记录,而 DEBUG, INFO 的日志会被忽略。

不同等级的value值如下,只有当value大于 logger 的值才会记录日志。

Level    Value
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
UNSET 0

简单输出日志

下面看一个简单的官方文档上的例子:

import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

输出如下:

WARNING:root:Watch out!

可以看到info记录的信息没有输出,这是因为默认输出级别不低于WARNING级别的。

输入日志到文件

logging 支持输出日志到文件,参考下面示例:

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

其中level是指的记录等级, 输出如下:

DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too

几个基本概念

loggers

logger是logging模块提供的日志类 Logger 的实例,它暴露出接口可以直接供程序调用。

每个实例都有一个名字,并且示例间有类之间那种继承关系,根据logger的名字来区分,比如叫"scan"的logger是叫"scan.text"和"scan.html"的父类(没错,他们是以点号错分隔符)。

所有logger共同的父类是 root , 就是上面示例中的中间那个默认的root。 basicConfig 默认的输出格式为: severity:logger name:message

logger的通过 logging.getLogger(name) 来创建,有种在包里命名的惯用做法是:

logger = logging.getLogger(__name__)

这样的好处是可以从logger的名字清楚的看到记录的来源。

handlers 和轮转日志

handlers 承担 logging 模块里负责处理合适的信息到不同的地方的角色,下面通过设置一个RotatingFileHandler来展示handler的特性。

有时候需要创建多个轮转日志,每个日志保存一定长度的内容,最多保留一定数量的日志,其余的丢弃,这种情况下,可以定义 RotatingFileHandler 来实现:

logging_rotatingfile_example.py
import glob
import logging
import logging.handlers LOG_FILENAME = 'logging_rotatingfile_example.out' # Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG) # Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME,
maxBytes=20,
backupCount=5,
)
my_logger.addHandler(handler) # Log some messages
for i in range(20):
my_logger.debug('i = %d' % i) # See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)
for filename in logfiles:
print(filename)

运行输出如下:

logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5

当日志内容达到定义的 maxBytes 时,会自动重命名文件后加上后缀".1",如果已经存在后续的".1",".2"等则自动重命名他们向后加1,最后最多只保留 backupCount 定义数量的日志文件。

其它有用的handler参见这里

Formatters 和 个性化输出

Formatters 可以用来控制日志输出的格式,参考下面的示例:

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')

输出如下:

2016-11-27 23:18:51,128 - simple_example - DEBUG - debug message
2016-11-27 23:18:51,128 - simple_example - INFO - info message
2016-11-27 23:18:51,128 - simple_example - WARNING - warn message
2016-11-27 23:18:51,128 - simple_example - ERROR - error message
2016-11-27 23:18:51,128 - simple_example - CRITICAL - critical message

可以看到 %(asctime)s - %(name)s - %(levelname)s - %(message)s 这里对格式化输出的影响。

其中默认的日期时间显示的格式是ISO8601格式, 也可以自定义时间格式,如下面的例子:

import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')

输出:

python test12.py
11/27/2016 11:22:41 PM is when this event was logged.

好有个比较有用的格式化参数时 %(lineno)d, 显示logger调用的时候所处的行数。具体的格式和作用可以参见这里

其它

logger.exception

ERROR 的等级记录日志,但和 DEBUG 等级一样会输出详细的错误信息,通常用在exception处理中

Filter Object

Filters 是可以被handlers和loggers用来过滤日志的输出的,因为用的不多,具体可参见文档

线程安全

logging模块是通过线程锁保证线程安全的。

Logging Flow

官方文档上看到的logging流程图,可以帮助理解日志记录流程,参见这里

从配置文件获取logging的配置

参见这里

参考资料

Python logging 模块简介的更多相关文章

  1. Python logging模块简介

    logging模块提供logger,handler,filter,formatter. logger:提供日志接口,供应用代码使用.logger最长用的操作有两类:配置和发送日志消息.可以通过logg ...

  2. Python Logging 模块研究

    背景在一个新的项目里面加入了日志功能,想自己写一个,但是一个偶然的机会,通过google发现Python内建了一个非常强大的日志(log)模块:l... 背景 在一个新的项目里面加入了日志功能,想自己 ...

  3. (转)python logging模块

    python logging模块 原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python ...

  4. 13 python logging模块

    原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日 ...

  5. python logging模块【转载】

    转自:https://www.cnblogs.com/dahu-daqing/p/7040764.html 参考:老顽童log模块,讲的很细致,基本上拿到手就可以直接用了,很赞 1 logging模块 ...

  6. python logging模块可能会令人困惑的地方

    python logging模块主要是python提供的通用日志系统,使用的方法其实挺简单的,这块就不多介绍.下面主要会讲到在使用python logging模块的时候,涉及到多个python文件的调 ...

  7. python logging模块使用

    近来再弄一个小项目,已经到收尾阶段了.希望加入写log机制来增加程序出错后的判断分析.尝试使用了python logging模块. #-*- coding:utf-8 -*- import loggi ...

  8. 读懂掌握 Python logging 模块源码 (附带一些 example)

    搜了一下自己的 Blog 一直缺乏一篇 Python logging 模块的深度使用的文章.其实这个模块非常常用,也有非常多的滥用.所以看看源码来详细记录一篇属于 logging 模块的文章. 整个 ...

  9. Python logging 模块学习

    logging example Level When it's used Numeric value DEBUG Detailed information, typically of interest ...

随机推荐

  1. 使用GreenDao 添加字段,删除表,新增表操作

    GreenDao 给我个人感觉 比一般的ORM框架要好很多,虽然说上手和其他的比起来,较复杂,但是如果使用熟练以后,你会爱上这个框架的 用这些ORM 框架给我的感觉都是,当升级时,都需要进行数据库所有 ...

  2. simotion byte/word ASCII码转换为字符、字符串

    建立string类型,和byte类型(ASCII)的数据 将byte类型(ASCII)赋值给string中的一个字符 参考程序 VAR_GLOBAL myword :WORD; mystring :S ...

  3. java集合框架——Set

    一.Set概述 Set集合的特点是元素不允许重复,而且是无序的(添加和取出的顺序不一致). Set接口中的方法和Collection接口中的方法几乎相同,略. Set接口下常用的两个类:HashSet ...

  4. Django QuestSet API (官方文档)

    1.返回新查询集的方法 (1)filter():滤指定条件的结果 Entry.objects.filter(pub_date__gt=datetime.date(2005, 1, 3), headli ...

  5. app接口测试总结

    前段时间在测试一个项目,任务是测试app的API.总结下遇到的问题类型: 1 通过app提交数据,隐形数据有误.(主要通过验证数据库) 比如用户通过app输入工单提交.接口数据中,用户输入的信息都正确 ...

  6. [转载]Memcached缓存服务的简单安装

    1.Linux下的安装方法 下载:wget http://memcached.org/latest tar -zxvf memcached-1.x.x.tar.gz cd memcached-1.x. ...

  7. tomcat7 的The Apache Tomcat Native library which allows optimal performance 的解决

    1.        用Myeclipse启动tomcat7启动时可能会收到下面的信息: 七月 24, 2014 10:13:30 上午 org.apache.catalina.core.AprLife ...

  8. IOS SQLite函数总结

    SQL语句的种类 ●  数据定义语句(DDL:Data Definition Language) ●  包括create和drop等操作 ●  在数据库中创建新表或删除表(create table或 ...

  9. IOS 数据加密总结(及MD5加密)

    数据安全总结 1.网络数据加密1> 加密对象:隐私数据,比如密码.银行信息2> 加密方案* 提交隐私数据,必须用POST请求* 使用加密算法对隐私数据进行加密,比如MD53> 加密增 ...

  10. 砍树,POJ(2665)

    题目链接:http://poj.org/problem?id=2665 解题报告: 这里的区域没有重复,若有重复的话,模拟即可. #include <cstdio> #include &l ...