-
-
Save j178/7d5b6a7bf77233caf6c3ef530f00709f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import time | |
from datetime import datetime | |
from logging.handlers import BaseRotatingHandler | |
class DailyRotatingFileHandler(BaseRotatingHandler): | |
def __init__(self): | |
filename = self.current_log_file() | |
super().__init__(filename, 'a') | |
# 做个缓存,提升一下日志的速率 | |
self.last_check = None | |
def current_log_file(self, create_dir=False): | |
date = datetime.now().strftime('%Y%m%d') | |
return date + '.log' | |
def shouldRollover(self, record): | |
now = time.monotonic() | |
# 60s 内只检查一次 | |
if self.last_check is None or now - self.last_check > 60: | |
self.last_check = now | |
log_file = self.current_log_file() | |
if os.path.isfile(log_file): | |
return False | |
else: | |
return True | |
return False | |
def doRollover(self): | |
if self.stream: | |
self.stream.close() | |
self.stream = None | |
filename = self.current_log_file(create_dir=True) | |
self.baseFilename = filename | |
if not self.delay: | |
self.stream = self._open() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment