@@ -102,6 +102,29 @@ def _generate_log_filename(self) -> Path:
102
102
103
103
return file_path
104
104
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
+
105
128
def _should_rotate (self ) -> bool :
106
129
"""
107
130
Check if the current file exceeds the maximum size.
@@ -133,23 +156,7 @@ def _rotate(self) -> None:
133
156
finally :
134
157
self .ostream .close ()
135
158
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 ()
153
160
self ._remove_old_backups ()
154
161
155
162
def _remove_old_backups (self ) -> None :
@@ -178,4 +185,6 @@ def _write(self, loglevel: int, msg: str) -> None:
178
185
"""
179
186
if self ._should_rotate ():
180
187
self ._rotate ()
188
+ elif not os .path .exists (self .current_log_file ):
189
+ self ._open_new_log_file ()
181
190
super ()._write (loglevel , msg )
0 commit comments