Skip to content

Commit 42796b2

Browse files
committed
chore: use get_tracer() for all tracer access
Signed-off-by: Cagri Yonca <[email protected]>
1 parent 9369fdd commit 42796b2

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

69 files changed

+1212
-908
lines changed

example/carry_context.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,13 @@
1111
import uvloop
1212
import aiohttp
1313

14-
from instana.singletons import tracer, async_tracer
14+
from instana.singletons import get_tracer
1515

1616
uvloop.install()
1717

18+
tracer = get_tracer()
19+
20+
1821
async def launch_async_calls(parent_span):
1922
"""
2023
Method to launch a series (1 currently) of asynchronous http calls
@@ -24,24 +27,24 @@ async def launch_async_calls(parent_span):
2427

2528
# Now that we are inside of the event loop, first thing to do is to initialize
2629
# the tracing context using <parent_span> _and_ the asynchronous tracer <async_tracer>
27-
with async_tracer.start_active_span('launch_async_calls', child_of=parent_span):
30+
with async_tracer.start_active_span("launch_async_calls", child_of=parent_span): # noqa: F821
2831
async with aiohttp.ClientSession() as session:
2932
session.get("http://127.0.0.1/api/v2/endpoint/1")
3033
session.get("http://127.0.0.1/api/v2/endpoint/2")
3134
session.get("http://127.0.0.1/api/v2/endpoint/3")
3235

36+
3337
#
3438
# Synchronous application code such as from inside a Django or Flask handler
3539
#
3640

3741
# Start an ENTRY span in our synchronous execution scope
3842
with tracer.start_active_span("launch_uvloop") as sync_scope:
39-
sync_scope.span.set_tag('span.kind', 'entry')
43+
sync_scope.span.set_tag("span.kind", "entry")
4044

4145
# You can also retrieve the currently active span with:
4246
# tracer.active_span
4347

4448
# Launch our requests asynchronously
4549
# Enter the event loop and pass in the parent tracing context (sync_scope) manually
4650
asyncio.run(launch_async_calls(sync_scope.span))
47-

src/instana/instrumentation/aio_pika.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# (c) Copyright IBM Corp. 2025
22

33
try:
4-
import aio_pika
4+
import aio_pika # noqa: F401
55
import wrapt
66
from typing import (
77
TYPE_CHECKING,
@@ -16,7 +16,7 @@
1616
from instana.log import logger
1717
from instana.propagators.format import Format
1818
from instana.util.traceutils import get_tracer_tuple, tracing_is_off
19-
from instana.singletons import tracer
19+
from instana.singletons import get_tracer
2020

2121
if TYPE_CHECKING:
2222
from instana.span.span import InstanaSpan
@@ -54,10 +54,8 @@ def _bind_args(
5454
**kwargs: object,
5555
) -> Tuple[object, ...]:
5656
return (message, routing_key, args, kwargs)
57-
58-
(message, routing_key, args, kwargs) = _bind_args(
59-
*args, **kwargs
60-
)
57+
58+
(message, routing_key, args, kwargs) = _bind_args(*args, **kwargs)
6159

6260
with tracer.start_as_current_span(
6361
"rabbitmq", span_context=parent_context
@@ -102,6 +100,7 @@ async def callback_wrapper(
102100
kwargs: Dict[str, Any],
103101
) -> Callable[[Type["AbstractMessage"]], Any]:
104102
message = args[0]
103+
tracer = get_tracer()
105104
parent_context = tracer.extract(
106105
Format.HTTP_HEADERS, message.headers, disable_w3c_trace_context=True
107106
)

src/instana/instrumentation/aiohttp/server.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from instana.log import logger
1111
from instana.propagators.format import Format
12-
from instana.singletons import agent, tracer
12+
from instana.singletons import agent, get_tracer
1313
from instana.util.secrets import strip_secrets_from_query
1414
from instana.util.traceutils import extract_custom_headers
1515

@@ -29,6 +29,7 @@ async def stan_middleware(
2929
handler: Callable[..., object],
3030
) -> Awaitable["aiohttp.web.Response"]:
3131
try:
32+
tracer = get_tracer()
3233
span_context = tracer.extract(Format.HTTP_HEADERS, request.headers)
3334
span: "InstanaSpan" = tracer.start_span(
3435
"aiohttp-server", span_context=span_context

src/instana/instrumentation/asgi.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,10 @@
88
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict
99

1010
from opentelemetry.semconv.trace import SpanAttributes
11-
from opentelemetry.trace import SpanKind
1211

1312
from instana.log import logger
1413
from instana.propagators.format import Format
15-
from instana.singletons import agent, tracer
14+
from instana.singletons import agent, get_tracer
1615
from instana.util.secrets import strip_secrets_from_query
1716
from instana.util.traceutils import extract_custom_headers
1817

@@ -66,6 +65,7 @@ async def __call__(
6665
send: Callable[[Dict[str, Any]], Awaitable[None]],
6766
) -> None:
6867
request_context = None
68+
tracer = get_tracer()
6969

7070
if scope["type"] not in ("http", "websocket"):
7171
return await self.app(scope, receive, send)
@@ -104,11 +104,14 @@ async def send_wrapper(response: Dict[str, Any]) -> Awaitable[None]:
104104
if status_code:
105105
if 500 <= int(status_code):
106106
current_span.mark_as_errored()
107-
current_span.set_attribute(SpanAttributes.HTTP_STATUS_CODE, status_code)
107+
current_span.set_attribute(
108+
SpanAttributes.HTTP_STATUS_CODE, status_code
109+
)
108110

109111
headers = response.get("headers")
110112
if headers:
111113
extract_custom_headers(current_span, headers)
114+
tracer = get_tracer()
112115
tracer.inject(current_span.context, Format.BINARY, headers)
113116
except Exception:
114117
logger.debug("ASGI send_wrapper error: ", exc_info=True)

src/instana/instrumentation/aws/boto3.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020
from instana.log import logger
2121
from instana.propagators.format import Format
22-
from instana.singletons import tracer
22+
from instana.singletons import get_tracer
2323
from instana.span.span import get_current_span
2424
from instana.util.traceutils import (
2525
extract_custom_headers,
@@ -34,6 +34,7 @@ def lambda_inject_context(payload: Dict[str, Any], span: "InstanaSpan") -> None:
3434
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#Lambda.Client.invoke
3535
"""
3636
try:
37+
tracer = get_tracer()
3738
invoke_payload = payload.get("Payload", {})
3839

3940
if not isinstance(invoke_payload, dict):

src/instana/instrumentation/aws/dynamodb.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from botocore.client import BaseClient
77

88
from instana.log import logger
9-
from instana.singletons import tracer
9+
from instana.singletons import get_tracer
1010
from instana.span_context import SpanContext
1111

1212

@@ -17,6 +17,7 @@ def create_dynamodb_span(
1717
kwargs: Dict[str, Any],
1818
parent_context: SpanContext,
1919
) -> None:
20+
tracer = get_tracer()
2021
with tracer.start_as_current_span("dynamodb", span_context=parent_context) as span:
2122
try:
2223
span.set_attribute("dynamodb.op", args[0])

src/instana/instrumentation/aws/s3.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import wrapt
1212

1313
from instana.log import logger
14-
from instana.singletons import tracer
14+
from instana.singletons import get_tracer
1515
from instana.util.traceutils import (
1616
get_tracer_tuple,
1717
tracing_is_off,
@@ -31,6 +31,7 @@ def create_s3_span(
3131
kwargs: Dict[str, Any],
3232
parent_context: SpanContext,
3333
) -> None:
34+
tracer = get_tracer()
3435
with tracer.start_as_current_span("s3", span_context=parent_context) as span:
3536
try:
3637
span.set_attribute("s3.op", args[0])
@@ -66,15 +67,17 @@ def collect_s3_injected_attributes(
6667
span.set_attribute("s3.bucket", args[1])
6768
except Exception:
6869
logger.debug(
69-
f"collect_s3_injected_attributes collect error: {wrapped.__name__}", exc_info=True
70+
f"collect_s3_injected_attributes collect error: {wrapped.__name__}",
71+
exc_info=True,
7072
)
7173

7274
try:
7375
return wrapped(*args, **kwargs)
7476
except Exception as exc:
7577
span.record_exception(exc)
7678
logger.debug(
77-
f"collect_s3_injected_attributes error: {wrapped.__name__}", exc_info=True
79+
f"collect_s3_injected_attributes error: {wrapped.__name__}",
80+
exc_info=True,
7881
)
7982
raise
8083

src/instana/instrumentation/celery.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,20 @@
22
# (c) Copyright Instana Inc. 2020
33

44

5-
import contextvars
6-
from typing import Any, Dict, Tuple
7-
from instana.log import logger
8-
from instana.propagators.format import Format
9-
from instana.singletons import tracer
10-
from instana.span.span import InstanaSpan
11-
from instana.util.traceutils import get_tracer_tuple
12-
from opentelemetry import trace, context
13-
145
try:
15-
import celery
6+
import celery # noqa: F401
7+
import contextvars
8+
from typing import Any, Dict, Tuple
9+
from urllib import parse
10+
1611
from celery import registry, signals
12+
from opentelemetry import context, trace
1713

18-
from urllib import parse
14+
from instana.log import logger
15+
from instana.propagators.format import Format
16+
from instana.singletons import get_tracer
17+
from instana.span.span import InstanaSpan
18+
from instana.util.traceutils import get_tracer_tuple
1919

2020
client_token: Dict[str, Any] = {}
2121
worker_token: Dict[str, Any] = {}
@@ -67,6 +67,7 @@ def task_prerun(
6767
) -> None:
6868
try:
6969
ctx = None
70+
tracer = get_tracer()
7071

7172
task = kwargs.get("sender", None)
7273
task_id = kwargs.get("task_id", None)

src/instana/instrumentation/django/middleware.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from typing import TYPE_CHECKING, Dict, Any, Callable, Optional, List, Tuple, Type
1212

1313
from instana.log import logger
14-
from instana.singletons import agent, tracer
14+
from instana.singletons import agent, get_tracer
1515
from instana.util.secrets import strip_secrets_from_query
1616
from instana.util.traceutils import extract_custom_headers
1717
from instana.propagators.format import Format
@@ -55,6 +55,7 @@ def __init__(
5555

5656
def process_request(self, request: Type["HttpRequest"]) -> None:
5757
try:
58+
tracer = get_tracer()
5859
env = request.META
5960

6061
span_context = tracer.extract(Format.HTTP_HEADERS, env)
@@ -81,7 +82,9 @@ def process_request(self, request: Type["HttpRequest"]) -> None:
8182
)
8283
request.span.set_attribute("http.params", scrubbed_params)
8384
if "HTTP_HOST" in env:
84-
request.span.set_attribute(SpanAttributes.HTTP_HOST, env["HTTP_HOST"])
85+
request.span.set_attribute(
86+
SpanAttributes.HTTP_HOST, env["HTTP_HOST"]
87+
)
8588
except Exception:
8689
logger.debug("Django middleware @ process_request", exc_info=True)
8790

@@ -118,6 +121,7 @@ def process_response(
118121
extract_custom_headers(
119122
request.span, response.headers, format=False
120123
)
124+
tracer = get_tracer()
121125
tracer.inject(request.span.context, Format.HTTP_HEADERS, response)
122126
except Exception:
123127
logger.debug("Instana middleware @ process_response", exc_info=True)

src/instana/instrumentation/flask/common.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from opentelemetry.semconv.trace import SpanAttributes
1111

1212
from instana.log import logger
13-
from instana.singletons import tracer
13+
from instana.singletons import get_tracer
1414
from instana.propagators.format import Format
1515

1616

@@ -19,7 +19,8 @@
1919
from flask.typing import ResponseReturnValue
2020
from jinja2.environment import Template
2121

22-
@wrapt.patch_function_wrapper('flask', 'templating._render')
22+
23+
@wrapt.patch_function_wrapper("flask", "templating._render")
2324
def render_with_instana(
2425
wrapped: Callable[..., str],
2526
instance: object,
@@ -32,6 +33,7 @@ def render_with_instana(
3233

3334
parent_span = flask.g.span
3435
parent_context = parent_span.get_span_context()
36+
tracer = get_tracer()
3537

3638
with tracer.start_as_current_span("render", span_context=parent_context) as span:
3739
try:
@@ -50,7 +52,7 @@ def render_with_instana(
5052
raise
5153

5254

53-
@wrapt.patch_function_wrapper('flask', 'Flask.handle_user_exception')
55+
@wrapt.patch_function_wrapper("flask", "Flask.handle_user_exception")
5456
def handle_user_exception_with_instana(
5557
wrapped: Callable[..., Union["HTTPException", "ResponseReturnValue"]],
5658
instance: flask.app.Flask,
@@ -70,7 +72,7 @@ def handle_user_exception_with_instana(
7072
if isinstance(response, tuple):
7173
status_code = response[1]
7274
else:
73-
if hasattr(response, 'code'):
75+
if hasattr(response, "code"):
7476
status_code = response.code
7577
else:
7678
status_code = response.status_code
@@ -80,12 +82,13 @@ def handle_user_exception_with_instana(
8082

8183
span.set_attribute(SpanAttributes.HTTP_STATUS_CODE, int(status_code))
8284

83-
if hasattr(response, 'headers'):
85+
if hasattr(response, "headers"):
86+
tracer = get_tracer()
8487
tracer.inject(span.context, Format.HTTP_HEADERS, response.headers)
8588
if span and span.is_recording():
8689
span.end()
8790
flask.g.span = None
88-
except:
91+
except Exception:
8992
logger.debug("handle_user_exception_with_instana:", exc_info=True)
9093

9194
return response

0 commit comments

Comments
 (0)