Python Logging 模塊研究
背景在一個新的項目里面加入了日志功能,想自己寫一個,但是一個偶然的機會,通過google發現Python內建了一個非常強大的日志(log)模塊:l...
背景
在一個新的項目里面加入了日志功能,想自己寫一個,但是一個偶然的機會,通過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()</pre>
上面定義了一個簡單的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的信息都將忽略,不輸出到輸出端,只輸入設定優先級以及設定優先級以上的信息
</div>