You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fix: Align trace_context with middleware and add tests
Refactors the existing `trace_context` manager to align its behavior with the
`TraceContextMiddleware`, ensuring consistent and safe observability for
non-web tasks.
This commit addresses these issues by:
- Modifying `trace_context` to only accept `origin` and `trace_id`.
- Adding validation to ensure any provided `trace_id` is a valid UUID, matching the middleware's logic.
- Removing the ability to create arbitrary context variables via `**kwargs`.
Additionally, this change introduces:
- Tests for the `trace_context` manager, covering its functionality, validation, thread-safety, and use as a decorator.
- Documentation in the `README.md` with usage instructions and an example for background tasks.
Copy file name to clipboardExpand all lines: ansible_base/lib/middleware/profiling/README.md
+32Lines changed: 32 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -31,6 +31,8 @@ To enable cProfile support, set the following in your Django settings:
31
31
ANSIBLE_BASE_CPROFILE_REQUESTS=True
32
32
```
33
33
34
+
> **Note:** Enabling cProfile has significant performance implications and is intended for temporary, live debugging sessions, not for permanent use in production environments.
35
+
34
36
### SQL Profiling Support
35
37
36
38
When the `ANSIBLE_BASE_SQL_PROFILING` setting is enabled, the middleware provides insights into the database queries executed during a request. It adds the following headers to the response:
@@ -48,6 +50,8 @@ To enable SQL profiling, set the following in your Django settings:
48
50
ANSIBLE_BASE_SQL_PROFILING=True
49
51
```
50
52
53
+
> **Note:** This feature is most effective when used in combination with your database's slow query logging capabilities. For high-traffic environments, consider configuring your database to log only a percentage of queries to manage logging overhead.
54
+
51
55
## `DABProfiler`
52
56
53
57
For profiling non-HTTP contexts, such as background tasks or gRPC services, the `DABProfiler` class can be used directly.
@@ -76,6 +80,34 @@ def my_background_task():
76
80
print(f"Task took {elapsed:.3f}s to complete.")
77
81
```
78
82
83
+
## `trace_context` for Background Tasks
84
+
85
+
For adding observability to non-HTTP contexts without the overhead of the `DABProfiler`, the `trace_context` context manager is the ideal tool. It ensures that background tasks can be traced with a unique request ID, just like the `ObservabilityMiddleware` does for web requests.
86
+
87
+
This is particularly useful for background tasks, such as those initiated by the controller's dispatcher, where you want to correlate all log messages for a specific operation.
88
+
89
+
### Example Usage
90
+
91
+
Here's how you might use the `trace_context` manager in the controller's dispatcher to ensure that all work related to a specific job has a consistent trace ID.
92
+
93
+
```python
94
+
# In a hypothetical controller dispatcher task
95
+
from ansible_base.lib.logging.context import trace_context
96
+
97
+
defrun_job(job_id, parent_trace_id=None):
98
+
"""
99
+
A background task that runs a job.
100
+
"""
101
+
# Use the parent_trace_id if it exists; otherwise, a new one will be generated.
102
+
# The origin is a string that identifies the source of the trace.
103
+
with trace_context(origin='controller_dispatcher', trace_id=parent_trace_id):
104
+
# All logging within this block will now have the same trace_id.
105
+
# logger.info(f"Starting job {job_id}")
106
+
# ... do work ...
107
+
# logger.info(f"Finished job {job_id}")
108
+
pass
109
+
```
110
+
79
111
## Visualizing Profile Data
80
112
81
113
The `.prof` files generated by the cProfile support can be analyzed with a variety of tools.
0 commit comments