Rotating-logger
日志檔案太大,一般不容易使用。現在的日志系統一般都提供了友善的日志回繞分片。一般有按照檔案大小、記錄時間長度來對日志檔案分片。
在python logging中,提供了這2種分片方式。
- 按照檔案大小分片
這種方式使用的Handler是RotatingFileHandler;
class RotatingFileHandler(BaseRotatingHandler):
"""
Handler for logging to a set of files, which switches from one file
to the next when the current file reaches a certain size.
"""
def __init__(self, filename, mode='a', maxBytes=, backupCount=, encoding=None, delay=):
下面看看使用方式:
rlogger = logging.getLogger("loggingtest2")
rfh = RotatingFileHandler("log/rtest.log", maxBytes=,backupCount=)
formatter = logging.Formatter('%(name)-12s %(asctime)s.%(msecs)03d %(levelname)-8s %(message)s', datefmt='%Y-%m-%d,%H:%M:%S')
rfh.setFormatter(formatter)
rlogger.addHandler(rfh)
完整示例:
import sys,time
import logging
from logging.handlers import RotatingFileHandler,TimedRotatingFileHandler
rlogger = logging.getLogger("loggingtest2")
rfh = RotatingFileHandler("log/rtest.log", maxBytes=,backupCount=)
formatter = logging.Formatter('%(name)-12s %(asctime)s.%(msecs)03d %(levelname)-8s %(message)s', datefmt='%Y-%m-%d,%H:%M:%S')
rfh.setFormatter(formatter)
rlogger.addHandler(rfh)
rlogger.setLevel(level = logging.INFO)
i =
while i<:
rlogger.info("this is a %s %i.......","info",i)
rlogger.warning("this is a %s %i........", "warning",i)
i=i+
執行時,會在log下生成rtest.log,以及分片的3個backup檔案rtest.log.0, rtest.log.1, rtest.log.2
- 按照時間長度分片
這裡使用的是TimedRotatingFileHandler。
定義如下:
class TimedRotatingFileHandler(BaseRotatingHandler):
"""
Handler for logging to a file, rotating the log file at certain timed
intervals.
If backupCount is > 0, when rollover is done, no more than backupCount
files are kept - the oldest ones are deleted.
"""
def __init__(self, filename, when='h', interval=, backupCount=, encoding=None, delay=False, utc=False):
使用方式:
formatter = logging.Formatter('%(name)-12s %(asctime)s.%(msecs)03d %(levelname)-8s %(message)s', datefmt='%Y-%m-%d,%H:%M:%S')
trlogger = logging.getLogger()
trfh = TimedRotatingFileHandler("log/tr_test.log",when="S",interval=,backupCount=)
trfh.setFormatter(formatter)
trlogger.addHandler(trfh)
完整示例:
import sys,time
import logging
from logging.handlers import RotatingFileHandler,TimedRotatingFileHandler
formatter = logging.Formatter('%(name)-12s %(asctime)s.%(msecs)03d %(levelname)-8s %(message)s', datefmt='%Y-%m-%d,%H:%M:%S')
trlogger = logging.getLogger()
trfh = TimedRotatingFileHandler("log/tr_test.log",when="S",interval=,backupCount=)
trfh.setFormatter(formatter)
trlogger.addHandler(trfh)
trlogger.setLevel(level = logging.INFO)
i=
while i < :
trlogger.info("this is a %s .......","info")
trlogger.warning("this is a %s........", "warning")
time.sleep(.)
i=i+