From 93054b2f57ccf24b36f012da89bfdfeab6c50833 Mon Sep 17 00:00:00 2001 From: GeoffreyCoulaud Date: Sun, 27 Aug 2023 14:10:31 +0200 Subject: [PATCH] Handle log rotation errors with corrupted files --- src/logging/session_file_handler.py | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/src/logging/session_file_handler.py b/src/logging/session_file_handler.py index a6f46b3..d207e29 100644 --- a/src/logging/session_file_handler.py +++ b/src/logging/session_file_handler.py @@ -89,18 +89,24 @@ class SessionFileHandler(StreamHandler): # If uncompressed, compress if not path.name.endswith(".xz"): + try: + with open(path, "r", encoding="utf-8") as original_file: + original_data = original_file.read() + except UnicodeDecodeError: + # If the file is corrupted, throw it away + path.unlink() + return + + # Compress the file compressed_path = path.with_suffix(path.suffix + ".xz") - with ( - lzma.open( - compressed_path, - "wt", - format=FORMAT_XZ, - preset=PRESET_DEFAULT, - encoding="utf-8", - ) as lzma_file, - open(path, "r", encoding="utf-8") as original_file, - ): - lzma_file.write(original_file.read()) + with lzma.open( + compressed_path, + "wt", + format=FORMAT_XZ, + preset=PRESET_DEFAULT, + encoding="utf-8", + ) as lzma_file: + lzma_file.write(original_data) path.unlink() path = compressed_path