Skip to content

Instantly share code, notes, and snippets.

@j178
Created August 26, 2020 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j178/7d5b6a7bf77233caf6c3ef530f00709f to your computer and use it in GitHub Desktop.
Save j178/7d5b6a7bf77233caf6c3ef530f00709f to your computer and use it in GitHub Desktop.
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