Skip to content
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

add example on how to add correlation_id in uvicorn access log #77

Merged
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,70 @@ priority_settings = {
}
```

# Integration with [Uvicorn](https://github.com/encode/uvicorn)
[Uvicorn](https://github.com/encode/uvicorn) is one of the ASGI servers
used to run a [FastAPI](https://fastapi.tiangolo.com/deployment/manually/) application.
nesies marked this conversation as resolved.
Show resolved Hide resolved

```
import logging
import os
import asgi_correlation_id
from fastapi import \
APIRouter, \
FastAPI
import uvicorn
from uvicorn.config import LOGGING_CONFIG


def configure_logging():
"""
configure logging with correlation_id
"""
console_handler = logging.StreamHandler()
console_handler.addFilter(
asgi_correlation_id.CorrelationIdFilter())
logging.basicConfig(
handlers=[console_handler],
level=getattr(
logging,
os.environ.get("LOGLEVEL", "DEBUG")),
format="%(asctime)s"
" %(levelname)s"
" %(correlation_id)s"
" log"
" %(filename)s:%(funcName)s:%(lineno)d"
" %(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")
result = True
return result


app.include_router(router)


if __name__ == "__main__":
# add correlation_id in uvicorn access_log
LOGGING_CONFIG["handlers"]["access"]["filters"] = [
asgi_correlation_id.CorrelationIdFilter()]
LOGGING_CONFIG["formatters"]["access"]["fmt"] = \
"%(asctime)s %(levelname)s %(correlation_id)s" \
" access %(client_addr)s - %(request_line)s %(status_code)s"
uvicorn.run(
"test:app",
port=8080,
log_level=os.environ.get("LOGLEVEL", "DEBUG").lower())
nesies marked this conversation as resolved.
Show resolved Hide resolved
```

# Extensions

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