python中l(wèi)ogging庫的使用總結(jié)
前言
最近因為工作的需要,在寫一些python腳本,總是使用print來打印信息感覺很low,所以抽空研究了一下python的logging庫,來優(yōu)雅的來打印和記錄日志,下面話不多說了,來一起看看詳細(xì)的介紹吧。
一、簡單的將日志打印到屏幕:
import logging logging.debug('This is debug message') #debug logging.info('This is info message') #info logging.warning('This is warning message') #warn
屏幕上打?。篧ARNING:root:This is warning message
默認(rèn)情況下,會打印WARNING級別的日志
- DEBUG:詳細(xì)信息,調(diào)試信息。
- INFO:確認(rèn)一切按預(yù)期運行。
- WARNING:表明發(fā)生了一些意外,或者不久的將來會發(fā)生問題(如‘磁盤滿了')。軟件還是在正常工作。
- ERROR:由于更嚴(yán)重的問題,軟件已不能執(zhí)行一些功能了。
- CRITICAL:嚴(yán)重錯誤,表明軟件已不能繼續(xù)運行了。
二、通過basicConfig函數(shù)來對日志的輸入格式和方法進(jìn)行配置
import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%Y-%m-%d %a %H:%M:%S', filename='test.log', filemode='w') logging.debug('This is debug message') logging.info('This is info message') logging.warning('This is warning message')
以上代碼不會在屏幕上打印日志,而是會在當(dāng)前目錄生成test.log的日志文件,日志被打印在日志文件中:
2017-10-16 Mon 10:05:17 testlogging.py[line:25] DEBUG This is debug message
2017-10-16 Mon 10:05:17 testlogging.py[line:26] INFO This is info message
2017-10-16 Mon 10:05:17 testlogging.py[line:27] WARNING This is warning message
- logging.basicConfig函數(shù)各參數(shù):
- filename: 指定日志文件名
- filemode: 和file函數(shù)意義相同,指定日志文件的打開模式,'w'或'a'
- format: 指定輸出的格式和內(nèi)容,format可以輸出很多有用信息,如上例所示:
%(levelno)s: 打印日志級別的數(shù)值 %(levelname)s: 打印日志級別名稱 %(pathname)s: 打印當(dāng)前執(zhí)行程序的路徑,其實就是sys.argv[0] %(filename)s: 打印當(dāng)前執(zhí)行程序名 %(funcName)s: 打印日志的當(dāng)前函數(shù) %(lineno)d: 打印日志的當(dāng)前行號 %(asctime)s: 打印日志的時間 %(thread)d: 打印線程ID %(threadName)s: 打印線程名稱 %(process)d: 打印進(jìn)程ID %(message)s: 打印日志信息
- datefmt: 指定時間格式,同time.strftime()
- level: 設(shè)置日志級別,默認(rèn)為logging.WARNING
- stream: 指定將日志的輸出流,可以指定輸出到sys.stderr,sys.stdout或者文件,默認(rèn)輸出到sys.stderr,當(dāng)stream和filename同時指定時,stream被忽略
三、同時將日志輸出到屏幕和日志文件
#定義一個StreamHandler,將INFO級別或更高的日志信息打印到標(biāo)準(zhǔn)錯誤,并將其添加到當(dāng)前的日志處理對象 console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console)
插入以上代碼就可以同時在屏幕上打印出日志
屏幕上打?。?br />
root : INFO This is info message
root : WARNING This is warning message
文件中打?。?br />
2017-10-16 Mon 10:20:07 testlogging.py[line:46] DEBUG This is debug message
2017-10-16 Mon 10:20:07 testlogging.py[line:47] INFO This is info message
2017-10-16 Mon 10:20:07 testlogging.py[line:48] WARNING This is warning message
四、通過配置文件配置日志
#logger.conf [loggers] #定義logger模塊,root是父類,必需存在的,其它的是自定義。 keys=root,infoLogger,warnlogger [logger_root] level=DEBUG #level 級別,級別有DEBUG、INFO、WARNING、ERROR、CRITICAL handlers=infohandler,warnhandler #handlers 處理類,可以有多個,用逗號分開 [logger_infoLogger] #[logger_xxxx] logger_模塊名稱 handlers=infohandler qualname=infoLogger #qualname logger名稱,應(yīng)用程序通過 logging.getLogger獲取。對于不能獲取的名稱,則記錄到root模塊。 propagate=0 #propagate 是否繼承父類的log信息,0:否 1:是 [logger_warnlogger] handlers=warnhandler qualname=warnlogger propagate=0 ############################################### #定義handler [handlers] keys=infohandler,warnhandler [handler_infohandler] class=StreamHandler #class handler類名 level=INFO #level 日志級別 formatter=form02 #formatter,下面定義的formatter args=(sys.stdout,) #args handler初始化函數(shù)參數(shù) [handler_warnhandler] class=FileHandler level=WARN formatter=form01 args=('logs/deploylog.log', 'a') ############################################### # 定義格式化輸出 [formatters] keys=form01,form02 [formatter_form01] format=%(message)s %(asctime)s datefmt=%Y-%m-%d %H:%M:%S [formatter_form02] format=%(asctime)s %(levelname)s %(message)s datefmt=%Y-%m-%d %H:%M:%S
日志格式
- %(asctime)s 年-月-日 時-分-秒,毫秒 2013-04-26 20:10:43,745
- %(filename)s 文件名,不含目錄
- %(pathname)s 目錄名,完整路徑
- %(funcName)s 函數(shù)名
- %(levelname)s 級別名
- %(lineno)d 行號
- %(module)s 模塊名
- %(message)s 消息體
- %(name)s 日志模塊名
- %(process)d 進(jìn)程id
- %(processName)s 進(jìn)程名
- %(thread)d 線程id
- %(threadName)s 線程名
測試配置文件
from logging.config import fileConfig fileConfig('logger.conf') logger=logging.getLogger('infoLogger') logger.info('test1') logger_error=logging.getLogger('warnhandler') logger_error.warn('test5')
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
- Python logging日志庫空間不足問題解決
- python GUI庫圖形界面開發(fā)之PyQt5中QWebEngineView內(nèi)嵌網(wǎng)頁與Python的數(shù)據(jù)交互傳參詳細(xì)方法實例
- python GUI庫圖形界面開發(fā)之PyQt5瀏覽器控件QWebEngineView詳細(xì)使用方法
- Python中l(wèi)ogging日志庫實例詳解
- 在Python中使用MongoEngine操作數(shù)據(jù)庫教程實例
- win系統(tǒng)下為Python3.5安裝flask-mongoengine 庫
- python logging類庫使用例子
- Python 分析Nginx訪問日志并保存到MySQL數(shù)據(jù)庫實例
- 聊聊python的gin庫的介紹和使用
相關(guān)文章
python中django框架通過正則搜索頁面上email地址的方法
這篇文章主要介紹了python中django框架通過正則搜索頁面上email地址的方法,涉及django框架及正則表達(dá)式的使用技巧,需要的朋友可以參考下2015-03-03python pandas實現(xiàn)excel轉(zhuǎn)為html格式的方法
今天小編就為大家分享一篇python pandas實現(xiàn)excel轉(zhuǎn)為html格式的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10使用Python將數(shù)組的元素導(dǎo)出到變量中(unpacking)
最近工作中遇到一個問題,需要利用Python將數(shù)組(list)或元組(tuple)中的元素導(dǎo)出到N個變量中,現(xiàn)在將我實現(xiàn)的方法分享給大家,有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-10-10Python基礎(chǔ)之hashlib模塊subprocess模塊logging模塊
這篇文章主要為大家介紹了Python基礎(chǔ)之hashlib模塊subprocess模塊logging模塊示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11