Python Logging 模組研究

pythontab發表於2013-07-25

背景

在一個新的專案裡面加入了日誌功能,想自己寫一個,但是一個偶然的機會,透過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的資訊都將忽略,不輸出到輸出端,只輸入設定優先順序以及設定優先順序以上的資訊

相關文章