python模塊—log

  日誌是咱們排查問題的關鍵利器,寫好日誌記錄,當咱們發生問題時,能夠快速定位代碼範圍進行修改。Python有給咱們開發者們提供好的日誌模塊python

1.日誌模塊:loggingide

例子:函數

import loggingspa

logging.debug("This is debug message")線程

logging.info("This is info message")debug

logging.warning("This is warning message")日誌

logging.error("This is error message")orm

logging.critical("This is critical message")對象


結果:進程

WARNING:root:This is warning message

ERROR:root:This is error message

CRITICAL:root:This is critical message


說明:級別由上往下,依次升高,默認爲info,因此只打印級別更高的日誌信息


2.經過logging.basicConfig函數,提高日誌級別至debug

函數說明:

level:        設置日誌級別,默認爲logging.WARNING

filename:      指定日誌文件名。

filemode:      和file函數意義相同,指定日誌文件的打開模式,'w'或'a'


format:       指定輸出的格式和內容,format能夠輸出不少有用信息:

%(levelname)s:  打印日誌級別名稱

%(filename)s:   打印當前執行程序名 

%(funcName)s:   打印日誌的當前函數

%(lineno)d:    打印日誌的當前行號

%(asctime)s:    打印日誌的時間

%(thread)d:     打印線程ID

%(process)d:    打印進程ID

%(message)s:    打印日誌信息


datefmt:       指定時間格式,同time.strftime()

stream:       指定將日誌的輸出流,能夠指定輸出到sys.stderr,sys.stdout或者文件,默認輸出到sys.stderr,當stream和filename同時指定時,stream被忽略

logging.getLogger([name]): 建立一個日誌對象


例子:

import logging

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt=' %Y/%m/%d %H:%M:%S', filename='mytest.log', filemode='w')

logger = logging.getLogger(__name__)

logging.debug("This is debug message")

logging.info("This is info message")

logging.warning("This is warning message")

logging.error("This is error message")

logging.critical("This is critical message")


結果:

目錄下產生一個名爲mytest.log文件,內容爲:

2017/10/24 16:30:23 a1.python.py[line:436] DEBUG This is debug message

2017/10/24 16:30:23 a1.python.py[line:437] INFO This is info message

2017/10/24 16:30:23 a1.python.py[line:438] WARNING This is warning message

2017/10/24 16:30:23 a1.python.py[line:439] ERROR This is error message

2017/10/24 16:30:23 a1.python.py[line:440] CRITICAL This is critical message


說明:返回一個logger實例,若是沒有指定name,返回root logger;只要name相同,返回的logger實例都是同一個並且只有一個,即name和logger實例是一一對應的。這意味着,無需把logger實例在各個模塊中傳遞。只要知道name,就能獲得同一個logger實例。

logging.getLogger(__name__) 在上述實例中__name__就指的是__main__

相關文章
相關標籤/搜索