Python Logging模塊-介紹與使用

概述

Logging模塊是python自帶的日誌模塊,提供了強大的API和配置系統,用於在項目中打印各級別的日誌。

日誌級別

Logging模塊提供了5種日誌的級別,如下表所示:

級別 說明
DEBUG 詳細的信息,在進行診斷問題時使用
INFO 正常運行的信息
WARNING 警示發生了一些意外的情況,或者警示將會出現問題,比如磁盤空間不足。程序仍正常運行。
ERROR 程序的某些功能已經不能正常使用
CRITICAL 表示嚴重錯誤,程序已經不能繼續跑了

且他們的順序是:CRITICAL>ERROR>WARNING>INFO>DEBUG
默認的級別是WARNING,意思是隻有比WARNING高級別的日誌纔會打印或者記錄下來。

使用

打印到屏幕上

import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

這樣的話會輸出到屏幕上:

Watch out! 

爲什麼不會輸出I told you so呢?因爲當前默認的級別是WARNING,INFO比它低,所以不會輸出。

打印到文件

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')

這樣將級別設置爲DEBUG,則打開example.log可以看到

DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too

使用格式化的輸出

logging.basicConfig(level=logging.INFO,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S',
                filename='example.log')
logging.warning('is when this event was logged.')

這會打印出

2016-04-25 16:00:36 test.py[line:39] INFO is when this event was logged

裏面各個參數分別是時間,文件名,行號,日誌級別,這樣日誌就完善了許多。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章