python logging模塊


很多程序都有記錄日志的需求,並且日志包含的信息有正常的程序訪問日志還可能有錯誤,警告等信息輸出,python的logging模塊提供了標准的日志接口,可以通過它存儲各種格式的日志,日志級別等級:critical > error > warning > info > debug

看下各個日志級別代表什么意思:

 

日志打印到屏幕:

>>> import logging
>>> logging.debug('test debug')
>>> logging.info('test info')
>>> logging.warning('test warning')
WARNING:root:test warning
>>> logging.error('test error')
ERROR:root:test error
>>> logging.critical('test critical')
CRITICAL:root:test critical
>>> 

默認情況下只顯示了大於等於WARNING級別的日志。

配置日志級別,日志格式,輸出位置:

import logging
logging.basicConfig(filename='app.log',level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(message)s',datefmt='%Y-%m-%d')
logging.info('test info')
logging.debug('test debug')
logging.warning('test warning')
logging.error('test error')
logging.critical('test critical')

當前目錄下多了個app.log文件:

 

 在logging.basicConfig()函數中可通過具體參數來更改logging模塊默認行為,可用參數有

filename:用指定的文件名創建FiledHandler(后邊會具體講解handler的概念),這樣日志會被存儲在指定的文件中。
filemode:文件打開方式,在指定了filename時使用這個參數,默認值為“a”還可指定為“w”。
format:指定handler使用的日志顯示格式。 
datefmt:指定日期時間格式。 
level:設置rootlogger(后邊會講解具體概念)的日志級別 
stream:用指定的stream創建StreamHandler。可以指定輸出到sys.stderr,sys.stdout或者文件,默認為sys.stderr。若同時列出了filename和stream兩個參數,則stream參數會被忽略。
format參數中可能用到的格式化串: %(name)s Logger的名字 %(levelno)s 數字形式的日志級別 %(levelname)s 文本形式的日志級別 %(pathname)s 調用日志輸出函數的模塊的完整路徑名,可能沒有 %(filename)s 調用日志輸出函數的模塊的文件名 %(module)s 調用日志輸出函數的模塊名 %(funcName)s 調用日志輸出函數的函數名 %(lineno)d 調用日志輸出函數的語句所在的代碼行 %(created)f 當前時間,用UNIX標准的表示時間的浮 點數表示 %(relativeCreated)d 輸出日志信息時的,自Logger創建以 來的毫秒數 %(asctime)s 字符串形式的當前時間。默認格式是 “2003-07-08 16:49:45,896”。逗號后面的是毫秒 %(thread)d 線程ID。可能沒有 %(threadName)s 線程名。可能沒有 %(process)d 進程ID。可能沒有 %(message)s用戶輸出的消息
若要對logging進行更多靈活的控制,必須了解Logger,Handler,Formatter,Filter的概念:

logger提供了應用程序可以直接使用的接口;

handler將(logger創建的)日志記錄發送到合適的目的輸出;

filter提供了細度設備來決定輸出哪條日志記錄;

formatter決定日志記錄的最終輸出格式。

屏幕輸出和文件輸出

import logging
logger = logging.getLogger() #定義對應的程序模塊名name,默認是root
#logger.setLevel(logging.DEBUG) #指定最低的日志級別
ch = logging.StreamHandler() #日志輸出到屏幕控制台
ch.setLevel(logging.WARNING) #設置日志等級
fh = logging.FileHandler('access.log')#向文件access.log輸出日志信息
fh.setLevel(logging.INFO) #設置輸出到文件最低日志級別
#create formatter
formatter = logging.Formatter('%(asctime)s %(name)s- %(levelname)s - %(message)s') #定義日志輸出格式
#add formatter to ch and fh
ch.setFormatter(formatter) #選擇一個格式
fh.setFormatter(formatter)
logger.addHandler(ch) #增加指定的handler
logger.addHandler(fh)
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')

控制台:

2019-12-30 23:25:24,047 root- WARNING - warn message
2019-12-30 23:25:24,047 root- ERROR - error message
2019-12-30 23:25:24,047 root- CRITICAL - critical message

當前文件access.log:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM