Skip to content

Commit

Permalink
Merge pull request #77 from nesies/add_example_add_correlation_id_to_…
Browse files Browse the repository at this point in the history
…uvicorn_access_log

Add example on how to add correlation_id in uvicorn access log
  • Loading branch information
sondrelg authored Dec 14, 2023
2 parents fc584d7 + f7f2918 commit 93e1ea1
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,47 @@ priority_settings = {
}
```

# Integration with [Uvicorn](https://github.com/encode/uvicorn)
To add a correlation ID to your [uvicorn](https://github.com/encode/uvicorn) logs, you'll need to add a log filter and change the log formatting. Here's an example of how to configure uvicorn, if you're running a [FastAPI](https://fastapi.tiangolo.com/deployment/manually/) app:

```
import logging
import os
import asgi_correlation_id
import uvicorn
from fastapi import APIRouter, FastAPI
from uvicorn.config import LOGGING_CONFIG
def configure_logging():
console_handler = logging.StreamHandler()
console_handler.addFilter(asgi_correlation_id.CorrelationIdFilter())
logging.basicConfig(
handlers=[console_handler],
format="%(levelname)s log [%(correlation_id)s] %(name)s %(message)s"
app = FastAPI(on_startup=[configure_logging])
app.add_middleware(asgi_correlation_id.CorrelationIdMiddleware)
router = APIRouter()
@router.get("/test")
async def test_get():
logger = logging.getLogger()
logger.info("test_get")
app.include_router(router)
if __name__ == "__main__":
LOGGING_CONFIG["handlers"]["access"]["filters"] = [asgi_correlation_id.CorrelationIdFilter()]
LOGGING_CONFIG["formatters"]["access"]["fmt"] = "%(levelname)s access [%(correlation_id)s] %(name)s %(message)s"
uvicorn.run("test:app", port=8080, log_level=os.environ.get("LOGLEVEL", "DEBUG").lower())
```

# Extensions

In addition to the middleware, we've added a couple of extensions for third-party packages.
Expand Down

0 comments on commit 93e1ea1

Please sign in to comment.