async def homepage(request): with trace("before api"): await asyncio.sleep(random()) response = await api_call() with trace("after api", "PRODUCER"): await asyncio.sleep(random()) return JSONResponse(response.json())
def test_trace_context(transport, root_span): dummy_trace = None with trace("my dummy trace") as span: span.annotate("dummy annotation") dummy_trace = _cur_span_ctx_var.get() dummy_record = dummy_trace._record.asdict() assert dummy_record == { "annotations": [ { "timestamp": dummy_record["annotations"][0]["timestamp"], "value": "dummy annotation", } ], "debug": False, "duration": dummy_record["duration"], "id": dummy_trace.context.span_id, "kind": "SERVER", "localEndpoint": {"serviceName": "dummy-service"}, "name": "my dummy trace", "parentId": root_span.context.span_id, "remoteEndpoint": None, "shared": False, "tags": {}, "timestamp": dummy_record["timestamp"], "traceId": root_span.context.trace_id, } assert transport.records == [dummy_record]
def test_headers(root_span): with trace("my dummy trace 4") as child_span: assert trace.make_headers() == { "X-B3-Flags": "0", "X-B3-ParentSpanId": root_span.context.span_id, "X-B3-Sampled": "1", "X-B3-SpanId": child_span._span.context.span_id, "X-B3-TraceId": child_span.trace_id, }
async def homepage(request): with trace("awesome api sub trace") as child_span: # ! if headers not explicitly provided,\ # root span from middleware injects headers # and becomes the parent for subsequet services wait = random.random() child_span.annotate( f"Child, sleeps for {wait}, injects headers and becomes parent") await asyncio.sleep(wait) return JSONResponse({"trace_id": child_span.trace_id})
def test_trace_id(root_span): with trace("my dummy trace 4") as child_span: assert child_span.trace_id is not None assert child_span.trace_id == root_span.context.trace_id
async def async_traced_function(): nonlocal dummy_trace_1, dummy_trace_2 dummy_trace_1 = _cur_span_ctx_var.get() async with trace("my dummy trace 3"): dummy_trace_2 = _cur_span_ctx_var.get() traced_function()
def traced_function(): nonlocal dummy_trace_3, dummy_trace_4 dummy_trace_3 = _cur_span_ctx_var.get() with trace("my dummy trace 4"): dummy_trace_4 = _cur_span_ctx_var.get()