question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How can I implement a Correlation ID middleware?

See original GitHub issue

It’s common practice in my company to trace log messages related to a unique request with a common UUID between messages. How could I implement these?

I have had a look in Starlette middleware docs but I have no idea how I can add an extra field for logging that has same value for log lines in the same request without some kind of global object.

Has someone done something along these lines in Python?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:5
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

6reactions
tomwojcikcommented, Dec 28, 2019

@mths0x5f @cetanu I needed something like this so I made a package.

https://github.com/tomwojcik/starlette-context

I basically packaged what you wrote in here + tested it myself in my small project. Seems to be working. All feedback welcome.

6reactions
mths0x5fcommented, Jul 20, 2019

This was indeed related and I just implemented the way was expecting to! Thank you, @dmontagu

middlewares.py


from contextvars import ContextVar
from uuid import uuid4

from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request

CORRELATION_ID_CTX_KEY = 'correlation_id'
REQUEST_ID_CTX_KEY = 'request_id'

_correlation_id_ctx_var: ContextVar[str] = ContextVar(CORRELATION_ID_CTX_KEY, default=None)
_request_id_ctx_var: ContextVar[str] = ContextVar(REQUEST_ID_CTX_KEY, default=None)


def get_correlation_id() -> str:
    return _correlation_id_ctx_var.get()


def get_request_id() -> str:
    return _request_id_ctx_var.get()


class RequestContextLogMiddleware(BaseHTTPMiddleware):

    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
        correlation_id = _correlation_id_ctx_var.set(request.headers.get('X-Correlation-ID', str(uuid4())))
        request_id = _request_id_ctx_var.set(str(uuid4()))

        response = await call_next(request)
        response.headers['X-Correlation-ID'] = get_correlation_id()
        response.headers['X-Request-ID'] = get_request_id()

        _correlation_id_ctx_var.reset(correlation_id)
        _request_id_ctx_var.reset(request_id)

        return response

logging.py


import logging

from app.middlewares import get_request_id, get_correlation_id
from app.settings import DEBUG


class AppFilter(logging.Filter):
    def filter(self, record):
        record.correlation_id = get_correlation_id()
        record.request_id = get_request_id()
        return True


def setup_logging():
    logger = logging.getLogger()
    syslog = logging.StreamHandler()
    syslog.addFilter(AppFilter())

    formatter = logging.Formatter('%(asctime)s %(process)s %(request_id)s %(correlation_id)s '
                                  '%(levelname)s %(name)s %(message)s')

    syslog.setFormatter(formatter)
    logger.setLevel(logging.DEBUG if DEBUG else logging.WARN)
    logger.addHandler(syslog)

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to use correlation IDs in ASP.NET Core MVC - InfoWorld
Correlation IDs are unique identifiers that enable you to correlate several micro tasks to a single macro action. Ensuring that each response ...
Read more >
ASP.NET Core Correlation IDs - Steve Gordon - Code with Steve
A correlation ID is simply a unique identifier that is passed through the entire request flow and crucially is passed between the services....
Read more >
ASP.NET Correlation ID - Mark Gossa
First of all, we need a CorrelationIdGenerator service which can generate or save an ASP.NET Correlation ID (depending on whether the client ...
Read more >
NET 6 - Web API Correlation Id - DEV Community ‍ ‍
A Correlation ID is a unique identifier value that is attached to requests and messages that allow reference to a particular transaction or ......
Read more >
correlation ID - GitHub
Correlations IDs are used in distributed applications to trace requests across multiple services. This library and package provides a lightweight correlation ID ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found