很多程式都有記錄日誌的需求,並且日誌中包含的資訊即有正常的程式訪問日誌,還可能有錯誤、警告等資訊輸出,python的logging模組提供了標準的日誌介面,你可以通過它儲存各種格式的日誌,logging的日誌可以分為 debug、info、warning、error、critical 5個層級,下面我們看一下怎麼用
模組初識:
#logging初識 import logging logging.warning("user [James] attempted wrong password more than 3 times")logging.critical("server is down") # WARNING:root:user [James] attempted wrong password more than 3 times# CRITICAL:root:server is down
上面的代碼是最簡單的方式,括弧裡的內容為列印的資訊,logging.後的方法為日誌的層級,下面看看logging五個層級的詳細資料
如果想把日誌寫到檔案裡,也很簡單:
#日誌列印到檔案中 import logging logging.basicConfig(filename="example.log",level=logging.INFO, format="%(asctime)s %(message)s", datefmt="%m/%d/%Y %H:%M:%S [%A]") # H 24小時格式 I 12小時格式 A 周幾完整 a 周幾簡寫 p AM/PM logging.debug("This message should go to the log file")logging.info("So should this")logging.warning("And this ,too")
logging.basicConfig裡定義了輸入檔案路徑,輸入日誌資訊的層級,輸入的格式,格式可自訂;執行完代碼後example.log檔案會產生資訊如下:
10/31/2016 17:16:17 [Monday] So should this10/31/2016 17:16:17 [Monday] And this ,too
其中下面這句中的level=loggin.INFO意思是,把日誌紀錄層級設定為INFO,也就是說,只有比日誌是INFO或比INFO層級更高的日誌才會被紀錄到檔案裡,在這個例子, 第一條日誌是不會被紀錄的,如果希望紀錄debug的日誌,那把記錄層級改成DEBUG就行了
如果想同時把log列印在螢幕和檔案日誌裡,就需要瞭解一點複雜的知識了:
The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.
Loggers expose the interface that application code directly uses.
Handlers send the log records (created by loggers) to the appropriate destination.
Filters provide a finer grained facility for determining which log records to output.
Formatters specify the layout of log records in the final output.
#!/usr/bin/env python# -*- coding:utf-8 -*-#-Author-Lian import logging #建立loggerlogger = logging.getLogger("test_log") #建立logger對象 括弧內容隨便寫logger.setLevel(logging.INFO) #全域記錄層級 ch = logging.StreamHandler() #日誌列印到螢幕上ch.setLevel(logging.DEBUG) #指定ch日誌列印層級 fh = logging.FileHandler("access.log") #日誌存進檔案fh.setLevel(logging.WARNING) #指定fh日誌輸入層級 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") #定義日誌格式,可寫多個 #添加日誌格式到ch,fhch.setFormatter(formatter)fh.setFormatter(formatter) #添加ch,fh到logger中logger.addHandler(ch)logger.addHandler(fh) logger.debug('debug message')logger.info('info message')logger.warn('warn message')logger.error('error message')logger.critical('critical message')
全域記錄層級為整個程式的底線,局部記錄層級要想列印則不能比這個層級再低了
螢幕列印資訊
2016-10-31 17:23:42,988 - test_log - INFO - info message2016-10-31 17:23:42,988 - test_log - WARNING - warn message2016-10-31 17:23:42,988 - test_log - ERROR - error message2016-10-31 17:23:42,988 - test_log - CRITICAL - critical message
access.log:
2016-10-31 17:02:06,223 - test_log - WARNING - warn message2016-10-31 17:02:06,224 - test_log - ERROR - error message2016-10-31 17:02:06,224 - test_log - CRITICAL - critical message
日誌所有的格式:
重要的幾個格式:%(lineno)d 輸出列印日誌程式碼 ,%(process)d輸出列印日誌的進程ID ,%(thread)d輸出列印日誌的線程ID