Adds an unique identifiert to fastapi requests
Project description
sag_py_fastapi_request_id
This library provides a way to identify all log entries that belong to a single request.
What it does
- Provides a middleware to generate a random request id for every request
- Contains a logging filter that adds the request id as field to every log entry
How to use
Installation
pip install sag_py_fastapi_request_id
Add the middleware
Add this middleware so that the request ids are generated:
from sag_py_fastapi_request_id.request_context_middleware import RequestContextMiddleware
from fastapi import FastAPI
app = FastAPI(...)
app.add_middleware(RequestContextMiddleware)
Get the request id
The request id can be accessed over the context
from sag_py_fastapi_request_id.request_context import get_request_id as get_request_id_from_context
request_id = get_request_id_from_context()
This works in async calls but not in sub threads (without additional changes).
See:
- https://docs.python.org/3/library/contextvars.html
- https://kobybass.medium.com/python-contextvars-and-multithreading-faa33dbe953d
Add request id field to logging
It is possible to log the request id by adding a filter.
import logging
from sag_py_fastapi_request_id.request_context_logging_filter import RequestContextLoggingFilter
console_handler = logging.StreamHandler(sys.stdout)
console_handler.addFilter(RequestContextLoggingFilter())
The filter adds the field request_id if it has a value in the context.
How to publish
- Update the version in setup.py and commit your change
- Create a tag with the same version number
- Let github do the rest
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for sag-py-fastapi-request-id-0.1.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 069e3b89d65092d54a96b8b028069c2ffb4faee945ff743f52f687ba2ad46223 |
|
MD5 | 1fa835b946889bbe5c1dbd1527b82fe8 |
|
BLAKE2b-256 | 6e19dfe2b40cfb576add02cd0db39fc57d3537572ecaa3ac31fdcdcea6e43193 |
Close
Hashes for sag_py_fastapi_request_id-0.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3a30e12b377414b99d63d25de6d35c71d97e1d210be9f92ff9bd0414da75e4b9 |
|
MD5 | 0d9019a043ee59cafffd83400c52151d |
|
BLAKE2b-256 | c35e56632649f77c70b822d0aa2864c99772572c8062a6c1e68d31b8940250ff |