Python Logging 模块研究

背景

在一个新的项目里面加入了日志功能,想自己写一个,但是一个偶然的机会,通过google发现Python内建了一个非常强大的日志(log)模块:logging。粗略的研究了一下,下面是我的一些心得札记。

为什么使用日志

追踪程序的一些运行信息,以达到时刻了解程序运行的状况,快速捕获程序的异常,及时发现程序错误的目的

logging模块简介

从Python2.3起,Python的标准库加入了logging模块.logging模块给运行中的应用提供了一个标准的信息输出接口.典型的logging机制实现是把要输出的数据简单地写到一个txt文件中去.写log文件的方式是一种常见的打log的方式,而logging模块提供的更多,它可以把输出信息输出到所有类文件的对象中去,甚至TCP和UDP的sockets,email服务器,Unix的syslog系统,NT系列的事件log系统,内存的buffer和HTTP服务器,当然还有”真正的”文件中去.

引入logging模块:

import logging #import logging module
#使用logging模块:
class CLog:
   #----------------------------------------------------------------------------
   def __init__(self):
      self.logger = logging.getLogger()
      fileHandler = logging.FileHandler(LOG_FILE_PATH)
      formatHandler = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
      fileHandler.setFormatter(formatHandler)
      self.logger.addHandler(fileHandler)
      self.logger.setLevel(logging.NOTSET)
  
   #----------------------------------------------------------------------------
   def DebugMessage(self,msg):
      self.logger.debug(msg)
      pass
     
oCLog = CLog()

上面定义了一个简单的log模块,我想用这一段简单的代码来描述一下logging模块

logger

获取log的一个实例,这个部分代码分离做得很好,可以通过增加不同的handler来丰富log实例的特性

FileHandler

指定了Log的输出端是文件,通过传入文件路劲来指定输出文件,我们可以为Log定义其他的输出端例如StreamHandler,以及其他各种复杂的输出方式,文件是可能是最常用的方式,其他方式有待慢慢探索

FormatHandler

FomartHandler指定了FileHandler的输出格式,例如我使用了以下的格式:('%(asctime)s %(levelname)s: %(message)s'),则输出的文本格式为:

2013-07-25 08:20:01,525 INFO: goodbye [127.0.0.1]:60442

有关format的关键字,例如asctime,levelname,可参考LogRecord attributes 官方文档

Level

Logging模块定义了5种log信息的优先级

LevelWhen it’s used

DEBUGDetailed information, typically of interest only when diagnosing problems.

INFOConfirmation that things are working as expected.

WARNINGAn 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.

ERRORDue to a more serious problem, the software has not been able to perform some function.

CRITICALA serious error, indicating that the program itself may be unable to continue running.

优先级关系:

DEBUG < INFO < WARNING < ERROR < CRITCAL

可以根据 self.logger.debug(msg),self.logger.info(msg),等函数来确定输出信息的优先级

SetLevel

SetLevel函数定义了Log实例对处理log信息的优先级,如果定义的优先级为info,则所有debug的信息都将忽略,不输出到输出端,只输入设定优先级以及设定优先级以上的信息

上一篇:你所不知道的python 循环中的else
下一篇:python线程池进一步认识

PythonTab微信公众号:

Python技术交流互助群 ( 请勿加多个群 ):

群1: 87464755

群2: 333646237

群3: 318130924

群4: 385100854