import logging
from logging.handlers import TimedRotatingFileHandler
class TimedRotatingLogger:
def __init__(self, name, log_dir, level=logging.INFO):
self.logger = logging.getLogger(name)
self.logger.setLevel(level)
file_handler = TimedRotatingFileHandler(
f"{log_dir}/{name}.log", when="midnight", interval=1, backupCount=5)
file_handler.suffix = "%Y-%m-%d.log"
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
self.logger.addHandler(file_handler)
self.logger.addHandler(console_handler)
def get_logger(self):
return self.logger
log_dir = '/work/code/随手demo'
logger_wrapper = TimedRotatingLogger('MyApp', log_dir)
logger = logger_wrapper.get_logger()
logger.info('This is a test log message.')
- when=“midnight” 参数指定了切换文件的时间,表示在午夜时分切换日志文件。
- interval=1 参数配合 when 参数使用,表示每隔1天(即每天)切换一次。
- backupCount=5 参数指定了保留日志文件的最大数量。在这个例子中,超过5个旧的日志文件会被删除。