(2022.04.21 Thur)
Logging提供的日志記錄方式有兩種泛领,分別是
- 模塊級別的函數(shù)
- 日志系統(tǒng)的四大組件
日志級別
logging日志分為五個級別赡盘,從低到高如下
- DEBUG: 詳細信息糊肤,level=10
- INFO: 普通信息竟趾,確認程序如預期運行言缤,level=20
- WARNING: 警告薯蝎,表示程序可能發(fā)生意想不到的問題簿煌,但仍然可以正常運行氮唯,level=30
- ERROR: 錯誤信息,程序某些功能不能執(zhí)行姨伟,level=40
- CRITICAL: 嚴重錯誤惩琉,程序無法繼續(xù)執(zhí)行,level=50
默認級別是WARNING夺荒。設置了日志級別之后瞒渠,該級別和高于該級別的信息都可以保存/顯示。
日志信息可輸出到控制臺console技扼,也可輸出到指定文件伍玖。
import logging
def logging_test():
logging.debug('this is a debug logging.')
logging.info('this is an info logging.')
logging.warning('this is a warning logging.')
logging.error('this is an error logging.')
logging.critical('this is a critical logging.')
return 'done'
調(diào)用
>>> logging_test()
WARNING:root:this is a warning logging.
ERROR:root:this is an error logging.
CRITICAL:root:this is a critical logging.
'done'
注意,對logging級別沒有設置剿吻,所以默認是WARNING窍箍,僅顯示W(wǎng)ARNING, ERROR, CRITICAL三個信息。
日志設置
通過logging.basicConfig
可設置,比如
>>> logging.basicConfig(filename='logging_debut.log', level=logging.DEBUG)
可設置的選項包括
- filename: 保存成的log文件名
- level: 日志級別
- filemode: 如果制定了filename椰棘,則指定打開模式('w', 'r', 'a')纺棺,默認'a'
- format: 為處理程序使用指定格式的字符串
- datafmt: 使用time.strftime()所接受的指定日期/時間格式
- style: 如果指定了格式,則對格式字符串使用此樣式邪狞,’%’ 用于 printf 樣式祷蝌、’{’ 用于 str.format()、’$’ 用于 string帆卓,默認為“%”
指定的格式包括:
- %(asctime)s: 日志發(fā)生的時間
- %(levelname)s: 日志級別
- %(message)s: 日志記錄的文本內(nèi)容
- %(name)s: 所使用的日志器名稱巨朦,默認'root'
- %(pathname)s: 日志記錄的函數(shù)的文件的全路徑
- %(filename)s: 日志記錄的函數(shù)的文件
- %(funcName)s: 日志記錄的函數(shù)的函數(shù)名
- %(lineno)s: 日志記錄的代碼所在的行號
應用模塊級別函數(shù)和設置信息生成日志
def test():
log_format = '%(asctime)s: %(levelname)s - %(message)s'
log_filename = 'logging_debut_fmt.log'
logging.basicConfig(filename= log_filename, level=logging.DEBUG, \
format=log_format)
logging.info('instanciate a class')
a = [1,2,3]
logging.debug('instance: '+str(a))
logging.warning('conduct addition')
b = [34,5,6]
logging.critical('b: '+str(b))
tmp = a+b
logging.info('results: '+str(tmp))
return 'done'
查看log文件,logging_debut_fmt.log
$ cat logging_debut_fmt.log
2022-04-21 12:09:26,061: INFO - instanciate a class
2022-04-21 12:09:26,062: DEBUG - instance: [1, 2, 3]
2022-04-21 12:09:26,062: WARNING - conduct addition
2022-04-21 12:09:26,062: CRITICAL - b: [34, 5, 6]
2022-04-21 12:09:26,062: INFO - results: [1, 2, 3, 34, 5, 6]