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 ...
随机推荐
- sql server pivot/unpivot 行列互转
有时候会碰到行转列的需求(也就是将列的值作为列名称),通常我都是用 CASE END + 聚合函数来实现的. 如下: declare @t table (StudentName nvarchar(20 ...
- RapidJSON 代码剖析(三):Unicode 的编码与解码
根据 RFC-7159: 8.1 Character Encoding JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32. The defa ...
- 【技术贴】大型发布会现场的WiFi网络应该如何搭建?
WiFi网络的部署要远远比一般人想象的复杂,不是说放上几十个AP带宽就自动增加几十倍,恰恰相反,简单放几十个AP带宽会由于AP之间的竞争而 迅速使带宽下降为几乎不可用.实际上这个问题完全可以写一本书了 ...
- 几个常用的CV知识点
刚结束一段实习,图像算法工程师.总结一下图像算法的几个基本的操作,图像操作算子各式各样,各显神通,光是滤波filter这一个专题就可以有很多的技巧和功能. 我从做过的两个小项目入手, 简单介绍一下该项 ...
- HTTP原型
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...
- [转]Struts2.3.16.1+Hibernate4.3.4+Spring4.0.2 框架整合
原文地址:http://blog.csdn.net/ycb1689/article/details/22928519 最新版Struts2+Hibernate+Spring整合 目前为止三大框架最新版 ...
- MVC架构模式分析与设计(一)---简单的mvc架构
首先 我要感谢慕课网的老师提供视频资料 http://www.imooc.com/learn/69 下面我来进行笔记 我们制作一个简单的mvc架构 制作第一个控制器 testController.cl ...
- 用CSS绘制最常见的形状和图形
#rectangle { width: 200px; height: 100px; background: red; } #circle { width: 100px; height: 100px; ...
- outlook 2016 for windows 每次刷新发送接收邮件会弹出登陆界面
Q: outlook2016 for windows 每次刷新发送接收邮件会弹出登陆界面,office365 ProPlus 都是正常激活了,Word 和Excel都不存在此类问题 A: 排除用户的o ...
- 微信小程序之明源商城系列-01-商城介绍及开发准备
1,效果展示 数据来自于写的一个小爬虫爬了明源商城部分的数据.由于价格的保密性,下列产品价格和真实的都不同. 1.1 主页及开发文件结构 1.2 产品的详细页面 1.2 产品分类页面 1.3 产品 ...