|
| 1 | +""" |
| 2 | +This module provides a logging configuration setup with structlog, including |
| 3 | +support for safe log rotation and multiprocessing. |
| 4 | +""" |
| 5 | + |
| 6 | +import logging |
| 7 | +import logging.handlers |
| 8 | +import os |
| 9 | +import threading |
| 10 | +from collections import deque |
| 11 | +from datetime import datetime |
| 12 | +from multiprocessing import Lock, Process, Queue |
| 13 | +from queue import Empty |
| 14 | + |
| 15 | +import structlog |
| 16 | +from pythonjsonlogger import jsonlogger |
| 17 | + |
| 18 | +rotation_lock = Lock() |
| 19 | + |
| 20 | +class SafeRotatingFileHandler(logging.handlers.RotatingFileHandler): |
| 21 | + """A rotating file handler that safely handles log file rotation.""" |
| 22 | + def __init__(self, *args, **kwargs): |
| 23 | + super().__init__(*args, **kwargs) |
| 24 | + self.process_name = os.getpid() # Get the process ID |
| 25 | + |
| 26 | + def doRollover(self): |
| 27 | + """Perform the log file rollover.""" |
| 28 | + with rotation_lock: |
| 29 | + if self.stream: |
| 30 | + self.stream.close() |
| 31 | + self.stream = None |
| 32 | + |
| 33 | + dfn = self.rotation_filename(f"{self.baseFilename}.{self.process_name}.{self.backupCount}") |
| 34 | + if os.path.exists(dfn): |
| 35 | + os.remove(dfn) |
| 36 | + self.rotate(self.baseFilename, dfn) |
| 37 | + |
| 38 | + if not self.delay: |
| 39 | + self.stream = self._open() |
| 40 | + |
| 41 | +class QueueHandler(logging.Handler): |
| 42 | + """This is a logging handler which sends events to a queue. It can be used |
| 43 | + from different processes to send logs to a single log file. |
| 44 | + """ |
| 45 | + def __init__(self, log_queue): |
| 46 | + super().__init__() |
| 47 | + self.log_queue = log_queue |
| 48 | + |
| 49 | + def emit(self, record): |
| 50 | + try: |
| 51 | + self.log_queue.put_nowait(record) |
| 52 | + except Exception as e: |
| 53 | + print(f"Error emitting log record: {e}") |
| 54 | + |
| 55 | +class QueueListener: |
| 56 | + """This is a listener which receives log events from the queue and processes |
| 57 | + them. It should be run in a separate process. |
| 58 | + """ |
| 59 | + def __init__(self, log_queue, handlers): |
| 60 | + self.log_queue = log_queue |
| 61 | + self.handlers = handlers |
| 62 | + self.stop_event = threading.Event() |
| 63 | + |
| 64 | + def start(self): |
| 65 | + """Start the queue listener.""" |
| 66 | + while not self.stop_event.is_set(): |
| 67 | + try: |
| 68 | + record = self.log_queue.get(timeout=0.05) |
| 69 | + self.handle(record) |
| 70 | + except Empty: |
| 71 | + continue |
| 72 | + |
| 73 | + def handle(self, record): |
| 74 | + """Handle a log record.""" |
| 75 | + for handler in self.handlers: |
| 76 | + handler.handle(record) |
| 77 | + |
| 78 | + def stop(self): |
| 79 | + """Stop the queue listener.""" |
| 80 | + self.stop_event.set() |
| 81 | + |
| 82 | +class CachingRotatingFileHandler(logging.handlers.RotatingFileHandler): |
| 83 | + """A rotating file handler with caching capabilities.""" |
| 84 | + def __init__(self, *args, **kwargs): |
| 85 | + super().__init__(*args, **kwargs) |
| 86 | + self.cache = deque(maxlen=1000) |
| 87 | + |
| 88 | + def emit(self, record): |
| 89 | + """Emit a record.""" |
| 90 | + try: |
| 91 | + self.cache.append(record) |
| 92 | + except Exception as e: |
| 93 | + print(f"Error caching log record: {e}") |
| 94 | + |
| 95 | + def flush_cache(self): |
| 96 | + """Flush the cache.""" |
| 97 | + while self.cache: |
| 98 | + record = self.cache.popleft() |
| 99 | + super().emit(record) |
| 100 | + |
| 101 | +def configure_logging( |
| 102 | + logging_directory: str = 'log', |
| 103 | + log_name: str = 'log', |
| 104 | + logging_level: str = 'INFO', |
| 105 | + log_rotation: int = 100, # Size in MB |
| 106 | + log_retention: int = 10, |
| 107 | + multiprocess: bool = False |
| 108 | +): |
| 109 | + """Configure logging with rotating file handlers.""" |
| 110 | + if not os.path.exists(logging_directory): |
| 111 | + os.makedirs(logging_directory) |
| 112 | + |
| 113 | + timestamp = datetime.now().strftime("%Y%m%d%H%M%S") |
| 114 | + log_name = f"{log_name}_{timestamp}.json" |
| 115 | + log_path = os.path.join(logging_directory, log_name) |
| 116 | + max_bytes = log_rotation * 1024 * 1024 |
| 117 | + |
| 118 | + cache_rotating_handler = CachingRotatingFileHandler( |
| 119 | + log_path, |
| 120 | + maxBytes=max_bytes, |
| 121 | + backupCount=log_retention |
| 122 | + ) |
| 123 | + safe_rotating_file_handler = SafeRotatingFileHandler( |
| 124 | + filename=log_path, |
| 125 | + maxBytes=max_bytes, |
| 126 | + backupCount=log_retention |
| 127 | + ) |
| 128 | + formatter = jsonlogger.JsonFormatter() |
| 129 | + cache_rotating_handler.setFormatter(formatter) |
| 130 | + safe_rotating_file_handler.setFormatter(formatter) |
| 131 | + |
| 132 | + handlers = [cache_rotating_handler, safe_rotating_file_handler] |
| 133 | + |
| 134 | + listener_process, listener_instance = None, None |
| 135 | + |
| 136 | + if multiprocess: |
| 137 | + log_queue = Queue() |
| 138 | + queue_handler = QueueHandler(log_queue) |
| 139 | + handlers = [queue_handler] |
| 140 | + listener_instance = QueueListener(log_queue, [cache_rotating_handler, safe_rotating_file_handler]) |
| 141 | + listener_process = Process(target=listener_instance.start) |
| 142 | + listener_process.start() |
| 143 | + |
| 144 | + logging.basicConfig( |
| 145 | + level=logging_level, |
| 146 | + handlers=handlers |
| 147 | + ) |
| 148 | + |
| 149 | + structlog.configure( |
| 150 | + processors=[ |
| 151 | + structlog.processors.TimeStamper(fmt="iso", utc=True), |
| 152 | + structlog.processors.StackInfoRenderer(), |
| 153 | + structlog.processors.format_exc_info, |
| 154 | + structlog.processors.JSONRenderer() |
| 155 | + ], |
| 156 | + context_class=dict, |
| 157 | + logger_factory=structlog.stdlib.LoggerFactory(), |
| 158 | + wrapper_class=structlog.stdlib.BoundLogger, |
| 159 | + cache_logger_on_first_use=True, |
| 160 | + ) |
| 161 | + |
| 162 | + cache_rotating_handler.flush_cache() |
| 163 | + |
| 164 | + return listener_instance, listener_process |
| 165 | + |
| 166 | +# Example usage |
| 167 | +if __name__ == "__main__": |
| 168 | + listener_instance, listener_process = configure_logging( |
| 169 | + logging_directory='log', |
| 170 | + log_name='log', |
| 171 | + logging_level='INFO', |
| 172 | + log_rotation=100, # Size in MB |
| 173 | + log_retention=10, |
| 174 | + multiprocess=True |
| 175 | + ) |
| 176 | + |
| 177 | + logger = structlog.get_logger() |
| 178 | + logger.info("Logging configured with SafeRotatingFileHandler") |
0 commit comments