Skip to content

Commit bb274ab

Browse files
committed
Minor modifications to isolate new log file creation logic and to handle the case that someone manually deletes log files
1 parent 6342c69 commit bb274ab

File tree

2 files changed

+26
-18
lines changed

2 files changed

+26
-18
lines changed

application/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
from werkzeug.serving import WSGIRequestHandler
2828

2929
global logger
30-
os.makedirs('logs', exist_ok=True)
3130

3231
try:
3332
with open('log_config.yaml') as config_file:

application/log_handlers/handlers.py

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,29 @@ def _generate_log_filename(self) -> Path:
102102

103103
return file_path
104104

105+
def _open_new_log_file(self) -> None:
106+
"""
107+
Generate a new log filename, open the file for writing, and switch the handler's stream.
108+
109+
This method updates `self.current_log_file`, opens a new stream in append-binary mode,
110+
and reinitializes the handler to use the new stream. It should be called when the
111+
current log file is deleted or after rotation.
112+
"""
113+
new_log_file = self._generate_log_filename()
114+
115+
try:
116+
new_stream = open(new_log_file, "ab")
117+
except Exception as e:
118+
raise RuntimeError(f"Failed to open new log file {new_log_file}: {e}")
119+
120+
self.acquire()
121+
try:
122+
self.stream = new_stream
123+
self.init(new_stream)
124+
self.current_log_file = new_log_file
125+
finally:
126+
self.release()
127+
105128
def _should_rotate(self) -> bool:
106129
"""
107130
Check if the current file exceeds the maximum size.
@@ -133,23 +156,7 @@ def _rotate(self) -> None:
133156
finally:
134157
self.ostream.close()
135158

136-
# Generate a new log filename (same UUID, new timestamp)
137-
new_log_file = self._generate_log_filename()
138-
139-
# Initialize the new stream
140-
try:
141-
new_stream = open(new_log_file, "ab")
142-
except Exception as e:
143-
raise RuntimeError(f"Failed to open new log file {new_log_file}: {e}")
144-
145-
self.acquire()
146-
try:
147-
self.stream = new_stream
148-
self.init(new_stream)
149-
finally:
150-
self.release()
151-
152-
# Remove old backups
159+
self._open_new_log_file()
153160
self._remove_old_backups()
154161

155162
def _remove_old_backups(self) -> None:
@@ -178,4 +185,6 @@ def _write(self, loglevel: int, msg: str) -> None:
178185
"""
179186
if self._should_rotate():
180187
self._rotate()
188+
elif not os.path.exists(self.current_log_file):
189+
self._open_new_log_file()
181190
super()._write(loglevel, msg)

0 commit comments

Comments
 (0)