對於小型專案而言,大家習慣於使用print語句列印資訊到終端進行除錯,然而,當專案**量擴大到了一定級別後,列印除錯的方法就顯得很凌亂了,更重要的是,當debug完成後,甄別並刪除(或注釋)除錯用的列印語句變得非常令人頭痛。而使用日誌模組則能很好地解決這些問題。
日誌(logging)是在程式執行過程中對發生的事件的追蹤、記錄。程式開發者們在**中引入日誌模組以指示某種特定事件的發生,而這些事件可以依據重要程度劃分為不同的層級,比如一般資訊(info),警告(warning),錯誤(error)等。
python的日誌模組提供了一系列的函式用來記錄不同的日誌資訊,包括』debug()』,info()
,warning
,error()
,critical()
等,下面的表對不同的函式適用範圍做了說明:
任務合適的工具
列印指令碼資訊或**資訊到控制台
print()
在程式正常執行時發生的報告事件(例如狀態監測或故障調查)
logging.info()(或者在診斷時使用logging.debug())輸出詳細的資訊
在執行出現問題時發出警告資訊
logging.warning()
對特定的執行時事件報告錯誤
丟擲異常
不引發異常的錯誤報告
比如長時間執行的伺服器程序中的錯誤處理程式
這些函式都是根據追蹤事件的級別和嚴重程度來命名的。如下所示:
級別使用場景
debug
並且只在除錯程式時關心的程式執行詳細資訊
info
確認程式像預期一樣工作
warning
指示超出預期的事件的發生或未來的將發生的問題
error
由於一些嚴重的問題,程式不能執行某些特定的函式
critical
嚴重的錯誤,用來指示程式將不能繼續執行下去
預設的層級是warning,即只追蹤警告及其以上的事件發生,比如下面的簡單的例子:
執行結果:import logging
logging.warning('watch out!') # 將會在終端列印資訊
logging.info('i told you so') # 不會列印任何資訊
warning:root:watch out!
執行上面的**,然後開啟import logging
logging.basicconfig(filename='example.log',level=logging.debug)
logging.debug('this message should go to the log file')
logging.info('so should this')
logging.warning('and this, too')
example.log
檔案,將會看到下面的內容:
這段**也對如何設定日誌層級進行了說明。其實,也可以通過命令列的方式設定:debug:root:this message should go to the log file
info:root:so should this
warning:root:and this, too
--log=info
然後加入下面的**讀到設定好的層級資訊:
如果不斷執行上面的程式,新的日誌將追加到舊的日誌之後,這會變得越來越龐大,可以通過下面的方法使新的日誌覆蓋舊的日誌:numeric_level = getattr(logging, loglevel.upper(), none)
if not isinstance(numeric_level, int):
raise valueerror('invalid log level: %s' % loglevel)
logging.basicconfig(level=numeric_level, ...)
logging.basicconfig(filename='example.log', filemode='w', level=logging.debug)
import logging
import mylib
def main():
logging.info('started')
mylib.do_something()
logging.info('finished')
if __name__ == '__main__':
main()
# mylib.py
import logging
def do_something():
logging.info('doing something')
可以使用格式化字串的方法記錄變數:info:root:started
info:root:doing something
info:root:finished
除了上面的方法外,也可以使用str.format()和string.template方法。import logging
logging.warning('%s before you %s', 'look', 'leap!')
輸出:import logging
logging.basicconfig(format='%(levelname)s:%(message)s', level=logging.debug)
logging.info('so should this')
logging.warning('and this, too')
info:so should this
warning:and this, too
輸出:import logging
logging.basicconfig(format='%(asctime)s %(message)s')
logging.warning('is when this event was logged.')
2010-12-12 11:41:42,612 is when this event was logged.
預設的日期格式是iso8601,你也可以在basicconfig
中進行改變:
輸出:import logging
logging.basicconfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%y %i:%m:%s %p')
logging.warning('is when this event was logged.')
12/12/2010 11:46:36 am is when this event was logged.
除此之外,還可以使用time.strftime()
來改變時間格式。
更高階的使用方法請看官方教程 advanced logging tutorial
python 日誌使用logging
將日誌列印入檔案,同時列印在控制台 logfile.py coding utf 8 import sys import logging from logging.handlers import timedrotatingfilehandler def getlogconfig name defaul...
Python日誌模組logging
logging分為4個模組 loggers,handlers,filters,and formatters.logger logger.setlevel 設定日誌級別 logger.addhandler 和logger.removehandler 增加和刪除日誌處理器 logger.addfilte...
python 記錄日誌logging
在專案開發中,往往要記錄日誌檔案。用python記錄日誌有兩種方式 1 利用python 自帶的logging庫,例如 coding utf 8 import osimport codecs import datetime import logging 封裝logging日誌 class logfi...