|
| 1 | +import gzip |
| 2 | +import bz2 |
| 3 | +import lzma |
| 4 | +import tempfile |
| 5 | +import logging |
| 6 | + |
| 7 | +logger = logging.getLogger(__name__) |
| 8 | + |
| 9 | +try: |
| 10 | + import brotli |
| 11 | + BROTLI_AVAILABLE = True |
| 12 | +except ImportError: |
| 13 | + BROTLI_AVAILABLE = False |
| 14 | + logger.warning("Brotli module not available. Brotli compression will not be supported.") |
| 15 | + |
| 16 | +class Compression: |
| 17 | + """ |
| 18 | + A class to handle compression of logs in different formats (gzip, bz2, lzma, brotli) using disk-based files. |
| 19 | + """ |
| 20 | + |
| 21 | + SUPPORTED_METHODS = ['gzip', 'bzip2', 'lzma', 'brotli'] |
| 22 | + COMPRESSION_CHUNK_SIZE = 1024 |
| 23 | + |
| 24 | + COMPRESSION_EXTENSIONS = { |
| 25 | + 'gzip': 'gz', |
| 26 | + 'bzip2': 'bz2', |
| 27 | + 'lzma': 'xz', |
| 28 | + 'brotli': 'br' |
| 29 | + } |
| 30 | + |
| 31 | + def __init__(self, method="gzip"): |
| 32 | + """ |
| 33 | + Initializes the compression method. |
| 34 | +
|
| 35 | + Parameters |
| 36 | + ---------- |
| 37 | + method : str |
| 38 | + The compression method to use. Default is 'gzip'. |
| 39 | +
|
| 40 | + Raises |
| 41 | + ------ |
| 42 | + ValueError |
| 43 | + If the compression method is not supported. |
| 44 | + """ |
| 45 | + if method not in self.SUPPORTED_METHODS: |
| 46 | + raise ValueError( |
| 47 | + f"Unsupported compression method: {method}. Supported methods are {', '.join(self.SUPPORTED_METHODS)}") |
| 48 | + self.method = method |
| 49 | + self._compression_handlers = { |
| 50 | + 'gzip': self._handle_streaming_compression(gzip.open), |
| 51 | + 'bzip2': self._handle_streaming_compression(bz2.BZ2File), |
| 52 | + 'lzma': self._handle_streaming_compression(lzma.open), |
| 53 | + 'brotli': self._handle_brotli_compression |
| 54 | + } |
| 55 | + |
| 56 | + def compress(self, input_file_path): |
| 57 | + """ |
| 58 | + Compresses the given input file and saves the compressed file on disk. |
| 59 | +
|
| 60 | + Parameters |
| 61 | + ---------- |
| 62 | + input_file_path : str |
| 63 | + The path to the file to compress. |
| 64 | +
|
| 65 | + Returns |
| 66 | + ------- |
| 67 | + str |
| 68 | + Path to the compressed file. |
| 69 | + """ |
| 70 | + # Create a temporary file for the compressed data |
| 71 | + with tempfile.NamedTemporaryFile(delete=False, suffix=f'.log.{self.method}') as temp_file: |
| 72 | + temp_compressed_file = temp_file.name |
| 73 | + |
| 74 | + try: |
| 75 | + # Get the appropriate compression handler and call it |
| 76 | + handler = self._compression_handlers[self.method] |
| 77 | + result = handler(input_file_path, temp_compressed_file) |
| 78 | + |
| 79 | + logger.info( |
| 80 | + f"Successfully compressed file to '{temp_compressed_file}' using {self.method} compression.") |
| 81 | + return result |
| 82 | + except Exception as e: |
| 83 | + logger.error(f"Error during compression: {e}") |
| 84 | + raise |
| 85 | + |
| 86 | + def get_extension(self): |
| 87 | + """ |
| 88 | + Returns the file extension for the current compression method. |
| 89 | +
|
| 90 | + Returns |
| 91 | + ------- |
| 92 | + str |
| 93 | + The file extension for the current compression method. |
| 94 | + """ |
| 95 | + return self.COMPRESSION_EXTENSIONS.get(self.method, self.method) |
| 96 | + |
| 97 | + def _handle_streaming_compression(self, open_func): |
| 98 | + """ |
| 99 | + Create a handler for streaming compression methods (gzip, bzip2, lzma). |
| 100 | +
|
| 101 | + Parameters |
| 102 | + ---------- |
| 103 | + open_func : callable |
| 104 | + The function to open a compressed file (e.g., gzip.open). |
| 105 | +
|
| 106 | + Returns |
| 107 | + ------- |
| 108 | + callable |
| 109 | + A function that handles the compression. |
| 110 | + """ |
| 111 | + |
| 112 | + def handler(input_file_path, output_file_path): |
| 113 | + with open(input_file_path, 'rb') as f_in: |
| 114 | + with open_func(output_file_path, 'wb') as f_out: |
| 115 | + while chunk := f_in.read(self.COMPRESSION_CHUNK_SIZE): |
| 116 | + f_out.write(chunk) |
| 117 | + return output_file_path |
| 118 | + |
| 119 | + return handler |
| 120 | + |
| 121 | + def _handle_brotli_compression(self, input_file_path, output_file_path): |
| 122 | + """Handle the brotli compression method.""" |
| 123 | + with open(input_file_path, 'rb') as f_in: |
| 124 | + compressed_data = brotli.compress(f_in.read()) |
| 125 | + with open(output_file_path, 'wb') as f_out: |
| 126 | + f_out.write(compressed_data) |
| 127 | + return output_file_path |
| 128 | + |
0 commit comments