# Request ID Middleware
**Request ID Middleware** is a Python library that provides middleware for Django
and FastAPI applications to generate and propagate request IDs across
incoming requests, enabling easier tracking in logs, Sentry,
and other observability tools.
## Features
- **Request ID Propagation**: Automatically generate or extract X-Request-ID headers and make them available throughout your application.
- **Django and FastAPI Support**: Middleware that works out-of-the-box with Django and FastAPI.
- **Sentry Integration**: Track request IDs in Sentry to trace issues by request.
- **Logging Support**: Inject request IDs into logs for better traceability across services.
## Installation
### Basic Installation (Core)
To install the core package without any framework dependencies:
```bash
pip install x-request-id-middleware
```
Or using **Poetry**:
```bash
poetry add x-request-id-middleware
```
### Django Installation
For Django support, install the package with the `django` extras:
```bash
pip install "x-request-id-middleware[django]"
```
Or using **Poetry**:
```bash
poetry add x-request-id-middleware -E django
```
### FastAPI Installation
For FastAPI support, install the package with the `fastapi` extras:
```bash
pip install "x-request-id-middleware[fastapi]"
```
Or using **Poetry**:
```bash
poetry add x-request-id-middleware -E fastapi
```
## Usage
### Django Setup
1. Add the `XRequestIDMiddleware` to your Django `MIDDLEWARE` settings:
```python
MIDDLEWARE = [
...,
'x_request_id_middleware.django_middleware.XRequestIDMiddleware',
...
]
```
2. Accessing the Request ID:
While you can access the request ID in your views or other parts of
your application, please note that this is typically not necessary in a
real-world application. The middleware automatically handles the
propagation of the `X-Request-ID` header for you.
```python
from x_request_id_middleware.common import get_x_request_id
def some_view(request):
x_request_id = get_x_request_id()
print(f"The request ID is: {x_request_id}")
```
In a real-world scenario, you usually do not need to manually access
the `X-Request-ID` as the middleware manages this automatically.
### FastAPI Setup
1. Add the `FastAPIXRequestIDMiddleware` to your FastAPI app:
```python
from fastapi import FastAPI
from x_request_id_middleware.fastapi_middleware import FastAPIXRequestIDMiddleware
app = FastAPI()
app.add_middleware(FastAPIXRequestIDMiddleware)
```
2. Accessing the Request ID:
Similarly, while you can access the request ID in your FastAPI routes,
this is generally not required in production. The middleware automatically
handles the `X-Request-ID` header for you.
```python
from x_request_id_middleware.common import get_x_request_id
@app.get("/")
async def root():
x_request_id = get_x_request_id()
return {"x_request_id": x_request_id}
```
In practice, the middleware ensures the `X-Request-ID` is propagated
properly without needing manual handling.
### Logging Integration
To include request IDs in your log messages,
use the `XRequestIDConfigLogging` class from the
`x_request_id_middleware.logging_config` module.
The XRequestIDConfigLogging class allows you to configure
logging and add request IDs to your log messages.
Setting Up `XRequestIDConfigLogging`
1. #### Import and Initialize
Import the XRequestIDConfigLogging class and create an instance of it.
You can optionally provide a custom log format string when initializing
the instance. If no format is provided, the default format will be used.
```python
from x_request_id_middleware.logging_config import XRequestIDConfigLogging
# Optionally, provide a custom log format
custom_format = "%(asctime)s %(levelname)s [%(x_request_id)s] %(message)s"
# Initialize with a custom format
x_request_id = XRequestIDConfigLogging(str_format=custom_format)
# Or initialize with default format
x_request_id = XRequestIDConfigLogging()
```
2. #### Configure Logging
Once you have created an instance of `XRequestIDConfigLogging`,
it will automatically set up the root logger and apply the formatter
and filter to it.
If you create new loggers using `logging.getLogger(__name__)` or similar,
you need to add them to the configuration by calling the `configure_logging`
method on your `XRequestIDConfigLogging` instance.
```python
import logging
from settings import x_request_id
# Example of configuring a new logger
logger = logging.getLogger(__name__)
x_request_id.configure_logging(logger)
```
The configure_logging method adds the formatter and filter to the
specified logger, ensuring that request IDs are included
in the log messages.
#### Example Usage
Here’s an example of how you might set up and use
`XRequestIDConfigLogging` in your application:
```python
import logging
from x_request_id_middleware.logging_config import XRequestIDConfigLogging
# Initialize XRequestIDConfigLogging with a custom format
x_request_id = XRequestIDConfigLogging(
str_format="%(asctime)s %(levelname)s [%(x_request_id)s] %(message)s"
)
# Create a new logger
logger = logging.getLogger(__name__)
# Configure the new logger to include request ID in log messages
x_request_id.configure_logging(logger)
# Use the logger in your application
logger.error("This is an error message with request ID.")
```
### Sentry Integration
If you're using Sentry for error tracking, this library automatically
adds the request ID to your Sentry logs. You don't need to manually set
the request ID for Sentry. Here’s how it works:
1. **Initialize Sentry in your project**:
Ensure that Sentry is initialized in your application as usual. For example:
```python
import sentry_sdk
sentry_sdk.init(
dsn="your_sentry_dsn_here",
# Other Sentry configuration
)
```
2. **Automatic Request ID Tagging**:
Once Sentry is initialized, the request ID will be automatically
attached to Sentry events as a `x_request_id` tag. This means you don't
need to call `set_request_id` manually. The middleware will handle
setting the request ID in the context for both Django and FastAPI,
and it will be picked up by Sentry.
Here’s how you would typically use the middleware in your applications:
- **For Django**:
```python
# In your Django settings.py
MIDDLEWARE = [
...,
'x_request_id_middleware.django_middleware.XRequestIDMiddleware',
...
]
```
- **For FastAPI**:
```python
from fastapi import FastAPI
from x_request_id_middleware.fastapi_middleware import FastAPIXRequestIDMiddleware
app = FastAPI()
app.add_middleware(FastAPIXRequestIDMiddleware)
```
You can now rely on Sentry to automatically handle request IDs for you.
## NGINX Integration
To ensure that request IDs are properly propagated through your system,
you need to configure NGINX to include the X-Request-ID header
in the request it passes to your application.
### NGINX Configuration
1. Update NGINX Configuration
Open your NGINX configuration file
(typically located at /etc/nginx/nginx.conf or
/etc/nginx/sites-available/default) and modify it to add the
X-Request-ID header. You can use the $x_request_id variable,
which NGINX generates for each request.
Example NGINX configuration:
```
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Request-ID $x_request_id;
}
}
```
In this example, the X-Request-ID header is set to the value of the
$x_request_id variable, which NGINX will include in requests forwarded
to your application.
2. Restart NGINX
After updating the configuration, restart NGINX to apply the changes:
```bash
sudo systemctl restart nginx
```
### Verifying X-Request-ID Propagation
1. Send a Request
Send a request to your server and verify that the X-Request-ID header
is included in the response.
2. Check Application Logs
Verify that your application logs include the X-request-ID,
which will help you trace requests through your system.
---
### Contributing
If you want to contribute to the project, please open an issue or
submit a pull request. All contributions, bug reports,
and feature requests are welcome.
---
### License
This project is licensed under the MIT License.
---
Raw data
{
"_id": null,
"home_page": "https://github.com/watchingwhileusleep/x-request-id-middleware",
"name": "x-request-id-middleware",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.8",
"maintainer_email": null,
"keywords": null,
"author": "WatchingWhileUSleep",
"author_email": "whatchingwhileusleepx@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/ef/06/ff5eeea05f2ebc87adc31f7bcba8f9093156f9c571a05778b6003ddc6952/x_request_id_middleware-0.2.2.tar.gz",
"platform": null,
"description": "# Request ID Middleware\n\n**Request ID Middleware** is a Python library that provides middleware for Django\nand FastAPI applications to generate and propagate request IDs across\nincoming requests, enabling easier tracking in logs, Sentry,\nand other observability tools.\n\n## Features\n- **Request ID Propagation**: Automatically generate or extract X-Request-ID headers and make them available throughout your application.\n- **Django and FastAPI Support**: Middleware that works out-of-the-box with Django and FastAPI.\n- **Sentry Integration**: Track request IDs in Sentry to trace issues by request.\n- **Logging Support**: Inject request IDs into logs for better traceability across services.\n\n## Installation\n\n### Basic Installation (Core)\n\nTo install the core package without any framework dependencies:\n\n```bash\npip install x-request-id-middleware\n```\n\nOr using **Poetry**:\n\n```bash\npoetry add x-request-id-middleware\n```\n\n### Django Installation\n\nFor Django support, install the package with the `django` extras:\n\n```bash\npip install \"x-request-id-middleware[django]\"\n```\n\nOr using **Poetry**:\n\n```bash\npoetry add x-request-id-middleware -E django\n```\n\n### FastAPI Installation\n\nFor FastAPI support, install the package with the `fastapi` extras:\n\n```bash\npip install \"x-request-id-middleware[fastapi]\"\n```\n\nOr using **Poetry**:\n\n```bash\npoetry add x-request-id-middleware -E fastapi\n```\n\n## Usage\n\n### Django Setup\n\n1. Add the `XRequestIDMiddleware` to your Django `MIDDLEWARE` settings:\n ```python\n MIDDLEWARE = [\n ...,\n 'x_request_id_middleware.django_middleware.XRequestIDMiddleware',\n ...\n ]\n ```\n\n2. Accessing the Request ID:\n\n While you can access the request ID in your views or other parts of\n your application, please note that this is typically not necessary in a\n real-world application. The middleware automatically handles the\n propagation of the `X-Request-ID` header for you.\n\n ```python\n from x_request_id_middleware.common import get_x_request_id\n \n def some_view(request):\n x_request_id = get_x_request_id()\n print(f\"The request ID is: {x_request_id}\")\n ```\n\n In a real-world scenario, you usually do not need to manually access\n the `X-Request-ID` as the middleware manages this automatically.\n\n### FastAPI Setup\n\n1. Add the `FastAPIXRequestIDMiddleware` to your FastAPI app:\n ```python\n from fastapi import FastAPI\n from x_request_id_middleware.fastapi_middleware import FastAPIXRequestIDMiddleware\n \n app = FastAPI()\n app.add_middleware(FastAPIXRequestIDMiddleware)\n ```\n\n2. Accessing the Request ID:\n\n Similarly, while you can access the request ID in your FastAPI routes,\n this is generally not required in production. The middleware automatically\n handles the `X-Request-ID` header for you.\n\n ```python\n from x_request_id_middleware.common import get_x_request_id\n \n @app.get(\"/\")\n async def root():\n x_request_id = get_x_request_id()\n return {\"x_request_id\": x_request_id}\n ```\n\n In practice, the middleware ensures the `X-Request-ID` is propagated\n properly without needing manual handling.\n\n### Logging Integration\n\nTo include request IDs in your log messages, \nuse the `XRequestIDConfigLogging` class from the \n`x_request_id_middleware.logging_config` module.\n\nThe XRequestIDConfigLogging class allows you to configure \nlogging and add request IDs to your log messages.\n\nSetting Up `XRequestIDConfigLogging`\n\n1. #### Import and Initialize\n\n Import the XRequestIDConfigLogging class and create an instance of it.\n You can optionally provide a custom log format string when initializing \n the instance. If no format is provided, the default format will be used.\n ```python\n from x_request_id_middleware.logging_config import XRequestIDConfigLogging\n \n # Optionally, provide a custom log format\n custom_format = \"%(asctime)s %(levelname)s [%(x_request_id)s] %(message)s\"\n \n # Initialize with a custom format\n x_request_id = XRequestIDConfigLogging(str_format=custom_format)\n \n # Or initialize with default format\n x_request_id = XRequestIDConfigLogging()\n ```\n2. #### Configure Logging\n\n Once you have created an instance of `XRequestIDConfigLogging`, \n it will automatically set up the root logger and apply the formatter\n and filter to it.\n\n If you create new loggers using `logging.getLogger(__name__)` or similar,\n you need to add them to the configuration by calling the `configure_logging`\n method on your `XRequestIDConfigLogging` instance.\n ```python\n import logging\n \n from settings import x_request_id\n\n # Example of configuring a new logger\n logger = logging.getLogger(__name__)\n x_request_id.configure_logging(logger)\n ```\n \n The configure_logging method adds the formatter and filter to the\n specified logger, ensuring that request IDs are included\n in the log messages.\n\n#### Example Usage\n\nHere\u2019s an example of how you might set up and use \n`XRequestIDConfigLogging` in your application:\n\n```python\nimport logging\n\nfrom x_request_id_middleware.logging_config import XRequestIDConfigLogging\n\n# Initialize XRequestIDConfigLogging with a custom format\nx_request_id = XRequestIDConfigLogging(\n str_format=\"%(asctime)s %(levelname)s [%(x_request_id)s] %(message)s\"\n)\n\n# Create a new logger\nlogger = logging.getLogger(__name__)\n\n# Configure the new logger to include request ID in log messages\nx_request_id.configure_logging(logger)\n\n# Use the logger in your application\nlogger.error(\"This is an error message with request ID.\")\n\n```\n\n### Sentry Integration\n\nIf you're using Sentry for error tracking, this library automatically\nadds the request ID to your Sentry logs. You don't need to manually set\nthe request ID for Sentry. Here\u2019s how it works:\n\n1. **Initialize Sentry in your project**:\n\n Ensure that Sentry is initialized in your application as usual. For example:\n \n ```python\n import sentry_sdk\n\n sentry_sdk.init(\n dsn=\"your_sentry_dsn_here\",\n # Other Sentry configuration\n )\n ```\n\n2. **Automatic Request ID Tagging**:\n\n Once Sentry is initialized, the request ID will be automatically\n attached to Sentry events as a `x_request_id` tag. This means you don't\n need to call `set_request_id` manually. The middleware will handle\n setting the request ID in the context for both Django and FastAPI,\n and it will be picked up by Sentry.\n\n Here\u2019s how you would typically use the middleware in your applications:\n\n - **For Django**:\n \n ```python\n # In your Django settings.py\n MIDDLEWARE = [\n ...,\n 'x_request_id_middleware.django_middleware.XRequestIDMiddleware',\n ...\n ]\n ```\n\n - **For FastAPI**:\n\n ```python\n from fastapi import FastAPI\n from x_request_id_middleware.fastapi_middleware import FastAPIXRequestIDMiddleware\n \n app = FastAPI()\n app.add_middleware(FastAPIXRequestIDMiddleware)\n ```\n\n You can now rely on Sentry to automatically handle request IDs for you.\n \n## NGINX Integration\n\nTo ensure that request IDs are properly propagated through your system,\nyou need to configure NGINX to include the X-Request-ID header\nin the request it passes to your application.\n\n### NGINX Configuration\n\n1. Update NGINX Configuration\nOpen your NGINX configuration file\n(typically located at /etc/nginx/nginx.conf or\n/etc/nginx/sites-available/default) and modify it to add the\nX-Request-ID header. You can use the $x_request_id variable,\nwhich NGINX generates for each request.\n\nExample NGINX configuration:\n\n```\nserver {\n listen 80;\n server_name yourdomain.com;\n\n location / {\n proxy_pass http://127.0.0.1:8000;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_set_header X-Request-ID $x_request_id;\n }\n}\n```\nIn this example, the X-Request-ID header is set to the value of the\n$x_request_id variable, which NGINX will include in requests forwarded\nto your application.\n\n2. Restart NGINX\n\nAfter updating the configuration, restart NGINX to apply the changes:\n\n```bash\nsudo systemctl restart nginx\n```\n\n### Verifying X-Request-ID Propagation\n\n1. Send a Request\n\n Send a request to your server and verify that the X-Request-ID header\n is included in the response.\n\n2. Check Application Logs\n\n Verify that your application logs include the X-request-ID, \n which will help you trace requests through your system.\n\n---\n\n### Contributing\n\nIf you want to contribute to the project, please open an issue or\nsubmit a pull request. All contributions, bug reports,\nand feature requests are welcome.\n\n---\n\n### License\n\nThis project is licensed under the MIT License.\n\n---\n\n\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Library to handle request ID propagation for Django and FastAPI",
"version": "0.2.2",
"project_urls": {
"Documentation": "https://github.com/watchingwhileusleep/x-request-id-middleware?tab=readme-ov-file",
"Homepage": "https://github.com/watchingwhileusleep/x-request-id-middleware",
"Repository": "https://github.com/watchingwhileusleep/x-request-id-middleware"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "4af88e9402b2bc084689f9acb43acc24093534123c57331d56926b5bf1a3d62c",
"md5": "01d33c0e3a230614bbe533b85cd4045b",
"sha256": "ad594e52ef80633ed04cf2c595c4f4ead0ae7c9261ab3cd057b0e5e4d7b1b748"
},
"downloads": -1,
"filename": "x_request_id_middleware-0.2.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "01d33c0e3a230614bbe533b85cd4045b",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.8",
"size": 9068,
"upload_time": "2024-08-29T11:42:35",
"upload_time_iso_8601": "2024-08-29T11:42:35.920081Z",
"url": "https://files.pythonhosted.org/packages/4a/f8/8e9402b2bc084689f9acb43acc24093534123c57331d56926b5bf1a3d62c/x_request_id_middleware-0.2.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "ef06ff5eeea05f2ebc87adc31f7bcba8f9093156f9c571a05778b6003ddc6952",
"md5": "a3fec247f276d2e429d4887b1455e618",
"sha256": "0414a53a112f20eb97b7486d9fbeba431447fef59ebbf4f3d23e80d2d31700ec"
},
"downloads": -1,
"filename": "x_request_id_middleware-0.2.2.tar.gz",
"has_sig": false,
"md5_digest": "a3fec247f276d2e429d4887b1455e618",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.8",
"size": 9793,
"upload_time": "2024-08-29T11:42:37",
"upload_time_iso_8601": "2024-08-29T11:42:37.333591Z",
"url": "https://files.pythonhosted.org/packages/ef/06/ff5eeea05f2ebc87adc31f7bcba8f9093156f9c571a05778b6003ddc6952/x_request_id_middleware-0.2.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-08-29 11:42:37",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "watchingwhileusleep",
"github_project": "x-request-id-middleware",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "x-request-id-middleware"
}