A rotating file handler that compresses rotated files with gzip. Checks file size only periodically to improve performance.
| 55 | |
| 56 | |
| 57 | class GzipRotatingFileHandler(logging.handlers.RotatingFileHandler): |
| 58 | """ |
| 59 | A rotating file handler that compresses rotated files with gzip. |
| 60 | Checks file size only periodically to improve performance. |
| 61 | """ |
| 62 | |
| 63 | def __init__(self, *args, **kwargs): |
| 64 | super().__init__(*args, **kwargs) |
| 65 | self._msg_count = 0 |
| 66 | self._check_interval = 1000 # Check size every 1000 messages |
| 67 | |
| 68 | def rotation_filename(self, default_name): |
| 69 | """ |
| 70 | Modify the rotated filename to include .gz extension |
| 71 | """ |
| 72 | return default_name + ".gz" |
| 73 | |
| 74 | def rotate(self, source, dest): |
| 75 | """ |
| 76 | Compress the source file and move it to the destination. |
| 77 | """ |
| 78 | import gzip |
| 79 | |
| 80 | with open(source, "rb") as f_in: |
| 81 | with gzip.open(dest, "wb") as f_out: |
| 82 | f_out.writelines(f_in) |
| 83 | os.remove(source) |
| 84 | |
| 85 | def emit(self, record): |
| 86 | """ |
| 87 | Emit a record, checking for rollover only periodically using modulo. |
| 88 | """ |
| 89 | self._msg_count += 1 |
| 90 | |
| 91 | # Only check for rollover periodically to save compute |
| 92 | if self._msg_count % self._check_interval == 0: |
| 93 | if self.shouldRollover(record): |
| 94 | self.doRollover() |
| 95 | |
| 96 | # Continue with normal emit process |
| 97 | super().emit(record) |
no outgoing calls
no test coverage detected
searching dependent graphs…