|
| 1 | +# ------------------------------------------------------------------------- |
| 2 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +# Licensed under the MIT License. See License in the project root for |
| 4 | +# license information. |
| 5 | +# -------------------------------------------------------------------------- |
| 6 | + |
| 7 | +import requests |
| 8 | +from azure.monitor.opentelemetry import configure_azure_monitor |
| 9 | +from opentelemetry.sdk.trace import SpanProcessor |
| 10 | +from opentelemetry.trace import get_tracer, SpanContext, SpanKind, TraceFlags |
| 11 | + |
| 12 | +# Define a custom processor to filter your spans |
| 13 | +class SpanFilteringProcessor(SpanProcessor): |
| 14 | + |
| 15 | + # Prevents exporting spans that are of kind INTERNAL |
| 16 | + def on_start(self, span, parent_context): |
| 17 | + # Check if the span is an internal activity. |
| 18 | + if span._kind is SpanKind.INTERNAL: |
| 19 | + # Create a new span context with the following properties: |
| 20 | + # * The trace ID is the same as the trace ID of the original span. |
| 21 | + # * The span ID is the same as the span ID of the original span. |
| 22 | + # * The is_remote property is set to `False`. |
| 23 | + # * The trace flags are set to `DEFAULT`. |
| 24 | + # * The trace state is the same as the trace state of the original span. |
| 25 | + span._context = SpanContext( |
| 26 | + span.context.trace_id, |
| 27 | + span.context.span_id, |
| 28 | + span.context.is_remote, |
| 29 | + TraceFlags(TraceFlags.DEFAULT), |
| 30 | + span.context.trace_state, |
| 31 | + ) |
| 32 | + |
| 33 | +# Create a SpanFilteringProcessor instance. |
| 34 | +span_filter_processor = SpanFilteringProcessor() |
| 35 | + |
| 36 | +# Pass in your processor to configuration options |
| 37 | +configure_azure_monitor( |
| 38 | + span_processors=[span_filter_processor] |
| 39 | +) |
| 40 | + |
| 41 | +tracer = get_tracer(__name__) |
| 42 | + |
| 43 | +with tracer.start_as_current_span("this_span_is_ignored"): |
| 44 | + # Requests made using the requests library will be automatically captured |
| 45 | + # The span generated from this request call will be tracked since it is not an INTERNAL span |
| 46 | + response = requests.get("https://azure.microsoft.com/", timeout=5) |
| 47 | + print("Hello, World!") |
| 48 | + |
| 49 | +input() |
0 commit comments