参考:

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的更多相关文章

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

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

  2. python logging 配置

    python logging 配置 在python中,logging由logger,handler,filter,formater四个部分组成,logger是提供我们记录日志的方法:handler是让 ...

  3. Python LOGGING使用方法

    Python LOGGING使用方法 1. 简介 使用场景 场景 适合使用的方法 在终端输出程序或脚本的使用方法 print 报告一个事件的发生(例如状态的修改) logging.info()或log ...

  4. python logging 日志轮转文件不删除问题

    前言 最近在维护项目的python项目代码,项目使用了 python 的日志模块 logging, 设定了保存的日志数目, 不过没有生效,还要通过contab定时清理数据. 分析 项目使用了 logg ...

  5. python logging模块使用

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

  6. python Logging的使用

    日志是用来记录程序在运行过程中发生的状况,在程序开发过程中添加日志模块能够帮助我们了解程序运行过程中发生了哪些事件,这些事件也有轻重之分. 根据事件的轻重可分为以下几个级别: DEBUG: 详细信息, ...

  7. Python logging 模块和使用经验

    记录下常用的一些东西,每次用总是查文档有点小麻烦. py2.7 日志应该是生产应用的重要生命线,谁都不应该掉以轻心 有益原则 级别分离 日志系统通常有下面几种级别,看情况是使用 FATAL - 导致程 ...

  8. Python logging日志系统

    写我小小的日志系统 配置logging有以下几种方式: 1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数: 2)创建一个日志配置文件, ...

  9. python logging模块使用流程

    #!/usr/local/bin/python # -*- coding:utf-8 -*- import logging logging.debug('debug message') logging ...

  10. python logging 日志轮转文件不删除问题的解决方法

    项目使用了 logging 的 TimedRotatingFileHandler : #!/user/bin/env python # -*- coding: utf-8 -*- import log ...

随机推荐

  1. discuz论坛插件设计学习培训视频全套教程

    discuz模板跟插件开发的教程比较少,特搜集给大家学习插件做的好,在dsicuz应用中心出 售也是可以卖不少的呢 教程目录:第1章  本章的标题第1节Discuz! X 产品安装与配置第2节模板风格 ...

  2. 基于jquery的has()方法以及与find()方法以及filter()方法的区别详解

    has(selector选择器或DOM元素)   将匹配元素集合根据选择器或DOM元素为条件,检索该条件在每个元素的后代中是否存在,将符合条件的的元素构成新的结果集. 下面举一个例子: <ul& ...

  3. VMware 设备VMnet0 上的网桥暂时关闭。此虚拟机无法与主机或网格中的其他计算机通信【转】

    今天克隆了一个win7的虚拟机,移动到我的本地.打开时发现虚拟机网格连接图标出现X断开连接,于是网上收了一堆答案无一个可用的,决定自己解决这个问题,解决过程如下: 1.报错图如下:设备VMnet0 上 ...

  4. C语言编程实现Linux命令——who

    C语言编程实现Linux命令--who 实践分析过程 who命令是查询当前登录的每个用户,它的输出包括用户名.终端类型.登录日期及远程主机,在Linux系统中输入who命令输出如下: 我们先man一下 ...

  5. 解决 PHPExcel 长数字串显示为科学计数

    解决 PHPExcel 长数字串显示为科学计数 在excel中如果在一个默认的格中输入或复制超长数字字符串,它会显示为科学计算法,例如身份证号码,解决方法是把表格设置文本格式或在输入前加一个单引号. ...

  6. jsp中的<%%>和<!%%>的区别

    jsp 都是解析成.java文件` 具体代码请看 如果你写 <%int a=1;%> 生成的代码是 public class xxx_jsp { public void doProcess ...

  7. Android,不小心关闭了某个小窗口怎么恢复,方法介绍

    Window > Show View > Other 需要哪个窗口就用哪个~

  8. PHP处理0e开头md5哈希字符串缺陷/bug

    PHP在处理哈希字符串时,会利用”!=”或”==”来对哈希值进行比较,它把每一个以”0E”开头的哈希值都解释为0,所以如果两个不同的密码经过哈希以后,其哈希值都是以”0E”开头的,那么PHP将会认为他 ...

  9. phpexcel导入数据部分数据有误

    数据在excel中是这样的: 插入数据库后是这样的: 很难发现,出错的那几条数据中的单元格中都有英文','符号,而phpexcel又是以','来拼接读取到的数据的. 解决办法:修改代码中的','为不常 ...

  10. 日常资料(TNB)

    http://www.med66.com/html/2005/5/hu47563183418550025733.html http://www.guokr.com/article/192045/ ht ...