|
| 1 | +import logging |
| 2 | + |
1 | 3 | from ..context import Context |
2 | 4 |
|
| 5 | +log = logging.getLogger(__name__) |
| 6 | + |
3 | 7 | # HTTP headers one should set for distributed tracing. |
4 | 8 | # These are cross-language (eg: Python, Go and other implementations should honor these) |
5 | 9 | HTTP_HEADER_TRACE_ID = 'x-datadog-trace-id' |
@@ -55,14 +59,29 @@ def my_controller(url, headers): |
55 | 59 | if not headers: |
56 | 60 | return Context() |
57 | 61 |
|
58 | | - trace_id = int(headers.get(HTTP_HEADER_TRACE_ID, 0)) |
59 | | - parent_span_id = int(headers.get(HTTP_HEADER_PARENT_ID, 0)) |
60 | | - sampling_priority = headers.get(HTTP_HEADER_SAMPLING_PRIORITY) |
61 | | - if sampling_priority is not None: |
62 | | - sampling_priority = int(sampling_priority) |
63 | | - |
64 | | - return Context( |
65 | | - trace_id=trace_id, |
66 | | - span_id=parent_span_id, |
67 | | - sampling_priority=sampling_priority, |
68 | | - ) |
| 62 | + try: |
| 63 | + trace_id = int(headers.get(HTTP_HEADER_TRACE_ID, 0)) |
| 64 | + parent_span_id = int(headers.get(HTTP_HEADER_PARENT_ID, 0)) |
| 65 | + sampling_priority = headers.get(HTTP_HEADER_SAMPLING_PRIORITY) |
| 66 | + if sampling_priority is not None: |
| 67 | + sampling_priority = int(sampling_priority) |
| 68 | + |
| 69 | + return Context( |
| 70 | + trace_id=trace_id, |
| 71 | + span_id=parent_span_id, |
| 72 | + sampling_priority=sampling_priority, |
| 73 | + ) |
| 74 | + # If headers are invalid and cannot be parsed, return a new context and log the issue. |
| 75 | + except Exception as error: |
| 76 | + try: |
| 77 | + log.debug( |
| 78 | + "invalid x-datadog-* headers, trace-id: %s, parent-id: %s, priority: %s, error: %s", |
| 79 | + headers.get(HTTP_HEADER_TRACE_ID, 0), |
| 80 | + headers.get(HTTP_HEADER_PARENT_ID, 0), |
| 81 | + headers.get(HTTP_HEADER_SAMPLING_PRIORITY), |
| 82 | + error, |
| 83 | + ) |
| 84 | + # We might fail on string formatting errors ; in that case only format the first error |
| 85 | + except Exception: |
| 86 | + log.debug(error) |
| 87 | + return Context() |
0 commit comments