snok / asgi-correlation-id

Request ID propagation for ASGI apps
MIT License
369 stars 29 forks source link

Adding Correlation Id to Uvicorn #88

Open pedrorjbr opened 3 months ago

pedrorjbr commented 3 months ago

I am trying to add the correlation id to uvicorn, but the uvicorn logging seems the same, without correlation-id.

def configure_logging():
    dictConfig(
        {
            "version": 1,
            "disable_existing_loggers": False,
            "filters": {
                "correlation_id": {
                    "()": "asgi_correlation_id.CorrelationIdFilter",
                    "uuid_length": 32,
                    "default_value": "-",
                },
            },
            "formatters": {
                "console": {
                    "class": "logging.Formatter",
                    "datefmt": "%H:%M:%S",
                    "format": "%(levelname)s: \t  %(asctime)s %(name)s:%(lineno)d [%(correlation_id)s] %(message)s",
                },
            },
            "handlers": {
                "console": {
                    "class": "logging.StreamHandler",
                    "filters": ["correlation_id"],
                    "formatter": "console",
                },
            },
            "loggers": {
                # project
                "": {"handlers": ["console"], "level": "DEBUG", "propagate": True},
                # third-party packages
                # "httpx": {"handlers": ["console"], "level": "INFO"},
                # "databases": {"handlers": ["console"], "level": "WARNING"},
                # "asgi_correlation_id": {"handlers": ["console"], "level": "WARNING"},
            },
        }
    )

    LOGGING_CONFIG["handlers"]["access"]["filters"] = [CorrelationIdFilter()]
    LOGGING_CONFIG["formatters"]["access"][
        "fmt"
    ] = "%(levelname)s access [%(correlation_id)s] %(name)s %(message)s"

app = FastAPI(on_startup=[configure_logging])