天天看點

python子產品 之 logging子產品logging子產品

logging子產品

寫在前面:

logging子產品是python用于輸出日志的子產品

logging子產品無法智能自己輸出對應的日志資訊,所有的日志資訊,都是由程式員自己寫好,然後通過logging子產品格式化輸出至檔案或者螢幕中

1.logging日志輸出的簡單配置

預設情況下,python的logging子產品将日志列印到标準輸出中(即螢幕上),且隻顯示大于等于WARNING級别的日志,這說明預設日志級别設定為WARNING(日志級别等級排序:CRITICAL > ERROR > WARNING > INFO > DEBUG)

預設的日志格式:

日志級别:logger名稱:使用者輸出資訊
           

例子:

import logging

logging.debug('--> 1 this is debug logs')
logging.info('-->2 this is info logs')
logging.warning('--> 3 this is warning logs')
logging.error('--> 4 this is error logs')
logging.critical('--> 5 this is critical logs')

'''---輸出---'''
# WARNING:root:--> 3 this is warning logs
# ERROR:root:--> 4 this is error logs
# CRITICAL:root:--> 5 this is critical logs
           

1.1 指定level輸出日志資訊

basicConfig(level = $level)

logging.basicConfig()

方法可通過其

level

的值來指定輸出的日志級别

import logging

logging.basicConfig(level=logging.DEBUG)    #自定義輸出DEBUG及以上級别的日志資訊

logging.debug('--> 1 this is debug logs')
logging.info('-->2 this is info logs')
logging.warning('--> 3 this is warning logs')
logging.error('--> 4 this is error logs')
logging.critical('--> 5 this is critical logs')

'''---輸出---'''
# DEBUG:root:--> 1 this is debug logs
# INFO:root:-->2 this is info logs
# WARNING:root:--> 3 this is warning logs
# ERROR:root:--> 4 this is error logs
# CRITICAL:root:--> 5 this is critical logs
           

1.2 将日志寫入指定檔案

FileHandler()

首先通過

logging.FileHandler

方法 定義日志寫入的檔案的路徑、寫入方式、編碼格式

其次在

logging.basicConfig()

方法中,通過

handlers

的值來指定日志寫入的檔案

注:可通過定義多個檔案并放到handlers的清單中,來實作日志輸出至多個檔案當中

import logging

fh = logging.FileHandler(filename='test.log',mode='a',encoding='utf-8') #定義fh檔案資訊
logging.basicConfig(level=logging.INFO,handlers=[fh])    #預設輸出INFO及以上級别的日志到fh檔案

logging.debug('--> 1 this is debug logs')
logging.info('-->2 this is info logs')
logging.warning('--> 3 this is warning logs')
logging.error('--> 4 this is error logs')
logging.critical('--> 5 this is critical logs')
           

執行結果:

在目前路徑下生成一個test.log檔案,且将INFO及以上級别的日志以utf8編碼追加寫入test.log檔案

python子產品 之 logging子產品logging子產品

1.3 日志既寫入檔案也輸出至螢幕

StreamHandler()

首先通過

logging.StreamHandler

方法 定義日志輸出至螢幕

其次在

logging.basicConfig()

方法中,通過

handlers

的值來指定日志寫入的檔案及輸出至螢幕

import logging

fh = logging.FileHandler(filename='test02.log',mode='a',encoding='utf-8') #定義fh檔案資訊
sh = logging.StreamHandler()    #定義日志輸出到螢幕
logging.basicConfig(level=logging.ERROR,handlers=[fh,sh])    #預設輸出INFO及以上級别的日志到fh及sh中

logging.debug('--> 1 this is debug logs')
logging.info('-->2 this is info logs')
logging.warning('--> 3 this is warning logs')
logging.error('--> 4 this is error logs')
logging.critical('--> 5 this is critical logs')
           

執行結果:

在本地生成test02.log檔案,并将ERROR及以上級别的日志以追加的方式寫入,同時在pycharm的調試平台輸出

python子產品 之 logging子產品logging子產品
python子產品 之 logging子產品logging子產品

2.logging日志格式化輸出的配置

2.1 輸出指定格式的日志到檔案/螢幕

basicConfig(format=$format)

logging.basicConfig()方法,可通過其

format

參數來定義輸出的日志的格式

import logging

fh = logging.FileHandler(filename='test03.log',mode='a',encoding='utf-8') #定義fh檔案資訊
logging.basicConfig(level=logging.ERROR,
                    handlers=[fh],
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s -%(lineno)d:  %(message)s'
                    )

logging.error('--> 4 this is error logs')
logging.critical('--> 5 this is critical logs')
           

執行結果:

在本地生成test03.log檔案,并将ERROR及其以上級别的日志以format定義的格式追加寫入test03.log檔案當中

python子產品 之 logging子產品logging子產品

如上圖輸出日志中,時間部分帶有毫秒,如何自定義日志中時間的格式?

2.2 自定義格式化日志中時間的格式

basicConfig(datefmt=$datefmt)

logging.basicConfig()方法,可通過其

datefmt

參數來規範format裡時間的格式(即

%(asctime)s

的格式)

import logging

fh = logging.FileHandler(filename='test04.log',mode='a',encoding='utf-8') #定義fh檔案資訊
logging.basicConfig(level=logging.ERROR,
                    handlers=[fh],
                    datefmt='%Y-%m-%d %H:%M:%S',    #定義format中指定的時間格式
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s -%(lineno)d:  %(message)s'
                    )

logging.error('--> 4 this is error logs')
logging.critical('--> 5 this is critical logs')
           

執行結果:

在本地生成test04.log檔案,并将ERROR及其以上級别的日志以format定義的格式追加寫入test04.log檔案當中(注意對比和test03.log日志的時間格式)

python子產品 之 logging子產品logging子產品

2.3 參數說明

logging.basicConfig()

logging.basicConfig()

函數中可通過具體參數來更改logging子產品預設行為

參數 參數說明
filename 用指定的檔案名建立FileHandler,這樣日志會被存儲在指定的檔案中
filemode 檔案打開方式,在指定了filename時使用這個參數,預設值位’a’還可以指定為’w’
format 指定handler使用的日志顯示格式
datefmt 指定日期時間格式
level 設定rootlogger的日志級别
stream 用指定的stream建立StreamHandler。可以指定輸出到sys.stderr,sys.stdout或者檔案(f=open(‘test.log’,’w’)),預設為sys.stderr。若同時列出了filename和stream兩個參數,則stream參數會被忽略

format

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 使用者輸出的消息

3.日志分割

from logging import handlers
           

logging

是一個包,而

handlers

是其中一個子產品,在

handlers

子產品中存在兩個方法:

RotatingFileHandler

TimedRotatingFileHandler

;前者是按照檔案大小對日志檔案進行分割,後者可通過時間對日志檔案進行分割

3.1 按照檔案大小分割

handlers.RotatingFileHandler()

RotatingFileHandler

方法可以根據日志檔案大小對日志進行分割,且可通過不同參數來限定每個日志檔案的大小及備份的檔案數量(預設以追加方式寫檔案)

常用參數說明:

參數 說明
maxBytes 日志檔案最大為多少開始進行分割(機關:位元組)
backupCount 日志備份當數量(滾動替換)數字越小日志越新,若不定義則都儲存
import time
import time
import logging
from logging import handlers
# 按照大小切,maxBytes代表每個日志檔案最大容量,backupCount代表備份對數量
sh = handlers.RotatingFileHandler('sizeLog.log',maxBytes=512,backupCount=5,encoding='utf-8')
logging.basicConfig(level=logging.ERROR,
                    handlers=[sh],
                    datefmt='%Y-%m-%d %H:%M:%S',    #定義format中指定的時間格式
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s -%(lineno)d:  %(message)s'
                    )
while True:
    logging.error('這是一個按照檔案大小切割日志檔案對測試,請看結果')
    time.sleep(0.3)
           

執行結果:

生成sizeLog.log檔案,且當檔案達到門檻值時,将其備份,最多存儲5個日志檔案

生成的日志檔案:

python子產品 之 logging子產品logging子產品

日志檔案内容:

python子產品 之 logging子產品logging子產品

3.2 按照時間分割

handlers.TimeRotatingFileHandler()

TimeRotatingFileHandler

方法可以按照時間(時分秒天等)對日志進行分割,并且可以定義需要儲存日志檔案的數量

常用參數說明

參數 說明
when 時間間隔的機關(s:秒;M:分;H:時;D:天;W:周)
interval 時間間隔
backupCount 日志備份當數量(滾動替換)數字越小日志越新,若不定義則都儲存
import time
import logging
from logging import handlers
# 按照時間切,when代表時間機關,interval代表時間間隔
th = handlers.TimedRotatingFileHandler('timeLog.log',when='s',interval=5,encoding='utf-8')
logging.basicConfig(level=logging.ERROR,
                    handlers=[th],
                    datefmt='%Y-%m-%d %H:%M:%S',    #定義format中指定的時間格式
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s -%(lineno)d:  %(message)s'
                    )
while True:
    logging.error('這是一個按照時間切割日志檔案的測試,請看結果')
    time.sleep(0.3)
           

執行結果:

生成timeLog.log檔案,且每5s進行分割及備份

生成的日志檔案:

python子產品 之 logging子產品logging子產品

日志檔案内容:

python子產品 之 logging子產品logging子產品