From 10d85bb78b6a1c10ac582da5bed19b97037fe7f1 Mon Sep 17 00:00:00 2001 From: Phil Skentelbery Date: Fri, 28 Nov 2025 16:22:12 -0700 Subject: [PATCH] fix: Apply correlation filter to handlers for proper multi-logger support Fixes logging errors during app initialization and in background threads. The correlation_id filter must be applied to handlers (not just loggers) to ensure all log records have the correlation_id attribute before formatting occurs. Issue: Gunicorn workers were crashing due to missing correlation_id in logs from memory monitor and other non-request contexts. --- starpunk/__init__.py | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/starpunk/__init__.py b/starpunk/__init__.py index 051f695..b7b7c0b 100644 --- a/starpunk/__init__.py +++ b/starpunk/__init__.py @@ -65,16 +65,8 @@ def configure_logging(app): datefmt="%Y-%m-%d %H:%M:%S" ) - console_handler.setFormatter(formatter) - file_handler.setFormatter(formatter) - - # Remove existing handlers and add our configured handlers - app.logger.handlers.clear() - app.logger.addHandler(console_handler) - app.logger.addHandler(file_handler) - - # Add filter to inject correlation ID - # This filter will be added to ALL loggers to ensure consistency + # Add filter to inject correlation ID BEFORE setting formatters + # This filter must be applied to handlers to work with all loggers class CorrelationIdFilter(logging.Filter): def filter(self, record): # Get correlation ID from Flask's g object, or use fallback @@ -90,11 +82,21 @@ def configure_logging(app): record.correlation_id = 'init' return True - # Apply filter to Flask's app logger correlation_filter = CorrelationIdFilter() - app.logger.addFilter(correlation_filter) - # Also apply to the root logger to catch all logging calls + # Apply filter to handlers (not loggers) to ensure all log records have correlation_id + console_handler.addFilter(correlation_filter) + file_handler.addFilter(correlation_filter) + + console_handler.setFormatter(formatter) + file_handler.setFormatter(formatter) + + # Remove existing handlers and add our configured handlers + app.logger.handlers.clear() + app.logger.addHandler(console_handler) + app.logger.addHandler(file_handler) + + # Also apply filter to root logger for any other loggers root_logger = logging.getLogger() root_logger.addFilter(correlation_filter)