Skip to content

Conversation

@avirajsingh7
Copy link
Collaborator

@avirajsingh7 avirajsingh7 commented Jul 3, 2025

Summary

This PR enhances platform logging by including a trace_id (via correlation_id) in all log entries, improving request traceability across services.

Target issue is #251

The CorrelationIdMiddleware from the asgi-correlation-id package is used to automatically assign and manage a unique trace ID (also called a correlation ID) for each incoming HTTP request in a FastAPI (or any ASGI) application.

Incoming Request:

  • If the request has a X-Correlation-ID header, it uses that as the correlation_id.
  • Otherwise, it generates a new UUID4 and assigns it.

Storage:

  • It uses Python’s contextvars to store the ID per-request.
  • This means the correlation_id is automatically accessible anywhere in your code during that request's lifecycle—even in async code.

Logging:

  • You can inject the correlation_id into all log lines by attaching a custom log filter.

Checklist

Before submitting a pull request, please ensure that you mark these task.

  • Ran fastapi run --reload app/main.py or docker compose up in the repository root and test.
  • If you've fixed a bug or added code that is tested and has test cases.

Summary by CodeRabbit

  • New Features

    • Added support for correlation IDs in API requests, enabling improved request tracking and traceability.
    • All logs and traces now include a request identifier for easier debugging and monitoring.
  • Chores

    • Updated dependencies to include the correlation ID package.

@avirajsingh7 avirajsingh7 added the enhancement New feature or request label Jul 3, 2025
@avirajsingh7 avirajsingh7 moved this to In Progress in Dev Priorities Jul 3, 2025
@avirajsingh7 avirajsingh7 linked an issue Jul 3, 2025 that may be closed by this pull request
@avirajsingh7 avirajsingh7 self-assigned this Jul 3, 2025
@codecov
Copy link

codecov bot commented Jul 3, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

📢 Thoughts on this report? Let us know!

@coderabbitai
Copy link

coderabbitai bot commented Jul 12, 2025

Walkthrough

The changes integrate request correlation IDs throughout the backend. Middleware is added to propagate correlation IDs per request, logging is enhanced to include the correlation ID in each log entry, and traces now always record the request ID in their metadata. The required dependency is also added to the project configuration.

Changes

File(s) Change Summary
backend/app/core/langfuse/langfuse.py Ensures trace metadata always includes a "request_id" from the correlation ID, defaulting to "N/A".
backend/app/core/logger.py Adds a logging filter to inject correlation IDs into logs; updates log format to display them.
backend/app/main.py Adds ASGI Correlation ID middleware to propagate correlation IDs per request.
backend/pyproject.toml Adds "asgi-correlation-id" as a new dependency.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant FastAPI App
    participant CorrelationIdMiddleware
    participant Logger
    participant Langfuse

    Client->>FastAPI App: HTTP Request
    FastAPI App->>CorrelationIdMiddleware: Process request
    CorrelationIdMiddleware->>FastAPI App: Attach correlation ID to context
    FastAPI App->>Logger: Log event (includes correlation ID)
    FastAPI App->>Langfuse: start_trace(metadata)
    Langfuse->>Langfuse: Add request_id from correlation ID to metadata
    Langfuse->>Langfuse: Record trace with metadata
    FastAPI App-->>Client: HTTP Response
Loading

Poem

In tunnels of logs, a new thread appears,
Correlation IDs now banish our fears.
Each trace and each log, with a tag they reside,
So bunnies can follow the trails far and wide.
With middleware magic and filters so neat,
Our backend’s now hopping with order and beat! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1b6c7fa and fdf4362.

⛔ Files ignored due to path filters (1)
  • backend/uv.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • backend/app/core/langfuse/langfuse.py (2 hunks)
  • backend/app/core/logger.py (3 hunks)
  • backend/app/main.py (2 hunks)
  • backend/pyproject.toml (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: checks (3.11.7, 6)
🔇 Additional comments (8)
backend/pyproject.toml (1)

31-31: Dependency addition approved: asgi-correlation-id>=4.3.4

  • 4.3.4 is the latest release (Oct 17, 2024), adds Sentry integration and Python 3.12 support.
  • No publicly disclosed security vulnerabilities for version 4.3.4.
  • Correctly placed under main dependencies in backend/pyproject.toml (line 31).
backend/app/main.py (2)

4-4: LGTM: Proper import of CorrelationIdMiddleware.

The import follows the correct pattern for the asgi-correlation-id package.


26-26: LGTM: Middleware integration is correct.

The CorrelationIdMiddleware is properly added to the FastAPI application. The placement after the http_request_logger middleware ensures that correlation IDs are available for logging during request processing.

backend/app/core/logger.py (3)

4-4: LGTM: Proper import for correlation ID access.

The import correctly brings in the correlation_id function from asgi-correlation-id for accessing the current request's correlation ID.


13-15: LGTM: Log format updated to include correlation ID.

The logging format is properly updated to include the %(correlation_id)s placeholder, which will be populated by the CorrelationIdFilter.


34-34: LGTM: Filter applied to all log handlers.

The CorrelationIdFilter is correctly applied to both the console stream handler and the rotating file handler, ensuring correlation IDs appear in all log outputs.

Also applies to: 42-42

backend/app/core/langfuse/langfuse.py (2)

4-4: LGTM: Proper import for correlation ID access.

The import correctly brings in the correlation_id function for accessing the current request's correlation ID in trace metadata.


59-60: LGTM: Safe metadata handling with correlation ID injection.

The implementation correctly:

  • Initializes metadata to an empty dict if None is passed (avoiding mutation of caller's parameter)
  • Injects the correlation ID as "request_id" with appropriate fallback to "N/A"
  • Ensures every trace includes request traceability information

This complements the logging and middleware changes to provide end-to-end correlation ID tracking.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Collaborator

@vijay-T4D vijay-T4D left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved

@avirajsingh7 avirajsingh7 merged commit 690b452 into main Jul 14, 2025
3 checks passed
@avirajsingh7 avirajsingh7 deleted the enhc/logs_trace_id branch July 14, 2025 07:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request ready-for-review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add trace_id or user_id to Logs for Enhanced Traceability

3 participants