0
# Trace Export
1
2
Distributed tracing export that sends OpenCensus span data to Azure Monitor for request tracking, dependency mapping, and performance analysis. The trace exporter enables comprehensive application performance monitoring through distributed tracing capabilities.
3
4
## Capabilities
5
6
### Azure Exporter
7
8
Exports OpenCensus trace spans to Azure Monitor, automatically detecting request vs. dependency spans and transforming them into appropriate Azure Monitor telemetry types.
9
10
```python { .api }
11
class AzureExporter(BaseExporter, TransportMixin, ProcessorMixin):
12
"""
13
An exporter that sends traces to Microsoft Azure Monitor.
14
15
Automatically converts OpenCensus span data to Azure Monitor request
16
and dependency telemetry, including HTTP-specific attributes and
17
exception handling.
18
"""
19
20
def __init__(self, **options):
21
"""
22
Initialize the Azure trace exporter.
23
24
Args:
25
**options: Configuration options including connection_string,
26
instrumentation_key, export_interval, etc.
27
"""
28
29
def export(self, span_datas):
30
"""
31
Export span data items (inherited from BaseExporter).
32
33
Queues span data for asynchronous export to Azure Monitor.
34
35
Args:
36
span_datas (list): List of SpanData objects to queue for export
37
"""
38
39
def span_data_to_envelope(self, span_data):
40
"""
41
Convert span data to Azure Monitor telemetry envelope(s).
42
43
Args:
44
span_data (SpanData): OpenCensus span data object
45
46
Yields:
47
Envelope: Azure Monitor telemetry envelope(s)
48
"""
49
50
def emit(self, batch, event=None):
51
"""
52
Process and transmit a batch of spans.
53
54
Args:
55
batch (list): List of span data objects
56
event (QueueEvent, optional): Synchronization event
57
"""
58
59
def add_telemetry_processor(self, processor):
60
"""
61
Add a telemetry processor for filtering/modifying telemetry.
62
63
Args:
64
processor (callable): Function that takes and returns envelope
65
"""
66
```
67
68
#### Basic Usage Example
69
70
```python
71
from opencensus.trace.tracer import Tracer
72
from opencensus.ext.azure.trace_exporter import AzureExporter
73
74
# Configure the exporter
75
exporter = AzureExporter(
76
connection_string="InstrumentationKey=your-instrumentation-key"
77
)
78
79
# Create tracer with Azure exporter
80
tracer = Tracer(exporter=exporter)
81
82
# Trace a simple operation
83
with tracer.span(name="process_order") as span:
84
span.add_attribute("order_id", "12345")
85
span.add_attribute("customer_id", "67890")
86
87
# Nested span for database operation
88
with tracer.span(name="database_query") as db_span:
89
db_span.add_attribute("query", "SELECT * FROM orders")
90
db_span.add_attribute("duration_ms", 45)
91
# Database operation here
92
93
# HTTP dependency span
94
with tracer.span(name="external_api_call") as api_span:
95
api_span.add_attribute("http.method", "POST")
96
api_span.add_attribute("http.url", "https://api.example.com/validate")
97
api_span.add_attribute("http.status_code", 200)
98
# API call here
99
```
100
101
#### Advanced Usage with HTTP Instrumentation
102
103
```python
104
from opencensus.trace.tracer import Tracer
105
from opencensus.ext.azure.trace_exporter import AzureExporter
106
from opencensus.ext.requests.trace import RequestsInstrumentor
107
from opencensus.ext.flask.flask_middleware import FlaskMiddleware
108
109
# Configure exporter
110
exporter = AzureExporter(
111
connection_string="InstrumentationKey=your-instrumentation-key",
112
export_interval=10.0, # Export every 10 seconds
113
max_batch_size=50 # Batch up to 50 spans
114
)
115
116
# Flask application with automatic request tracing
117
app = Flask(__name__)
118
middleware = FlaskMiddleware(app, exporter=exporter)
119
120
# Automatic HTTP client tracing
121
RequestsInstrumentor().instrument()
122
123
@app.route('/api/orders/<order_id>')
124
def get_order(order_id):
125
# This request is automatically traced as a SERVER span
126
# Any requests.get() calls are traced as CLIENT spans
127
128
# Manual span for business logic
129
tracer = middleware.tracer
130
with tracer.span(name="order_processing") as span:
131
span.add_attribute("order_id", order_id)
132
133
# This HTTP call is automatically traced
134
response = requests.get(f"https://api.inventory.com/check/{order_id}")
135
136
return {"order": order_id, "status": "processed"}
137
```
138
139
## Span Type Mapping
140
141
The Azure exporter automatically maps OpenCensus spans to Azure Monitor telemetry types:
142
143
### Server Spans (SpanKind.SERVER)
144
145
Server spans become **Request** telemetry in Azure Monitor:
146
147
- **Name**: HTTP method + route (e.g., "GET /api/orders")
148
- **Duration**: Span start to end time
149
- **Success**: Based on HTTP status code or span status
150
- **Properties**: All span attributes except HTTP-specific ones
151
- **URL**: From `http.url` attribute
152
- **Response Code**: From `http.status_code` attribute
153
154
### Client Spans (SpanKind.CLIENT)
155
156
Client spans become **RemoteDependency** telemetry:
157
158
- **Name**: HTTP method + path (e.g., "POST /validate")
159
- **Type**: Component type (e.g., "HTTP", "SQL")
160
- **Target**: Host and port from URL
161
- **Data**: Full URL for HTTP calls
162
- **Success**: Based on HTTP status code or span status
163
- **Properties**: All span attributes except HTTP-specific ones
164
165
### Internal Spans
166
167
Internal spans become **RemoteDependency** telemetry with type "INPROC":
168
169
- **Name**: Span name
170
- **Type**: "INPROC"
171
- **Success**: Always true unless span has error status
172
- **Properties**: All span attributes
173
174
## Exception Handling
175
176
Server spans with exceptions automatically generate both Request and Exception telemetry:
177
178
```python
179
# Example: Exception in server span
180
with tracer.span(name="risky_operation") as span:
181
span.add_attribute("operation_type", "data_processing")
182
183
try:
184
# Risky operation
185
result = process_data()
186
except ValueError as e:
187
# Add exception details to span
188
span.add_attribute("error.name", "ValueError")
189
span.add_attribute("error.message", str(e))
190
span.add_attribute("stacktrace", traceback.format_exc())
191
span.set_status(Status(code=StatusCode.ERROR, message=str(e)))
192
raise
193
194
# This generates:
195
# 1. Request telemetry for the operation
196
# 2. Exception telemetry with stack trace
197
```
198
199
## HTTP Attribute Mapping
200
201
The exporter recognizes these OpenCensus HTTP attributes:
202
203
- `http.method` → Request/dependency name prefix
204
- `http.url` → Request URL or dependency data
205
- `http.route` → Request name (preferred over path)
206
- `http.path` → Request name (fallback)
207
- `http.status_code` → Response code and success determination
208
209
## Correlation and Context
210
211
The exporter automatically handles distributed tracing correlation:
212
213
- **Operation ID**: Maps to OpenCensus trace ID
214
- **Parent ID**: Maps to parent span ID
215
- **Operation Name**: Derived from HTTP route for server spans
216
- **Links**: W3C trace context links for cross-service correlation
217
218
## Configuration Options
219
220
Trace exporter supports these specific options in addition to common options:
221
222
- `grace_period` (float): Time to wait for clean shutdown (default: 5.0 seconds)
223
- Automatic registration with `atexit` for graceful shutdown
224
225
## Performance Considerations
226
227
- **Asynchronous Export**: Spans are exported asynchronously to avoid blocking application
228
- **Batching**: Multiple spans are sent in single HTTP requests
229
- **Local Storage**: Optional persistence prevents data loss during connectivity issues
230
- **Sampling**: Use OpenCensus sampling to control telemetry volume
231
232
## Integration Examples
233
234
### Django Integration
235
236
```python
237
from opencensus.ext.django.middleware import OpencensusMiddleware
238
from opencensus.ext.azure.trace_exporter import AzureExporter
239
240
MIDDLEWARE = [
241
'opencensus.ext.django.middleware.OpencensusMiddleware',
242
# ... other middleware
243
]
244
245
OPENCENSUS = {
246
'TRACE': {
247
'EXPORTER': {
248
'CLASS_NAME': 'opencensus.ext.azure.trace_exporter.AzureExporter',
249
'OPTIONS': {
250
'connection_string': 'InstrumentationKey=your-key-here'
251
}
252
}
253
}
254
}
255
```
256
257
### FastAPI Integration
258
259
```python
260
from fastapi import FastAPI
261
from opencensus.ext.azure.trace_exporter import AzureExporter
262
from opencensus.trace.tracer import Tracer
263
from opencensus.trace.samplers import ProbabilitySampler
264
265
app = FastAPI()
266
267
# Configure tracer
268
exporter = AzureExporter(connection_string="InstrumentationKey=your-key-here")
269
tracer = Tracer(exporter=exporter, sampler=ProbabilitySampler(rate=1.0))
270
271
@app.middleware("http")
272
async def trace_requests(request, call_next):
273
with tracer.span(name=f"{request.method} {request.url.path}") as span:
274
span.add_attribute("http.method", request.method)
275
span.add_attribute("http.url", str(request.url))
276
277
response = await call_next(request)
278
279
span.add_attribute("http.status_code", response.status_code)
280
return response
281
```