-
Notifications
You must be signed in to change notification settings - Fork 410
Correlation ID for Unified Request Tracking #1443
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
shoummu1
wants to merge
25
commits into
main
Choose a base branch
from
feat/correlation-id-logging
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
d0712be to
a17e408
Compare
dd94c98 to
cb9e60a
Compare
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
Signed-off-by: Shoumi <[email protected]>
7650197 to
f5d3932
Compare
Signed-off-by: Shoumi <[email protected]>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
π Summary
This PR delivers a comprehensive structured JSON logging pipeline that captures correlation IDs end-to-end (ingress middleware β services β persistence) while maintaining backward compatibility with legacy console/file logs. It introduces:
π Related Issues
#300
π§ Changes Made
Core Implementation
Correlation ID Infrastructure
mcpgateway/utils/correlation_id.py): ContextVar-based correlation ID storage for async-safe request tracking across the entire request lifecyclemcpgateway/middleware/correlation_id.py): HTTP middleware for X-Correlation-ID header extraction, validation, generation, and injection into responsesmcpgateway/services/logging_service.py): CorrelationIdJsonFormatter for automatic correlation ID injection into JSON logs with OpenTelemetry trace contextStructured Logging & Observability
mcpgateway/services/structured_logger.py): Central logging facade that persists to database (StructuredLogEntry) with enriched metadata (user, component, operation type, duration)mcpgateway/services/log_aggregator.py): Aggregates structured logs into PerformanceMetric windows with percentiles (p50/p95/p99) and error ratesmcpgateway/services/security_logger.py): Specialized logger for authentication attempts, suspicious activity, and threat scoringmcpgateway/services/audit_trail_service.py): CRUD operation tracking with change sets, data classification, and review flagsAPI & Admin UI
mcpgateway/routers/log_search.py): RESTful endpoints for log search, correlation tracing, security events, audit trails, and performance metricsmcpgateway/static/admin.js,mcpgateway/templates/admin.html): System Logs tab rebuilt with quick actions, correlation trace modal, unified timeline view, and dynamic filtersDatabase Schema
mcpgateway/alembic/versions/k5e6f7g8h9i0_add_structured_logging_tables.py): Creates 4 new tables:structured_log_entries: Comprehensive log storage with correlation IDs, user context, performance data, security indicatorsperformance_metrics: Time-windowed aggregations with percentile calculationssecurity_events: Threat analysis, failed attempt tracking, alert managementaudit_trails: CRUD tracking with change detection and compliance metadataβοΈ Configuration
New Settings in
config.py:Correlation ID Settings (4 new fields):
correlation_id_enabled: Enable/disable correlation ID tracking (default:True)correlation_id_header: Configurable header name (default:X-Correlation-ID)correlation_id_preserve: Preserve client-provided IDs (default:True)correlation_id_response_header: Echo correlation ID in responses (default:True)Structured Logging Settings (3 new fields):
structured_logging_enabled: Enable JSON logging with DB persistence (default:True)structured_logging_database_enabled: Persist logs to database (default:True)structured_logging_external_enabled: Send to external systems (default:False)Performance Tracking Settings (6 new fields):
performance_tracking_enabled: Enable performance metrics (default:True)performance_threshold_*_ms: Alert thresholds for database queries, tool invocations, resource reads, HTTP requestsperformance_degradation_multiplier: Alert threshold vs baseline (default:1.5)Security Logging Settings (4 new fields):
security_logging_enabled: Enable security event logging (default:True)security_failed_auth_threshold: Failed attempts before high severity (default:5)security_threat_score_alert: Threat score alert threshold (default:0.7)security_rate_limit_window_minutes: Rate limit check window (default:5)Metrics Aggregation Settings (4 new fields):
metrics_aggregation_enabled: Enable automatic log aggregation (default:True)metrics_aggregation_backfill_hours: Historical data to backfill on startup (default:6)metrics_aggregation_window_minutes: Aggregation window size (default:5)metrics_aggregation_auto_start: Auto-run aggregation loop (default:False)Log Search Settings (2 new fields):
log_search_max_results: Maximum results per query (default:1000)log_retention_days: Days to retain logs in database (default:30)Updated
.env.example:π Integration Points
Middleware Stack (
main.py):metrics_aggregation_auto_start=Truestructured_logging_enabled=TrueAuthentication & Security:
auth.py: Enhanced JWT validation with correlation ID contextmiddleware/auth_middleware.py: AuthContextMiddleware now logs successful/failed authentication attempts via SecurityLoggermiddleware/http_auth_middleware.py: Unified correlation ID usage across plugin auth hooksService Layer:
services/tool_service.py: Integrated correlation ID fallback chain and structured logging for tool invocationsservices/resource_service.py: Added user context and audit logging for resource operationsservices/prompt_service.py: Enhanced with structured logging and performance trackingservices/server_service.py: Integrated audit trails for server lifecycle eventsservices/gateway_service.py: Added correlation ID propagation for federated requestsservices/a2a_service.py: Added correlation ID and user context to agent invocationsObservability:
observability.py: Auto-inject correlation_id into OpenTelemetry spans asrequest.idattributemiddleware/request_logging_middleware.py: Gateway boundary logging (request_started/completed) with correlation IDs, user resolution, and duration trackingadmin.py: Plugin marketplace endpoints emit structured logs + audit trails for complianceπ New Files
mcpgateway/middleware/correlation_id.pyβ FastAPI middleware that extracts/preserves correlation IDs and injects them into responsesmcpgateway/utils/correlation_id.pyβ ContextVar utilities for generating, validating, and retrieving correlation IDs across async scopesmcpgateway/services/structured_logger.pyβ Central structured logging facade that writes to JSON, DB, and optional external sinksmcpgateway/services/log_aggregator.pyβ Aggregates StructuredLogEntry rows into PerformanceMetric windows and exposes helper APIsmcpgateway/services/security_logger.pyβ Specialized logger for auth/suspicious events, computing threat scores and security audit entriesmcpgateway/services/audit_trail_service.pyβ Shared audit trail writer that records CRUD/data-access operations with change trackingmcpgateway/routers/log_search.pyβ FastAPI router exposing/api/logs/search,/trace,/security-events,/audit-trails,/performance-metricsendpointsmcpgateway/alembic/versions/k5e6f7g8h9i0_add_structured_logging_tables.pyβ Migration that createsstructured_log_entries,performance_metrics,security_events, andaudit_trailstables plus supporting indexesExample Usage
Full Response:
x-correlation-id: 6930e1f1a8b84beb904e18594bbf15dd{"request_id": "6930e1f1a8b84beb904e18594bbf15dd", ...}Correlation trace in Admin UI: