python logging日誌模組

2022-02-24 10:46:54 字數 1961 閱讀 6837

1.匯入模組

>>> import logging

2.五種日誌級別

#輸出時預設只顯示警告級別以上的資訊,可以使用basicconfig的level引數更改

>>> logging.basicconfig(level=logging.debug)

... logging.debug('除錯')

... logging.info('資訊')

... logging.warning('警告')

... logging.error('錯誤')

... logging.critical('崩潰')

debug:root:除錯

info:root:資訊

warning:root:警告

error:root:錯誤

critical:root:崩潰

3.baseconfig()可選引數

filename:跟檔名,日誌將記錄在檔案內,指定之後就不會在控制台顯示

filemode:檔案開啟方式,預設為'a'

format:指定日誌記錄格式

datefmt:指定日期時間格式。

level:設定顯示的日誌級別

4.日誌記錄格式

%(name)s 哪個使用者

%(levelno)s 數字形式的日誌級別

%(levelname)s 文字形式的日誌級別

%(filename)s 呼叫函式所在檔名

%(module)s 呼叫日誌輸出函式的模組名

%(lineno)d 呼叫函式所在的行

%(asctime)s 字串形式的當前時間。

%(message)s使用者輸出的訊息

示例logging.basicconfig(level=logging.debug,

format='%(asctime)s %(filename)s line:%(lineno)d [%(levelname)s] %(message)s',

datefmt='%y-%m-%d %h:%m:%s')

logging.error('111')

2019-09-17 13:51:33 測試專用.py line:15 [error] 111

5.在控制台和檔案中同時輸出日誌

#匯入模組

import logging

#建立日誌檔案助手和螢幕顯示檔案助手

filehandler = logging.filehandler('python.log',encoding='utf-8')

streamhandler = logging.streamhandler()

#指定日誌輸出格式,可以指定多個,繫結時可以分別繫結

format = logging.formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

#將日誌格式繫結到助手

filehandler.setformatter(format)

streamhandler.setformatter(format)

#建立乙個logger物件

logger = logging.getlogger()

#將兩個助手新增到logger物件中

logger.addhandler(filehandler)

logger.addhandler(streamhandler)

#設定日誌顯示級別

logger.setlevel(logging.debug)

#filehandler.setlevel(logging.debug) 可以單獨設定級別

#streamhandler.setlevel(logging.error)

#輸出日誌就可以在檔案和控制台中同時顯示了

logger.error('casadasdasd')

Python logging日誌模組

1.日誌的級別 日誌一共分成5個等級,從低到高分別是 1 debug 2.info 3.warning 4.error 5.critical說明 這5個等級,也分別對應5種打日誌的方法 debug info warning error critical。預設的是 warning,當在warning或...

python logging日誌模組

logging模組是python的乙個標準庫模組,由標準庫模組提供日誌記錄api的關鍵好處是所有python模組都可以使用這個日誌記錄功能。所以,你的應用日誌可以將你自己的日誌資訊與來自第三方模組的資訊整合起來。1.日誌級別 logging模組預設定義了以下幾個日誌等級,開發應用程式或部署開發環境時...

python logging日誌設定

log等級,輸出格式,輸出檔名,檔案讀寫模式 logging.basicconfig level logging.debug,format asctime s filename s line lineno d levelname s message s filename log.txt filemo...