前言

日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法。本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表。

另外,Python的HOWTOs文档很详细,连日志该怎么用都写了,所以有英文阅读能力的同学建议去阅读一下。

Logging模块构成

组成

主要分为四个部分:

  • Loggers:提供应用程序直接使用的接口
  • Handlers:将Loggers产生的日志传到指定位置
  • Filters:对输出日志进行过滤
  • Formatters:控制输出格式

日志级别

Level Numeric value When it’s used
DEBUG 10 Detailed information, typically of interest only when diagnosing problems.
INFO 20 Confirmation that things are working as expected.
WARNING 30 An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR 40 Due to a more serious problem, the software has not been able to perform some function.
CRITICAL 50 A serious error, indicating that the program itself may be unable to continue running.
NOSET 0 getattr(logging, loglevel.upper())

默认级别是WARNING,可以使用打印到屏幕上的方式记录,也可以记录到文件中。

模块使用示例

简单例子

打印输出
In [5]: import logging

In [6]: logging.warning("FBI warning")
WARNING:root:FBI warning In [7]: logging.info("information")
# 没有打印是因为默认级别是warning
输出到文件中
In [4]: import logging

In [5]: logging.basicConfig(filename='example.log', level=logging.DEBUG)

In [6]: logging.debug("debug")

In [7]: logging.warning('warning')

In [8]: logging.info('info')

In [9]: ls
C++ STL/ a.py example.log parser/ test.sh* In [10]: cat example.log
DEBUG:root:debug
WARNING:root:warning
INFO:root:info In [14]: logging.warning('new warning')
# 注意这种是直接往后面添加,也就是add的,若是想覆盖内容可以更改文件写入方式 In [15]: cat example.log
DEBUG:root:debug
WARNING:root:warning
INFO:root:info
WARNING:root:new warning # 覆盖的方式写入例子
(test) ➜ test ipython
WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
Python 2.7.11 (default, Jun 17 2016, 20:01:51)
Type "copyright", "credits" or "license" for more information. IPython 4.2.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details. In [1]: import logging In [2]: logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG) In [3]: logging.warning('FBI warning') In [4]: ls
C++ STL/ a.py example.log parser/ test.sh* In [5]: cat example.log
WARNING:root:FBI warning In [6]: quit
(test) ➜ test ipython
WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
Python 2.7.11 (default, Jun 17 2016, 20:01:51)
Type "copyright", "credits" or "license" for more information. IPython 4.2.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details. In [1]: import logging In [2]: logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG) In [3]: logging.warning('warning') In [4]: cat example.log
WARNING:root:warning
变量的使用

print语句中使用变量一样,如:

In [5]: logging.warning('%s before you %s', 'Look', 'leap!')

In [6]: cat example.log
WARNING:root:warning
WARNING:root:Look before you leap!
输出格式

可以在basicConfig中设置,参数名称可以参见链接,可以设置时间什么的,如:

In [2]: import logging

In [3]: logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG)

In [4]: logging.warning('And this, too')
2016-12-06 15:40:43,577:WARNING:And this, too

进阶使用

当想项目中使用logging模块的时候肯定不能在这样一句句的写了,一般可能会抽象出一个模块来,这样比较有效一些。logging模块提供了四个类(Loggers,Formatters,Filtters,Handlers)来实现不同的功能,与此对应的我们如果想封装一个函数,也就要针对这几个功能来自定义一下。

想自定义的话思路也很简单,首先实例化一个相应的对象,然后进行一些设置,可以简单看一下下面的例子:

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') # 输出是:
$ python simple_logging_module.py
2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
2005-03-19 15:10:26,620 - simple_example - INFO - info message
2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
2005-03-19 15:10:26,697 - simple_example - ERROR - error message
2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
从配置文件导入配置

模块内容:

import logging
import logging.config logging.config.fileConfig('logging.conf') # create logger
logger = logging.getLogger('simpleExample') # 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message') # 输出
$ python simple_logging_config.py
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message

配置文件内容:

[loggers]
keys=root,simpleExample [handlers]
keys=consoleHandler [formatters]
keys=simpleFormatter [logger_root]
level=DEBUG
handlers=consoleHandler [logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0 [handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,) [formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

同时也可以使用YAML格式的配置文件,如:

version: 1
formatters:
simple:
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
loggers:
simpleExample:
level: DEBUG
handlers: [console]
propagate: no
root:
level: DEBUG
handlers: [console]

PS

Logging模块使用也会有很多坑,常见的是日志重复打印的问题,大家可以搜一下,这里提供一些链接供参考:

  1. http://www.jianshu.com/p/25f70905ae9d
  2. https://yinzo.github.io/14610807170718.html
  3. http://python.jobbole.com/86887/

参考

  1. https://docs.python.org/2/library/logging.html
  2. https://docs.python.org/2/howto/logging.html#logging-basic-tutorial

Python Logging模块的简单使用的更多相关文章

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

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

  2. python logging模块使用

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

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

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

  4. Python logging 模块学习

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

  5. python logging—模块

    python logging模块 python logging提供了标准的日志接口,python logging日志分为5个等级: debug(), info(), warning(), error( ...

  6. 0x01 Python logging模块

    目录 Python logging 模块 前言 logging模块提供的特性 logging模块的设计过程 logger的继承 logger在逻辑上的继承结构 logging.basicConfig( ...

  7. (转)python logging模块

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

  8. Python logging模块无法正常输出日志

    废话少说,先上代码 File:logger.conf [formatters] keys=default [formatter_default] format=%(asctime)s - %(name ...

  9. 0x03 Python logging模块之Formatter格式

    目录 logging模块之Formatter格式 Formater对象 日志输出格式化字符串 LogRecoder对象 时间格式化字符串 logging模块之Formatter格式 在记录日志是,日志 ...

随机推荐

  1. iOS:frame访问、设置简化

    看到一些程序都有这种写法,也不知道原创者是谁了.先在博客保存下. 在.m文件 #import "UIView+MyFrameCategory.h" @implementation ...

  2. Swift-数组

    Swift数组 OC和Swift数组的比较 OC 只能存放对象 swift 既可以存放对象,又可以存Int,Float等基本数据类型 下面是swift数组的具体示范 空数组 let arr = [] ...

  3. 使用gulp解决外部编辑器修改Eclipse文件延迟更新的问题

    本人前端用惯了Hbuilder,修改了eclipse项目中的文件后,由于是外部编辑器修改过的,eclipse不会自动部署更新,一般按F5刷新项目,或者在 preferences > genera ...

  4. IT软件的编程方向 - 进阶者系列 - 学习者系列文章

    IT软件经过了这么些年的发展,已经形成了很多的软件公司和开发团队,而且当前编程语言也有很多种,让开发人员能够有很大的选择.现在国际上的开发阵营基本分为ASP.NET.JAVA和PHP三种,但是每种开发 ...

  5. Spring 4 使用Freemarker模板发送邮件&添加附件

    前言 Spring对Java的邮件发送提供了很好的支持,提供了超级简单的API,大大简化了Java邮件发送功能的开发. Spring对Email的支持是基于JavaMail API开发的,所以,我们在 ...

  6. android 关闭多个或指定activity

    打开了.activityA,B,C,D,...然后到E一起关闭前面所有activity(转自:http://blog.csdn.net/lengguoxing/article/details/4214 ...

  7. MyBatis源码分析-IDEA新建MyBatis源码工程

    MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以对配置和原生Map使用简 ...

  8. Cookie和Session的那些事儿

    Cookie和Session都是为了保持用户的访问状态,一方面为了方便业务实现,另一方面为了简化服务端的程序设计,提高访问性能.Cookie是客户端(也就是浏览器端)的技术,设置了Cookie之后,每 ...

  9. [LeetCode] Longest Common Prefix 最长共同前缀

    Write a function to find the longest common prefix string amongst an array of strings. 这道题让我们求一系列字符串 ...

  10. 使用 Docker 编译 OpenWRT(Widora)

    Docker 是一种新的被称之为容器的虚拟机.本文将使用此工具,进行 OpenWRT 的编译. 在 Docker 中下载 Ubuntu 14.04 的镜像 使用以下命令可以十分方便的从远程服务器上将 ...