python之-- logging模組

來源:互聯網
上載者:User

標籤:rem   port   ogg   filter   pre   code   move   proc   odi   

logging模組
功能:提供了標準的日誌介面,可以通過它儲存各種格式的日誌。
日誌5個層級分:debug(),info(),warning(),error(),critical()

logging.basicConfig函數各參數:
filename: 指定記錄檔名
filemode: 和file函數意義相同,指定記錄檔的開啟模式,‘w‘或‘a‘
format: 指定輸出的格式和內容,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: 列印日誌資訊
datefmt: 指定時間格式,同time.strftime()
level: 設定記錄層級,預設為logging.WARNING
stream: 指定將日誌的輸出資料流,可以指定輸出到sys.stderr,sys.stdout或者檔案,預設輸出到sys.stderr,當stream和filename同時指定時,stream被忽略

簡單樣本:5種日誌列印和順序
import logging
logging.debug(‘mess‘)
logging.info(‘mess‘)
logging.warning(‘user warnning log info‘)
logging.error(‘error‘)
logging.critical(‘server is down‘)
輸出critical的日誌如下:
CRITICAL:root:server is down
舉例:日誌記錄到檔案中
1 import logging2 #開啟記錄記錄檔並設定日誌寫入層級為info以上,設定記錄檔格式,開頭是時間,然後是日誌資訊3 logging.basicConfig(filename=‘example.log‘,4                     level=logging.INFO,5                     format=‘%(asctime)s %(levelname)s %(message)s‘,6                     datefmt=‘%m%d%Y %I:%M:%S %p‘)7 logging.info(‘mess‘)8 logging.warning(‘warning‘)
View Code
logging模組記錄日誌涉及4個類:
1:logger提供了應用程式可以直接使用的介面
2:handler將(logger建立的)日誌記錄發送到合適的目的輸出。
3:filter提供了細度裝置來決定輸出哪條日誌記錄
4:formatter決定日誌記錄的最終輸出格式。
另:logging 有2種方式可以切割日誌(根據時間 或者 根據大小 )
logger:每個程式在輸出資訊之前都要獲得一個logger,logger通常對應了程式的模組名。如:
LOG = logging.getLogger(‘access.log‘)
而核心模組可以這樣:
LOG = logging.getLogger(‘chat.kernel‘)
Logger.setLevel(lel):指定最低的記錄層級,低於lel的層級將被忽略。debug為最低,critical為最高。
Logger.addFilter(filt),Logger.removeFilter(filt):添加或刪除指定的filter
Logger.addHandler(hdlr),Logger.removeHandler(hdlr):添加或刪除指定的handler
Logger.debug(),Logger.Info(),Logger.Warning(),Logger.error(),Logger.critical() 為可以設定的記錄層級。

handler:負責把資訊發送到指定的目的地,如:控制台,檔案,網路或者編寫自己的handler。通過addHandler()添加多個handler
Handler.setLevel(lel):指定被處理的資訊層級,低於lel層級的被忽略。
Handler.setFormatter():給一個handler選擇一個格式。
Handler.addFilter(filt),Handler.removeFilter(filt):新增/刪除一個filter對象。
以下為常用的handler:
1:logging.StreamHandler:就是螢幕輸出
2:logging.FileHandler:輸出到檔案
3:logging.handlers.RotatingFileHandler:可以管理檔案大小,當達到指定大小後,會自動對當前檔案改名。改為:檔案名稱.1,.2,.3這樣
格式為:RotatingFileHandler(filename[,mode[,maxBytes[,backupCount]]])
參數:maxBytes 是檔案大小,0為無限大。backupCount:保留的備份檔案個數。
4:logging.handlers.TimeRotatingFileHandler:按照時間切割日誌
格式為:TimeRotatingFileHandler(filename,[,when[,interval[,backupCount]]])
參數:interval 時間間隔
when 是個字串,時間間隔的單位有(S秒,M分,H小時,D天,W星期,midnight每天淩晨)
日誌基本流程圖

 


舉例:實現日誌的螢幕和檔案輸出
 1 import logging 2 #自訂日誌名字test-log 3 logger = logging.getLogger(‘test-log‘) 4 #設定最低記錄層級DEBUG 5 logger.setLevel(logging.DEBUG) 6  7 #添加一個handler到螢幕輸出 8 ch = logging.StreamHandler() 9 #螢幕輸出自訂層級為WARNING10 ch.setLevel(logging.WARNING)11 12 #在添加一個handler輸出到檔案13 fh = logging.FileHandler(‘access.log‘,encoding=‘utf-8‘)14 fh.setLevel(logging.ERROR)15 16 # 在定義日誌輸出的格式(這個定義為到檔案格式)17 fh_formatter = logging.Formatter(‘%(asctime)s%(process)d %(filename)s - %(levelname)s - %(message)s‘)18 # 這個定義為螢幕列印格式19 ch_formatter = logging.Formatter(‘%(asctime)s, - %(name)s - %(levelname)s - %(message)s‘)20 21 #接下來將自訂的日誌格式和handler關聯起來22 #關聯檔案handler23 fh.setFormatter(fh_formatter)24 #關聯螢幕handler25 ch.setFormatter(ch_formatter)26 27 #最後將定義好的handler關聯到logger,日誌通過logger輸出28 logger.addHandler(fh)29 logger.addHandler(ch)30 31 #到現在,就可以做輸出日誌進行測試32 logger.debug(‘debug message‘)33 logger.info(‘info message‘)34 logger.warning(‘warning message‘)35 logger.error(‘error message‘)36 logger.critical(‘critical message‘)
View Code
舉例:按照檔案大小或者時間切割日誌
 1 import logging 2 from logging import handlers 3 logger = logging.getLogger(__name__) 4 log_file = ‘logname.log‘ 5 #按照檔案大小切割日誌 6 # fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3,encoding=‘utf-8‘) 7 #按照檔案時間切割日誌,這裡的 ‘S‘ 表示秒 8 # fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3,encoding=‘utf-8‘) 9 10 formatter = logging.Formatter(‘%(asctime)s %(module)s %(message)s‘)11 fh.setFormatter(formatter)12 logger.addHandler(fh)
View Code

 

python之-- logging模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.