在一個新的項目裏面加入了日誌功能,想本身寫一個,可是一個偶然的機會,經過google發現Python內建了一個很是強大的日誌(log)模塊:logging。粗略的研究了一下,下面是個人一些心得札記。html
從Python2.3起,Python的標準庫加入了logging模塊.logging模塊給運行中的應用提供了一個標準的信息輸出接口.典型的logging機制實現是把要輸出的數據簡單地寫到一個txt文件中去.寫log文件的方式是一種常見的打log的方式,而logging模塊提供的更多,它能夠把輸出信息輸出到全部類文件的對象中去,甚至TCP和UDP的sockets,email服務器,Unix的syslog系統,NT系列的事件log系統,內存的buffer和HTTP服務器,固然還有」真正的」文件中去.python
引入logging模塊:服務器
import logging #import logging module
使用logging模塊:app
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模塊socket
獲取log的一個實例,這個部分代碼分離作得很好,能夠經過增長不一樣的handler來豐富log實例的特性函數
指定了Log的輸出端是文件,經過傳入文件路勁來指定輸出文件,咱們能夠爲Log定義其餘的輸出端例如StreamHandler,以及其餘各類複雜的輸出方式,文件是多是最經常使用的方式,其餘方式有待慢慢探索學習
FomartHandler指定了FileHandler的輸出格式,例如我使用瞭如下的格式:('%(asctime)s %(levelname)s: %(message)s'),則輸出的文本格式爲:google
有關format的關鍵字,例如asctime,levelname,可參考LogRecord attributes 官方文檔spa
Logging模塊定義了5種log信息的優先級debug
Level | When it’s used |
---|---|
DEBUG | Detailed information, typically of interest only when diagnosing problems. |
INFO | Confirmation that things are working as expected. |
WARNING | An 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. |
ERROR | Due to a more serious problem, the software has not been able to perform some function. |
CRITICAL | A 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函數定義了Log實例對處理log信息的優先級,若是定義的優先級爲info,則全部debug的信息都將忽略,不輸出到輸出端,只輸入設定優先級以及設定優先級以上的信息
以上是筆者在學習過程當中的一些總結,在使用logging模塊的這段時間內,發現這個模塊實在是博大精深。
若是您還存在疑問,我想官方文檔是您最佳的學習資源: