From f2ef1a2a0479ccd57bad69b3314516a0148ff764 Mon Sep 17 00:00:00 2001 From: Matthieu Baerts Date: Wed, 22 Jul 2026 16:59:11 +0200 Subject: [PATCH] logger: rotate log at startup Before this modification, the log files were truncated at startup: the last log messages were then lost in case of restart, e.g. a service failed, restarted because the crashed seemed to be caused by a transient error, then ... arf, too late to understand why. Now, the log files, if any and not empty, are rotated at startup. Another solution could be to modify _log_open_init() to open the log files with 'a+' to avoid the truncation. It seems cleaner to do a rotation. The drawback is that it can create many small files in case of frequent restarts, but that shouldn't be that frequent. Signed-off-by: Matthieu Baerts --- core/logger.py | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/core/logger.py b/core/logger.py index 166b9645..766dc5fb 100644 --- a/core/logger.py +++ b/core/logger.py @@ -78,6 +78,17 @@ def log(self, header, data): self.end_sec() self._log_flush() + def _rotate_log(self): + # copy the data in to a compressed file now + name = self._path + '-' + datetime.datetime.now().isoformat() + '.xz' + + with open(self._path, "rb") as f: + with lzma.open(name, "w") as zf: + data = f.read() + while data: + zf.write(data) + data = f.read() + def _maybe_close(self): if self._level: return @@ -90,21 +101,16 @@ def _maybe_close(self): self._log_file.close() self._log_file = None - # copy the data in to a compressed file now - name = self._path + '-' + datetime.datetime.now().isoformat() + '.xz' - - with open(self._path, "rb") as f: - with lzma.open(name, "w") as zf: - data = f.read() - while data: - zf.write(data) - data = f.read() + self._rotate_log(self) # truncate the main log by re-opening self._log_file = open(self._path, "w+") self._log_open() def _log_open_init(self): + if os.path.isfile(self._path) and os.path.getsize(self._path) > 0: + self._rotate_log(self) + self._log_file = open(self._path, "w+") def _log_open(self):