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 ...
随机推荐
- WPF MVVM 验证
WPF MVVM(Caliburn.Micro) 数据验证 书接前文 前文中仅是WPF验证中的一种,我们暂且称之为View端的验证(因为其验证规是写在Xaml文件中的). 还有一种我们称之为Model ...
- EF6 在 SQLite中使用备忘
== 菜鸟级选手试验在EF6中使用Sqlite,零EF基础,少量Sqlite基础.经过断断续续的很长时间 - _ -! >>连接 1. 安装 使用目前最新版本EF6.1,Sqlite1.0 ...
- php特殊用法
1.将字符串转换成可执行的php代码(简单的代码)--eval() <?php $str="echo phpinfo();"; echo eval( $str);
- SpringBean_获取Spring加载的所有bean(实践)
一.查询代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 3 ...
- BZOJ 4552: [Tjoi2016&Heoi2016]排序
4552: [Tjoi2016&Heoi2016]排序 Time Limit: 60 Sec Memory Limit: 256 MBSubmit: 579 Solved: 322[Sub ...
- 【Phylab2.0】Alpha版本项目展示
团队成员 冯炜韬(PM)http://www.cnblogs.com/toka 岳桐宇(后端)http://www.cnblogs.com/mycraftmw 杨子琛(测试&LaTeX)htt ...
- poj 2724 Purifying Machinef
poj 2724 Purifying Machinef 题意 每一个01串中最多含有一个'*','*'既可表示0也可表示1,给出一些等长的这样的01串,问最少能用多少个这样的串表示出这些串.如:000 ...
- 总结的JS数据类型判定(非常全面)
用typeof 来检测数据类型 Javascript自带两套类型:基本数据类型(undefined,string,null,boolean,function,object)和对象类型. 但是如果尝试用 ...
- 框架集(Framesets)
1.Frameset的使用 所谓框架便是网页画面分成几个框窗,同时取得多个 URL.只 要 <FRAMESET> <FRAME> 即可,而所有框架标记 要放在一个总起的 htm ...
- 如何使用iconfont字体代替小图片?
我们以阿里巴巴矢量图标库举例,地址:http://www.iconfont.cn/ 在这里,你可以上传你的矢量图标,也可以直接使用现成的小图标. 为什么要用这些个图标字体,本文就不介绍了,请自行百度. ...