Python的logging模組提供了通用的日誌系統,可以方便第三方模組或者是應用使用,下面這篇文章主要給大家介紹了關於python中logging庫使用的一些知識總結,文中給出了詳細的範例程式碼,需要的朋友可以參考借鑒,下面來一起看看吧。
前言
最近因為工作的需要,在寫一些python腳本,總是使用print來列印訊息感覺很low,所以抽空研究了一下python的logging庫,來優雅的來列印和記錄日誌,下面話不多說了,來一起看看詳細的介紹吧。
一、簡單的將日誌印到螢幕:
import logging logging.debug('This is debug message') #debug logging.info('This is info message') #info logging.warning('This is warning message') #warn
螢幕上列印:WARNING:root:This is warning message
預設情況下,會列印WARNING層級的日誌
DEBUG:詳細資訊,調試資訊。
INFO:確認一切如預期運作。
WARNING:表示發生了一些意外,或在不久的將來會發生問題(如『磁碟滿了』)。軟體還是在正常工作。
ERROR:由於更嚴重的問題,軟體已經不能執行一些功能了。
CRITICAL:嚴重錯誤,表示軟體已無法繼續運作了。
二、透過basicConfig函數來對日誌的輸入格式和方法進行配置
##
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')以上程式碼不會在螢幕上列印日誌,而是會在目前目錄產生test.log的日誌文件,日誌被印在日誌檔案中:
- # #logging.basicConfig函數各參數: ##filename: 指定日誌檔案名稱
- filemode: 和file函數意義相同,指定日誌檔案的開啟模式,'w'或'a'
%(levelno)s: 打印日志级别的数值 %(levelname)s: 打印日志级别名称 %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0] %(filename)s: 打印当前执行程序名 %(funcName)s: 打印日志的当前函数 %(lineno)d: 打印日志的当前行号 %(asctime)s: 打印日志的时间 %(thread)d: 打印线程ID %(threadName)s: 打印线程名称 %(process)d: 打印进程ID %(message)s: 打印日志信息
datefmt: 指定時間格式,同time.strftime()- level: 設定日誌等級,預設為logging.WARNING
stream: 指定將日誌的輸出流,可以指定輸出到sys.stderr,sys.stdout或文件,預設輸出到sys.stderr,當stream和filename同時指定時,stream被忽略
三、同時將日誌輸出到螢幕和日誌檔案
#定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象 console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console)
插入以上程式碼就可以同時在螢幕上列印出日誌
#畫面上列印:
root : INFO This is info message
root : WARNING This is warning message
檔案中列印:
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名称,应用程序通过 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初始化函数参数 [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 函式名
- ##%(levelname) s 等級名稱
- %(lineno)d 行號
- #%(module)s 模組名稱
-
- %(name)s 日誌模組名稱
- %(process)d 進程id
- %(processName)s 行程名稱
- %(thread)d 執行緒id
測試設定檔#
from logging.config import fileConfig fileConfig('logger.conf') logger=logging.getLogger('infoLogger') logger.info('test1') logger_error=logging.getLogger('warnhandler') logger_error.warn('test5')#####總結###### ###
以上是python中關於logging函式庫的使用總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表sandnumpyArraysInpythonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,with withOverHeadeBheadaroundAroundaround64byty64-bitsysysysysysysysysyssyssyssyssysssyssys2)

toensurepythonscriptsbehavecorrectlyacrycrosdevelvermations,分期和生產,USETHESTERTATE:1)Environment varriablesForsimplesettings,2)configurationfilesfilesForcomPlexSetups,3)dynamiCofforComplexSetups,dynamiqualloadingForaptaptibality.eachmethodoffersuniquebeneiquebeneqeniquebenefitsandrefitsandrequiresandrequiresandrequiresca

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Atom編輯器mac版下載
最受歡迎的的開源編輯器

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中