Skip to content

Commit 2632695

Browse files
author
Peter Giacomo Lombardo
committed
Example: Carry context across event loops
1 parent 93543bd commit 2632695

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

example/carry_context.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#
2+
# This example illustrates how to carry context from a syncronous tracing context into
3+
# an asynchronous one.
4+
#
5+
# In this use case, we want to launch a series of asyncronous http calls using uvloop and aiohttp
6+
#
7+
import asyncio
8+
import uvloop
9+
import aiohttp
10+
11+
from instana.singletons import tracer, async_tracer
12+
13+
uvloop.install()
14+
15+
async def launch_async_calls(parent_span):
16+
"""
17+
Method to launch a series (1 currently) of asynchronous http calls
18+
using uvloop and aiohttp. This method is run inside of an event loop
19+
with `asyncio.run`, `run_until_complete` or `gather`
20+
"""
21+
22+
# Now that we are inside of the event loop, first thing to do is to initialize
23+
# the tracing context using <parent_span> _and_ the asynchronous tracer <async_tracer>
24+
with async_tracer.start_active_span('launch_async_calls', child_of=parent_span):
25+
async with aiohttp.ClientSession() as session:
26+
session.get("http://127.0.0.1/api/v2/endpoint/1")
27+
session.get("http://127.0.0.1/api/v2/endpoint/2")
28+
session.get("http://127.0.0.1/api/v2/endpoint/3")
29+
30+
#
31+
# Synchronous application code such as from inside a Django or Flask handler
32+
#
33+
34+
# Start an ENTRY span in our synchronous execution scope
35+
with tracer.start_active_span("launch_uvloop") as sync_scope:
36+
sync_scope.span.set_tag('span.kind', 'entry')
37+
38+
# Launch our requests asynchronously
39+
# Enter the event loop and pass in the parent tracing context (sync_scope) manually
40+
asyncio.run(launch_async_calls(sync_scope.span))
41+

0 commit comments

Comments
 (0)