TimedRotatingFileHandler
按时间自动切割日志文件
参数说明
logging.handlers.TimedRotatingFileHandler(filename, when=’h’, interval=1, backupCount=0, encoding=None, delay=False, utc=False)
when - interval的类型
| Value | Type of interval |
|---|---|
'S' |
Seconds |
'M' |
Minutes |
'H' |
Hours |
'D' |
Days |
'W0'-'W6' |
Weekday (0=Monday) |
'midnight' |
Roll over at midnight |
interval - 时间间隔
backupCount - 备份保留的数目,默认不限制
示例
import loggingfrom logging.handlers import TimedRotatingFileHandlerlogger = logging.getLogger('SQD')logger.setLevel(logging.DEBUG)formatter = logging.Formatter(fmt='[%(asctime)s %(levelname)s %(filename)s:%(lineno)d] %(message)s',datefmt='%Y%m%d %H:%M:%S')file_hdlr = TimedRotatingFileHandler('log/out.log',when='s',backupCount=3,interval=1)file_hdlr.setFormatter(formatter)logger.addHandler(file_hdlr)logger.debug('debug message')logger.info('info message')logger.warn('warn message')

后缀默认格式为%Y-%m-%d_%H-%M-%S ,可设置.suffix修改,但backupCount会失效
# ...file_hdlr.suffix = '%Y%m%d-%H%M%S'# ...

