python中用logging實現日誌滾動和過期日誌刪除
用python中的logging庫實現日誌滾動和過期日誌刪除。
logging庫提供了兩個可以用於日誌滾動的class(可以參考https://docs.python.org/2/library/logging.handlers.html),一個是RotatingFileHandler,它主要是根據日誌檔案的大小進行滾動,另一個是TimeRotatingFileHandler,它主要是根據時間進行滾動。在實際應用中,我們通常根據時間進行滾動,因此,本文中主要介紹TimeRotaingFileHandler的使用方法(RotatingFileHandler一樣)。程式碼示例如下:
#!/usr/bin/env python
#_*_coding:utf-8_*_
# vim : set expandtab ts=4 sw=4 sts=4 tw=100 :
import logging
import time
import re
from logging.handlers import TimedRotatingFileHandler
from logging.handlers import RotatingFileHandler
def main():
#日誌列印格式
log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s'
formatter = logging.Formatter(log_fmt)
#建立TimedRotatingFileHandler物件
log_file_handler = TimedRotatingFileHandler(filename="ds_update", when="M", interval=2, backupCount=2)
#log_file_handler.suffix = "%Y-%m-%d_%H-%M.log"
#log_file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$")
log_file_handler.setFormatter(formatter)
logging.basicConfig(level=logging.INFO)
log = logging.getLogger()
log.addHandler(log_file_handler)
#迴圈列印日誌
log_content = "test log"
count = 0
while count < 30:
log.error(log_content)
time.sleep(20)
count = count + 1
log.removeHandler(log_file_handler)
if __name__ == "__main__":
main()
- filename:日誌檔名的prefix;
- when:是一個字串,用於描述滾動週期的基本單位,字串的值及意義如下:
“S”: Seconds
“M”: Minutes
“H”: Hours
“D”: Days
“W”: Week day (0=Monday)
“midnight”: Roll over at midnight - interval: 滾動週期,單位有when指定,比如:when=’D’,interval=1,表示每天產生一個日誌檔案;
- backupCount: 表示日誌檔案的保留個數;
除了上述引數之外,TimedRotatingFileHandler還有兩個比較重要的成員變數,它們分別是suffix和extMatch。suffix是指日誌檔名的字尾,suffix中通常帶有格式化的時間字串,filename和suffix由“.”連線構成檔名(例如:filename=“runtime”, suffix=“%Y-%m-%d.log”,生成的檔名為runtime.2015-07-06.log)。extMatch是一個編譯好的正則表示式,用於匹配日誌檔名的字尾,它必須和suffix是匹配的,如果suffix和extMatch匹配不上的話,過期的日誌是不會被刪除的。比如,suffix=“%Y-%m-%d.log”, extMatch的只應該是re.compile(r”^\d{4}-\d{2}-\d{2}.log$”)。預設情況下,在TimedRotatingFileHandler物件初始化時,suffxi和extMatch會根據when的值進行初始化:
‘S’: suffix=”%Y-%m-%d_%H-%M-%S”, extMatch=r”\^d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}”;
‘M’:suffix=”%Y-%m-%d_%H-%M”,extMatch=r”^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}”;
‘H’:suffix=”%Y-%m-%d_%H”,extMatch=r”^\d{4}-\d{2}-\d{2}_\d{2}”;
‘D’:suffxi=”%Y-%m-%d”,extMatch=r”^\d{4}-\d{2}-\d{2}”;
‘MIDNIGHT’:”%Y-%m-%d”,extMatch=r”^\d{4}-\d{2}-\d{2}”;
‘W’:”%Y-%m-%d”,extMatch=r”^\d{4}-\d{2}-\d{2}”;
如果對日誌檔名沒有特殊要求的話,可以不用設定suffix和extMatch,如果需要,一定要讓它們匹配上。