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 - 备份保留的数目,默认不限制

示例

  1. import logging
  2. from logging.handlers import TimedRotatingFileHandler
  3. logger = logging.getLogger('SQD')
  4. logger.setLevel(logging.DEBUG)
  5. formatter = logging.Formatter(
  6. fmt='[%(asctime)s %(levelname)s %(filename)s:%(lineno)d] %(message)s',
  7. datefmt='%Y%m%d %H:%M:%S')
  8. file_hdlr = TimedRotatingFileHandler('log/out.log',
  9. when='s',
  10. backupCount=3,
  11. interval=1)
  12. file_hdlr.setFormatter(formatter)
  13. logger.addHandler(file_hdlr)
  14. logger.debug('debug message')
  15. logger.info('info message')
  16. logger.warn('warn message')

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

  1. # ...
  2. file_hdlr.suffix = '%Y%m%d-%H%M%S'
  3. # ...

image.png