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.
This commit is contained in:
@@ -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)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user