Skip to content
This repository was archived by the owner on Jan 16, 2026. It is now read-only.

Commit 11b9b81

Browse files
committed
Implement daily rotating log file handler to manage log files by date
1 parent 6fd8596 commit 11b9b81

1 file changed

Lines changed: 18 additions & 9 deletions

File tree

main.py

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,24 @@
3939
if not os.path.exists(f"{FOLDER_LOCATION}/logs"):
4040
os.makedirs(f"{FOLDER_LOCATION}/logs")
4141

42-
logFile = f"{FOLDER_LOCATION}/logs/{datetime.now().strftime("%Y-%B-%d-%A")}.log"
43-
logHandler = RotatingFileHandler(
44-
logFile,
45-
mode="a",
46-
maxBytes=1024**2 * 1024, # 1 gb
47-
backupCount=2,
48-
encoding=None,
49-
delay=0,
50-
)
42+
43+
class DailyRotatingFileHandler(logging.FileHandler):
44+
def __init__(self, logs_dir):
45+
self.logs_dir = logs_dir
46+
self.current_date = datetime.now().strftime("%Y-%B-%d-%A")
47+
self.base_filename = os.path.join(self.logs_dir, f"{self.current_date}.log")
48+
super().__init__(self.base_filename, mode="a", encoding="utf-8")
49+
50+
def emit(self, record):
51+
new_date = datetime.now().strftime("%Y-%B-%d-%A")
52+
if new_date != self.current_date:
53+
self.current_date = new_date
54+
self.baseFilename = os.path.join(self.logs_dir, f"{self.current_date}.log")
55+
self.stream.close()
56+
self.stream = self._open()
57+
super().emit(record)
58+
59+
logHandler = DailyRotatingFileHandler(f"{FOLDER_LOCATION}/logs")
5160

5261
logHandler.setFormatter(
5362
logging.Formatter(

0 commit comments

Comments
 (0)