2017-09-25 107 views
0

我使用以下代碼來限制一個日誌文件(例如最小)的大小:Python 3的記錄器與RotatingFileHandler excedes maxBytes限制

import logging 
from logging.handlers import RotatingFileHandler 

# Set up logfile and message logging. 
logger = logging.getLogger("Logger") 
logger.setLevel(logging.ERROR) 
# Create the rotating file handler. Limit the size to 1000000Bytes ~ 1MB . 
handler = RotatingFileHandler("test.log", mode='a', maxBytes=1000000, encoding=None, delay=0) 
handler.setLevel(logging.ERROR) 
# Create a formatter. 
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
# Add handler and formatter. 
handler.setFormatter(formatter) 
logger.addHandler(handler) 

for l in range(1000): 
    logger.error("test" * 1000) 

然而文件大小excedes 1MB的限制和不斷記錄。我沒有看到我做錯了什麼。有沒有辦法選擇不同的參數來正確限制我的日誌文件的大小?

回答

0

好吧,看來我發現,解決我的問題解決方法:

import logging 
from logging.handlers import RotatingFileHandler 

# Set up logfile and message logging. 
logger = logging.getLogger("Logger") 
logger.setLevel(logging.ERROR) 
# Create the rotating file handler. Limit the size to 1000000Bytes ~ 1MB . 
handler = RotatingFileHandler("test.log", mode='a', maxBytes=1000000, backupCount=1, encoding='utf-8', delay=0) 
handler.setLevel(logging.ERROR) 
# Create a formatter. 
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
# Add handler and formatter. 
handler.setFormatter(formatter) 
logger.addHandler(handler) 

for l in range(1000): 
    logger.error("test" * 1000) 

我只是錯過了BACKUPCOUNT = 1個參數。然而,這會創建兩個文件test.log和test.log.1(正確文件旋轉似乎需要2個文件)。不是完美的解決方案,因爲我只想要一個文件,但對我來說效果很好。