Python中使用logging模块打印log日志详解


Posted in Python onApril 05, 2015

学一门新技术或者新语言,我们都要首先学会如何去适应这们新技术,其中在适应过程中,我们必须得学习如何调试程序并打出相应的log信息来,正所谓“只要log打的好,没有bug解不了”,在我们熟知的一些信息技术中,log4xxx系列以及开发Android app时的android.util.Log包等等都是为了开发者更好的得到log信息服务的。在Python这门语言中,我们同样可以根据自己的程序需要打出log。

log信息不同于使用打桩法打印一定的标记信息,log可以根据程序需要而分出不同的log级别,比如info、debug、warn等等级别的信息,只要实时控制log级别开关就可以为开发人员提供更好的log信息,与log4xx类似,logger,handler和日志消息的调用可以有具体的日志级别(Level),只有在日志消息的级别大于logger和handler的设定的级别,才会显示。下面我就来谈谈我在Python中使用的logging模块一些方法。

logging模块介绍

Python的logging模块提供了通用的日志系统,熟练使用logging模块可以方便开发者开发第三方模块或者是自己的Python应用。同样这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP、GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。下文我将主要介绍如何使用文件方式记录log。

logging模块包括logger,handler,filter,formatter这四个基本概念。

logger:提供日志接口,供应用代码使用。logger最长用的操作有两类:配置和发送日志消息。可以通过logging.getLogger(name)获取logger对象,如果不指定name则返回root对象,多次使用相同的name调用getLogger方法返回同一个logger对象。
handler:将日志记录(log record)发送到合适的目的地(destination),比如文件,socket等。一个logger对象可以通过addHandler方法添加0到多个handler,每个handler又可以定义不同日志级别,以实现日志分级过滤显示。
filter:提供一种优雅的方式决定一个日志记录是否发送到handler。
formatter:指定日志记录输出的具体格式。formatter的构造方法需要两个参数:消息的格式字符串和日期字符串,这两个参数都是可选的。

基本使用方法

一些小型的程序我们不需要构造太复杂的log系统,可以直接使用logging模块的basicConfig函数即可,代码如下:

'''

Created on 2012-8-12

 

@author: walfred

@module: loggingmodule.BasicLogger

'''

import logging

 

log_file = "./basic_logger.log"

 

logging.basicConfig(filename = log_file, level = logging.DEBUG)

 

logging.debug("this is a debugmsg!")

logging.info("this is a infomsg!")

logging.warn("this is a warn msg!")

logging.error("this is a error msg!")

logging.critical("this is a critical msg!")

运行程序时我们就会在该文件的当前目录下发现basic_logger.log文件,查看basic_logger.log内容如下:

INFO:root:this is a info msg!

DEBUG:root:this is a debug msg!

WARNING:root:this is a warn msg!

ERROR:root:this is a error msg!

CRITICAL:root:this is a critical msg!

需要说明的是我将level设定为DEBUG级别,所以log日志中只显示了包含该级别及该级别以上的log信息。信息级别依次是:notset、debug、info、warn、error、critical。如果在多个模块中使用这个配置的话,只需在主模块中配置即可,其他模块会有相同的使用效果。

较高级版本

上述的基础使用比较简单,没有显示出logging模块的厉害,适合小程序用,现在我介绍一个较高级版本的代码,我们需要依次设置logger、handler、formatter等配置。

'''

Created on 2012-8-12

 

@author: walfred

@module: loggingmodule.NomalLogger

'''

import logging

 

log_file = "./nomal_logger.log"

log_level = logging.DEBUG

 

logger = logging.getLogger("loggingmodule.NomalLogger")

handler = logging.FileHandler(log_file)

formatter = logging.Formatter("[%(levelname)s][%(funcName)s][%(asctime)s]%(message)s")

 

handler.setFormatter(formatter)

logger.addHandler(handler)

logger.setLevel(log_level)

 

#test

logger.debug("this is a debug msg!")

logger.info("this is a info msg!")

logger.warn("this is a warn msg!")

logger.error("this is a error msg!")

logger.critical("this is a critical msg!")

这时我们查看当前目录的nomal_logger.log日志文件,如下:

[DEBUG][][2012-08-12 17:43:59,295]this is a debug msg!

[INFO][][2012-08-12 17:43:59,295]this is a info msg!

[WARNING][][2012-08-12 17:43:59,295]this is a warn msg!

[ERROR][][2012-08-12 17:43:59,295]this is a error msg!

[CRITICAL][][2012-08-12 17:43:59,295]this is a critical msg!

这个对照前面介绍的logging模块,不难理解,下面的最终版本将会更加完整。

完善版本

这个最终版本我用singleton设计模式来写一个Logger类,代码如下:

'''

Created on 2012-8-12

 

@author: walfred

@module: loggingmodule.FinalLogger

'''

 

import logging.handlers

 

class FinalLogger:

 

 logger = None

 

 levels = {"n" : logging.NOTSET,

  "d" : logging.DEBUG,

  "i" : logging.INFO,

  "w" : logging.WARN,

  "e" : logging.ERROR,

  "c" : logging.CRITICAL}

 

 log_level = "d"

 log_file = "final_logger.log"

 log_max_byte = 10 * 1024 * 1024;

 log_backup_count = 5

 

 @staticmethod

 def getLogger():

  if FinalLogger.logger is not None:

   return FinalLogger.logger

 

  FinalLogger.logger = logging.Logger("oggingmodule.FinalLogger")

  log_handler = logging.handlers.RotatingFileHandler(filename = FinalLogger.log_file,\

  maxBytes = FinalLogger.log_max_byte,\

  backupCount = FinalLogger.log_backup_count)

  log_fmt = logging.Formatter("[%(levelname)s][%(funcName)s][%(asctime)s]%(message)s")

  log_handler.setFormatter(log_fmt)

  FinalLogger.logger.addHandler(log_handler)

  FinalLogger.logger.setLevel(FinalLogger.levels.get(FinalLogger.log_level))

  return FinalLogger.logger

 

if __name__ == "__main__":

 logger = FinalLogger.getLogger()

 logger.debug("this is a debug msg!")

 logger.info("this is a info msg!")

 logger.warn("this is a warn msg!")

 logger.error("this is a error msg!")

 logger.critical("this is a critical msg!")

当前目录下的 final_logger.log内容如下:

[DEBUG][][2012-08-12 18:12:23,029]this is a debug msg!

[INFO][][2012-08-12 18:12:23,029]this is a info msg!

[WARNING][][2012-08-12 18:12:23,029]this is a warn msg!

[ERROR][][2012-08-12 18:12:23,029]this is a error msg!

[CRITICAL][][2012-08-12 18:12:23,029]this is a critical msg!

这个final版本,也是我一直用的,读者朋友也可以再加上其他的一些Handler,比如StreamHandler等等来获取更多的log信息,当然也可以将你的log信息通过配置文件来完成。
Python 相关文章推荐
新手该如何学python怎么学好python?
Oct 07 Python
Python 文件重命名工具代码
Jul 26 Python
Python线程指南详细介绍
Jan 05 Python
python 中if else 语句的作用及示例代码
Mar 05 Python
DataFrame 将某列数据转为数组的方法
Apr 13 Python
python批量修改文件编码格式的方法
May 31 Python
PyQt5通信机制 信号与槽详解
Aug 07 Python
python numpy 常用随机数的产生方法的实现
Aug 21 Python
numpy:np.newaxis 实现将行向量转换成列向量
Nov 30 Python
Python中SQLite如何使用
May 27 Python
Python logging模块原理解析及应用
Aug 13 Python
Python+OpenCV检测灯光亮点的实现方法
Nov 02 Python
Python中的两个内置模块介绍
Apr 05 #Python
Python中不同进制互相转换(二进制、八进制、十进制和十六进制)
Apr 05 #Python
Python中使用第三方库xlrd来写入Excel文件示例
Apr 05 #Python
Python中使用第三方库xlrd来读取Excel示例
Apr 05 #Python
Python中使用第三方库xlutils来追加写入Excel文件示例
Apr 05 #Python
Python下使用Psyco模块优化运行速度
Apr 05 #Python
Python中使用tarfile压缩、解压tar归档文件示例
Apr 05 #Python
You might like
php上传文件中文文件名乱码的解决方法
2013/11/01 PHP
深入探究PHP的多进程编程方法
2015/08/18 PHP
浅谈使用 Yii2 AssetBundle 中 $publishOptions 的正确姿势
2017/11/08 PHP
用Javascript做flash做的事..才完成的一个类.Auntion Action var 0.1
2007/02/23 Javascript
9个JavaScript评级/投票插件
2010/01/18 Javascript
被jQuery折腾得半死,揭秘为何jQuery为何在IE/Firefox下均无法使用
2010/01/22 Javascript
NodeJS框架Express的模板视图机制分析
2011/07/19 NodeJs
js delete 用法(删除对象属性及变量)
2014/08/24 Javascript
setTimeout()递归调用不加引号出错的解决方法
2014/09/05 Javascript
分享一个常用的javascript静态类
2014/12/31 Javascript
javascript判断数组内是否重复的方法
2015/04/21 Javascript
Jquery中$.post和$.ajax的用法小结
2015/04/28 Javascript
微信小程序tabBar底部导航中文注解api详解
2017/08/16 Javascript
[js高手之路]单例模式实现模态框的示例
2017/09/01 Javascript
3种vue路由传参的基本模式
2018/02/22 Javascript
微信小程序实现刷脸登录
2018/05/25 Javascript
微信小程序实现日期格式化和倒计时
2020/11/01 Javascript
JavaScript Canvas编写炫彩的网页时钟
2019/10/16 Javascript
使用JavaScript获取Django模板指定键值数据
2020/05/27 Javascript
JS自定义右键菜单实现代码解析
2020/07/16 Javascript
Jquery $.map使用方法实例详解
2020/09/01 jQuery
[49:21]完美世界DOTA2联赛循环赛 Ink Ice vs LBZS BO2第二场 11.05
2020/11/06 DOTA
python列表的增删改查实例代码
2018/01/30 Python
Python OpenCV读取png图像转成jpg图像存储的方法
2018/10/28 Python
PyQt5 QListWidget选择多项并返回的实例
2019/06/17 Python
程序员的七夕用30行代码让Python化身表白神器
2019/08/07 Python
Python拆分大型CSV文件代码实例
2019/10/07 Python
Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签
2019/12/04 Python
python重要函数eval多种用法解析
2020/01/14 Python
Oracle里面常用的数据字典有哪些
2014/02/14 面试题
平面设计自荐信
2013/10/07 职场文书
思想作风整顿个人剖析材料
2014/10/06 职场文书
商业门面租房协议书
2014/11/25 职场文书
南阳市白酒市场的调查报告
2019/11/08 职场文书
一文搞懂如何实现Go 超时控制
2021/03/30 Python
pytorch中的model=model.to(device)使用说明
2021/05/24 Python