Python模塊-logging模塊

簡介

logging模塊用於輸出日誌信息,能夠按照不一樣日誌等級劃分反饋給用戶,默認以追加形式添加日誌信息函數

通常狀況下分的五種等級:學習

優先級 等級
1 debug()
2 info()
3 warning()
4 error()
5 critical()

logging.basicConfig()

logging配置信息,實現打印日誌的基礎配置信息this

logging配置參數

參數 釋義
filename 指定日誌文件名
filemode 和file函數意義相同,指定日誌文件的打開模式,'w'或'a'
format 指定輸出的格式和內容
datefmt 指定時間格式,同time.strftime()
level 設置日誌級別,默認爲logging.WARNING
stream 指定將日誌的輸出流,如:sys.stderr,sys.stdout或文件,默認sys.stderr,stream和filename同時指定,stream被忽略

format輸出格式

格式 釋義
%(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 打印日誌信息

示例

改變默認等級並輸出日誌內容線程

# -*- coding:utf8 -*-
import logging
logging.basicConfig(
    level = logging.DEBUG,          #變動默認等級
    filename = "logging.log",       #輸出日誌到文件
    format = "[%(lineno)d] %(asctime)s 【%(message)s】 " #定義格式,顯示行號、時間、日誌信息
)
logging.debug("this is debug")
logging.info("this is info")
logging.warning("this is warning")
logging.error("this is error")
logging.critical("this is critical")

logging.log內容debug

[8] 2018-04-05 16:15:34,486 【this is debug】 
[9] 2018-04-05 16:15:34,487 【this is info】 
[10] 2018-04-05 16:15:34,487 【this is warning】 
[11] 2018-04-05 16:15:34,487 【this is error】 
[12] 2018-04-05 16:15:34,487 【this is critical】

logging.getLogger()

logging對象日誌

參數 釋義
logging.getLogger() 建立對象
logger.setLevel() 定義等級
logging.Formatter() 定義格式
logging.FileHandler() 定義輸出文件信息
logging.StreamHandler() 定義屏幕打印信息
.setFormatter() 格式學習
.addHandler() 對象添加學習內容

使用示例code

# -*- coding:utf8 -*-
import logging

logger = logging.getLogger("root")          #定義用戶建立對象
logger.setLevel(logging.DEBUG)              #定義默認等級

format1 = logging.Formatter("[%(lineno)d] %(asctime)s 【%(message)s】 ")  #定義輸出格式1,用於文件輸出
format2 = logging.Formatter("%(asctime)s %(message)s ")                   #定義輸出格式2,用於屏幕輸出

a = logging.FileHandler("test.log")         #定義文件存儲位置和名稱
b = logging.StreamHandler()                 #定義屏幕打印信息

a.setFormatter(format1)                     #學習文件輸出格式
b.setFormatter(format2)                     #學習屏幕輸出格式

logger.addHandler(a)                        #學習文件存儲功能
logger.addHandler(b)                        #學習屏幕打印功能

logger.debug("this is debug")
logger.info("this is info")
logger.warning("this is warning")
logger.error("this is error")
logger.critical("this is critical")

屏幕輸出內容orm

2018-04-05 17:49:45,746 this is debug 
2018-04-05 17:49:45,746 this is info 
2018-04-05 17:49:45,746 this is warning 
2018-04-05 17:49:45,746 this is error 
2018-04-05 17:49:45,746 this is critical

文件輸出內容對象

[33] 2018-04-05 17:49:45,746 【this is debug】 
[34] 2018-04-05 17:49:45,746 【this is info】 
[35] 2018-04-05 17:49:45,746 【this is warning】 
[36] 2018-04-05 17:49:45,746 【this is error】 
[37] 2018-04-05 17:49:45,746 【this is critical】
相關文章
相關標籤/搜索