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中的函数用法入门教程
Sep 02 Python
Python爬取读者并制作成PDF
Mar 10 Python
简单谈谈python中的语句和语法
Aug 10 Python
python中实现指定时间调用函数示例代码
Sep 08 Python
Python利用字典将两个通讯录文本合并为一个文本实例
Jan 16 Python
PyQt5每天必学之关闭窗口
Apr 19 Python
python之cv2与图像的载入、显示和保存实例
Dec 05 Python
python图像和办公文档处理总结
May 28 Python
python之拟合的实现
Jul 19 Python
python字典setdefault方法和get方法使用实例
Dec 25 Python
django-orm F对象的使用 按照两个字段的和,乘积排序实例
May 18 Python
python 爬取华为应用市场评论
May 29 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
4月1日重磅发布!《星际争霸II》6.0.0版本更新
2020/04/09 星际争霸
ini_set的用法介绍
2014/01/07 PHP
yii实现级联下拉菜单的方法
2014/07/31 PHP
基于thinkphp5框架实现微信小程序支付 退款 订单查询 退款查询操作
2020/08/17 PHP
一种JavaScript的设计模式
2006/11/22 Javascript
在chrome中window.onload事件的一些问题
2010/03/01 Javascript
转义字符(\)对JavaScript中JSON.parse的影响概述
2013/07/17 Javascript
jquery购物车实时结算特效实现思路
2013/09/23 Javascript
javascript中DOM复选框选择用法实例
2015/05/14 Javascript
JQuery中节点遍历方法实例
2015/05/18 Javascript
JS+CSS实现大气的黑色首页导航菜单效果代码
2015/09/10 Javascript
JS匿名函数类生成方式实例分析
2016/11/26 Javascript
JS日程管理插件FullCalendar中文说明文档
2017/02/06 Javascript
IE11下使用canvas.toDataURL报SecurityError错误的解决方法
2017/11/19 Javascript
利用vue和element-ui设置表格内容分页的实例
2018/03/02 Javascript
js字符串处理之绝妙的代码
2019/04/05 Javascript
js实现div色块拖动录制
2020/01/16 Javascript
vue中axios防止多次触发终止多次请求的示例代码(防抖)
2020/02/16 Javascript
原生js实现密码强度验证功能
2020/03/18 Javascript
vue radio单选框,获取当前项(每一项)的value值操作
2020/09/10 Javascript
[06:04]DOTA2国际邀请赛纪录片:Just For LGD
2013/08/11 DOTA
[03:24]CDEC.Y赛前采访 努力备战2016国际邀请赛中国区预选赛
2016/06/25 DOTA
python合并同类型excel表格的方法
2018/04/01 Python
Python使用re模块正则提取字符串中括号内的内容示例
2018/06/01 Python
django中ORM模型常用的字段的使用方法
2019/03/05 Python
伦敦眼门票在线预订:London Eye
2018/05/31 全球购物
美国珠宝店:Helzberg Diamonds
2018/10/24 全球购物
编码实现字符串转整型的函数
2012/06/02 面试题
乡镇信息公开实施方案
2014/03/23 职场文书
工地安全质量标语
2014/06/07 职场文书
员工生日会策划方案
2014/06/14 职场文书
关于读书的活动方案
2014/08/14 职场文书
2014年国庆节活动总结
2014/08/26 职场文书
Angular性能优化之第三方组件和懒加载技术
2021/05/10 Javascript
HTML基础详解(上)
2021/10/16 HTML / CSS
clear 万能清除浮动(clearfix:after)
2023/05/21 HTML / CSS