|
2 | 2 | Custom OpenTelemetry SpanProcessor filters to reduce telemetry noise in Application Insights. |
3 | 3 | """ |
4 | 4 |
|
| 5 | +import logging |
5 | 6 | from opentelemetry.sdk.trace import SpanProcessor, ReadableSpan |
6 | 7 | from opentelemetry.trace import SpanContext, TraceFlags |
7 | 8 |
|
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
8 | 11 |
|
9 | 12 | def _unsample(span: ReadableSpan) -> None: |
10 | 13 | """Set trace_flags to 0 so BatchSpanProcessor skips exporting this span.""" |
11 | | - span._context = SpanContext( |
12 | | - trace_id=span.context.trace_id, |
13 | | - span_id=span.context.span_id, |
14 | | - is_remote=span.context.is_remote, |
15 | | - trace_flags=TraceFlags(0), |
16 | | - trace_state=span.context.trace_state, |
17 | | - ) |
| 14 | + try: |
| 15 | + span._context = SpanContext( |
| 16 | + trace_id=span.context.trace_id, |
| 17 | + span_id=span.context.span_id, |
| 18 | + is_remote=span.context.is_remote, |
| 19 | + trace_flags=TraceFlags(0), |
| 20 | + trace_state=span.context.trace_state, |
| 21 | + ) |
| 22 | + except (AttributeError, TypeError) as e: |
| 23 | + # Gracefully handle SDK changes where _context might not be mutable |
| 24 | + logger.debug("Unable to unsample span %s: %s", span.name, e) |
18 | 25 |
|
19 | 26 |
|
20 | 27 | class DropASGIResponseBodySpanProcessor(SpanProcessor): |
@@ -62,9 +69,11 @@ def on_start(self, span, parent_context=None): |
62 | 69 |
|
63 | 70 | def on_end(self, span: ReadableSpan) -> None: |
64 | 71 | attrs = span.attributes or {} |
| 72 | + span_name = span.name or "" |
65 | 73 | if ( |
66 | 74 | attrs.get("db.system") == "cosmosdb" |
67 | | - or "documents.azure.com" in (span.name or "") |
| 75 | + or ".documents.azure.com" in span_name |
| 76 | + or span_name.endswith("documents.azure.com") |
68 | 77 | ): |
69 | 78 | _unsample(span) |
70 | 79 |
|
|
0 commit comments