python logging
参考:
https://docs.python.org/2/howto/logging.html#logging-basic-tutorial
https://docs.python.org/2/library/logging.config.html#logging-config-api
https://docs.python.org/2/howto/logging-cookbook.html#logging-cookbook
http://victorlin.me/posts/2012/08/26/good-logging-practice-in-python
背景
Logging 用来追踪程序运行过程中发生的事件, 事件按其重要性可划分为不同的级别: DEBUG, INFO, WARNING, ERROR, CRITICAL.
- DEBUG 运行中的详细信息, 特别用于代码调试
- INFO 确认事情按照期待的方式发生了
- WARNING 一些超出预期的事情发生或将要发生, 但是程序仍可以按照期望的方式继续运行
- ERROR 发生了更严重的事情, 程序的一些功能会受到影响, 无法进行
- CRITICAL 程序炸了
默认的级别是 WARNING, DEBUG 和 INFO 会被忽略.
输出到终端
import logging
logging.info("info information") # will print nothing
logging.warn("warn infotmation") # will print a message to the console
Output:
WARNING:root:warn infotmation
观察输出, WARNING 是级别, warn infomation 是记录的信息, root是啥? root 是 logger 的名字.
虽然我们没有显式创建 root logger, root logger 是默认创建的.
输出到文件
import logging logging.basicConfig(filename="example.log", level=DEBUG)
logging.debug("debug information")
logging.info("info information")
logging.error("error information") example.log
DEBUG:root:debug information
INFO:root:info information
ERROR:root:error information
注意到 basicConfig 方法, 该方法创建一个使用默认 Formatter 的 StreamHandler 并添加到 root logger. 如果 root logger 已经配置了 handler, 调用该方法 will do nothing.
参数 filename 用来指定日志输出的文件名, 一旦指定了 filename, StreamHandler 不会被创建, FileHandler 会代替 SteamHandler 添加到 root logger.
名词解释
Logger 提供应用直接调用的接口
Handler 将 logger 创建的日志发送到设定的目的地
Filter 过滤日志, 决定哪些可以输出(暂时用不到, 略)
Formatter 确定日志最终的输出格式
Logger
- Logger.setLevel() 设定级别
- Logger.addHandler(), Logger.removeHandler() 添加或删除 Handler
- Logger.addFilter(), Logger.removeFilter() 添加或删除 Filter
- Logger.debug(), Logger.info(), Logger.warn(), Logger.error(), Logger.critical()
- Logger.exception() 输出与 Logger.error() 相似, 附加异常详情, 用于异常处理
Handler
- Handler.setLevel() 设定级别, 决定是否继续传递
- Handler.setFormatter() 设定输出格式
- Handler.addFilter(), Handler.removeFilter() 添加或删除Filter
Formatter
- Formatter.__init__(fmt=None, datefmt=None) datefmt 默认为 "%Y-%m-%d %H:%M:%S" with the milliseconds tacked on at the end, fmt 默认为 "%(levelname)s:%(name)s:%(message)s"
同时输出到终端和文件, 终端级别为DEBUG, 文件级别为ERROR
import logging logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG) formatter = logging.Formatter("%(asctime)s-%(name)s-%(levelname)s-%(message)s") console = logging.StreamHandler()
console.setLevel(level=logging.DEBUG)
console.setFormatter(formatter) logfile = logging.FileHandler("example.log")
logfile.setLevel(level=logging.ERROR)
logfile.setFormatter(formatter) logger.addHandler(console)
logger.addHandler(logfile) logger.debug("debug information")
logger.info("info information")
logger.warn("warn information")
logger.error("error information")
logger.critical("critical information") Output:
2016-09-03 23:49:17,207-__main__-DEBUG-debug information
2016-09-03 23:49:17,207-__main__-INFO-info information
2016-09-03 23:49:17,207-__main__-WARNING-warn information
2016-09-03 23:49:17,207-__main__-ERROR-error information
2016-09-03 23:49:17,207-__main__-CRITICAL-critical information example.log
2016-09-03 23:49:17,207-__main__-ERROR-error information
2016-09-03 23:49:17,207-__main__-CRITICAL-critical information
logging.FileHandler() 支持相对路径和绝对路径, 习惯上使用绝对路径会好一些
logging.config.dictConfig
从字典中读取配置信息, 配置信息可以存储为 json 或 yaml 格式, yaml 更易读, pip install pyyaml
version: 1 disable_existing_logger: False formatters:
brief:
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: brief file:
class: logging.handlers.RotatingFileHandler
level: INFO
formatter: brief
filename: info.log
maxBytes: 10500000
backupCount: 5
encoding: utf8 mail:
class: logging.handlers.SMTPHandler
level: ERROR
formatter: brief
mailhost: localhost
fromaddr: username@test.com
toaddrs: [receiver0@test.com, receiver1@test.com]
subject: Program crashed!!! loggers:
warthog:
level: ERROR
handlers: [file, mail]
propagate: no root:
level: DEBUG
handlers: [console]
varsion: 1 必须存在且必须为1
disable_existing_logger 默认为 True, 会禁用除当前模块的所有 logger
handlers console, file, mail 标识不同的 handler, class, level, formatter 指定特定的 Handler, 级别, 输出格式, 其他的参数由不同的 Handler 决定.
loggers warthog 标识不同的 logger, 使用方式为 logger.getLogger("warthog"), propagate 默认为 yes, warthog logger 的日志会向上传递到 root logger.
如果一个模块叫做 warthog.py, logger = logging.getLogger(__name__), 该 logger 就是 logger warthog
进阶
use __name__ as the logger name
__name__ 是当前模块的名字, 假设当前模块是 foo.bar.my_module, 只要对 logger foo 进行设置, 所有 foo. 中模块的 logger 会自动继承.
logger.exception
try:
open('/path/to/does/not/exist', 'rb')
except (SystemExit, KeyboardInterrupt):
raise
except Exception as e:
logger.exception("Failed to open file")
#logger.error("Failed to open file", exc_info=True) Output: ERROR:__main__:Failed to open file
Traceback (most recent call last):
File "example.py", line 6, in <module>
open('/path/to/does/not/exist', 'rb')
IOError: [Errno 2] No such file or directory: '/path/to/does/not/exist'
Do not get logger at the module level unless disable_existing_loggers is False
# not good
import logging logger = logging.getLogger(__name__) def foo():
logger.info("info message") # better
import logging
def foo():
logger = logging.getLogger(__name__)
logger.info("info message")
python logging的更多相关文章
- python logging模块可能会令人困惑的地方
python logging模块主要是python提供的通用日志系统,使用的方法其实挺简单的,这块就不多介绍.下面主要会讲到在使用python logging模块的时候,涉及到多个python文件的调 ...
- python logging 配置
python logging 配置 在python中,logging由logger,handler,filter,formater四个部分组成,logger是提供我们记录日志的方法:handler是让 ...
- Python LOGGING使用方法
Python LOGGING使用方法 1. 简介 使用场景 场景 适合使用的方法 在终端输出程序或脚本的使用方法 print 报告一个事件的发生(例如状态的修改) logging.info()或log ...
- python logging 日志轮转文件不删除问题
前言 最近在维护项目的python项目代码,项目使用了 python 的日志模块 logging, 设定了保存的日志数目, 不过没有生效,还要通过contab定时清理数据. 分析 项目使用了 logg ...
- python logging模块使用
近来再弄一个小项目,已经到收尾阶段了.希望加入写log机制来增加程序出错后的判断分析.尝试使用了python logging模块. #-*- coding:utf-8 -*- import loggi ...
- python Logging的使用
日志是用来记录程序在运行过程中发生的状况,在程序开发过程中添加日志模块能够帮助我们了解程序运行过程中发生了哪些事件,这些事件也有轻重之分. 根据事件的轻重可分为以下几个级别: DEBUG: 详细信息, ...
- Python logging 模块和使用经验
记录下常用的一些东西,每次用总是查文档有点小麻烦. py2.7 日志应该是生产应用的重要生命线,谁都不应该掉以轻心 有益原则 级别分离 日志系统通常有下面几种级别,看情况是使用 FATAL - 导致程 ...
- Python logging日志系统
写我小小的日志系统 配置logging有以下几种方式: 1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数: 2)创建一个日志配置文件, ...
- python logging模块使用流程
#!/usr/local/bin/python # -*- coding:utf-8 -*- import logging logging.debug('debug message') logging ...
- python logging 日志轮转文件不删除问题的解决方法
项目使用了 logging 的 TimedRotatingFileHandler : #!/user/bin/env python # -*- coding: utf-8 -*- import log ...
随机推荐
- OrcharNoCMS中的发布订阅使用
对于Orchard里面的EventBus,没有太多的文章去介绍说明.它最好的应用是发布订阅的应用. 使用介绍: 在Car模块中,我们定义一个接口,继承IEventHandler接口. 当我们在创建一条 ...
- tensorflow学习笔记三:实例数据下载与读取
一.mnist数据 深度学习的入门实例,一般就是mnist手写数字分类识别,因此我们应该先下载这个数据集. tensorflow提供一个input_data.py文件,专门用于下载mnist数据,我们 ...
- elasticsearch suggest 的几种使用-completion 的基本 使用
在lucene里面,suggest 的支持非常完善,可以随心所欲的定制: 但是在es中使用起来就没有那么方便了. es给suggest 分类4类:term :phrase: completion: c ...
- 【平面设计AFTER】读到的设计海报分层法
来源参考:http://www.uisdc.com/graphic-designer-self-improvement 分层法的三层:“背景层”,“图形层”,“信息层” 1,背景层,一般为纯色,场景, ...
- Redis集群(三):主从配置一
一.本文目的 Redis的主从配置分为两篇文章,第一篇主要介绍了Redis主从配置的搭建过程及使用,第二篇主要说明各种情况下Redis主从状态,如Master挂掉,Slaver挂掉, ...
- 【OpenJudge 1665】完美覆盖
http://noi.openjudge.cn/ch0405/1665/?lang=zh_CN 状压水题,手动转移 #include<cstdio> #include<cstring ...
- 线段树 poj 1436
题目大意:给出n条垂直于x轴的线段的数据y1,y2,x,求出有几个三条线段一组的三元组并且他们兩兩能相见的.思路:对y轴建树,将x排序,然后按顺序边询问边擦入,用mark[i][j]表示j往左可以看到 ...
- C#-WinForm-Winform TextBox中只能输入数字的几种常用方法(C#)
方法一: private void tBox_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 0x20) e.KeyCh ...
- VBScript使用CDO.Message发送邮件
Const Email_From = "from@163.com" Const Password = "password" Const Email_To = & ...
- mac下配置Qt for Android+iOS
ref: http://www.cnblogs.com/yjmyzz/p/4219829.html http://www.cnblogs.com/rophie/p/3226543.html http: ...