sentry-sdk 0.7.5__py2.py3-none-any.whl → 2.46.0__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sentry_sdk/__init__.py +48 -30
- sentry_sdk/_compat.py +74 -61
- sentry_sdk/_init_implementation.py +84 -0
- sentry_sdk/_log_batcher.py +172 -0
- sentry_sdk/_lru_cache.py +47 -0
- sentry_sdk/_metrics_batcher.py +167 -0
- sentry_sdk/_queue.py +289 -0
- sentry_sdk/_types.py +338 -0
- sentry_sdk/_werkzeug.py +98 -0
- sentry_sdk/ai/__init__.py +7 -0
- sentry_sdk/ai/monitoring.py +137 -0
- sentry_sdk/ai/utils.py +144 -0
- sentry_sdk/api.py +496 -80
- sentry_sdk/attachments.py +75 -0
- sentry_sdk/client.py +1023 -103
- sentry_sdk/consts.py +1438 -66
- sentry_sdk/crons/__init__.py +10 -0
- sentry_sdk/crons/api.py +62 -0
- sentry_sdk/crons/consts.py +4 -0
- sentry_sdk/crons/decorator.py +135 -0
- sentry_sdk/debug.py +15 -14
- sentry_sdk/envelope.py +369 -0
- sentry_sdk/feature_flags.py +71 -0
- sentry_sdk/hub.py +611 -280
- sentry_sdk/integrations/__init__.py +276 -49
- sentry_sdk/integrations/_asgi_common.py +108 -0
- sentry_sdk/integrations/_wsgi_common.py +180 -44
- sentry_sdk/integrations/aiohttp.py +291 -42
- sentry_sdk/integrations/anthropic.py +439 -0
- sentry_sdk/integrations/argv.py +9 -8
- sentry_sdk/integrations/ariadne.py +161 -0
- sentry_sdk/integrations/arq.py +247 -0
- sentry_sdk/integrations/asgi.py +341 -0
- sentry_sdk/integrations/asyncio.py +144 -0
- sentry_sdk/integrations/asyncpg.py +208 -0
- sentry_sdk/integrations/atexit.py +17 -10
- sentry_sdk/integrations/aws_lambda.py +377 -62
- sentry_sdk/integrations/beam.py +176 -0
- sentry_sdk/integrations/boto3.py +137 -0
- sentry_sdk/integrations/bottle.py +221 -0
- sentry_sdk/integrations/celery/__init__.py +529 -0
- sentry_sdk/integrations/celery/beat.py +293 -0
- sentry_sdk/integrations/celery/utils.py +43 -0
- sentry_sdk/integrations/chalice.py +134 -0
- sentry_sdk/integrations/clickhouse_driver.py +177 -0
- sentry_sdk/integrations/cloud_resource_context.py +280 -0
- sentry_sdk/integrations/cohere.py +274 -0
- sentry_sdk/integrations/dedupe.py +48 -14
- sentry_sdk/integrations/django/__init__.py +584 -191
- sentry_sdk/integrations/django/asgi.py +245 -0
- sentry_sdk/integrations/django/caching.py +204 -0
- sentry_sdk/integrations/django/middleware.py +187 -0
- sentry_sdk/integrations/django/signals_handlers.py +91 -0
- sentry_sdk/integrations/django/templates.py +79 -5
- sentry_sdk/integrations/django/transactions.py +49 -22
- sentry_sdk/integrations/django/views.py +96 -0
- sentry_sdk/integrations/dramatiq.py +226 -0
- sentry_sdk/integrations/excepthook.py +50 -13
- sentry_sdk/integrations/executing.py +67 -0
- sentry_sdk/integrations/falcon.py +272 -0
- sentry_sdk/integrations/fastapi.py +141 -0
- sentry_sdk/integrations/flask.py +142 -88
- sentry_sdk/integrations/gcp.py +239 -0
- sentry_sdk/integrations/gnu_backtrace.py +99 -0
- sentry_sdk/integrations/google_genai/__init__.py +301 -0
- sentry_sdk/integrations/google_genai/consts.py +16 -0
- sentry_sdk/integrations/google_genai/streaming.py +155 -0
- sentry_sdk/integrations/google_genai/utils.py +576 -0
- sentry_sdk/integrations/gql.py +162 -0
- sentry_sdk/integrations/graphene.py +151 -0
- sentry_sdk/integrations/grpc/__init__.py +168 -0
- sentry_sdk/integrations/grpc/aio/__init__.py +7 -0
- sentry_sdk/integrations/grpc/aio/client.py +95 -0
- sentry_sdk/integrations/grpc/aio/server.py +100 -0
- sentry_sdk/integrations/grpc/client.py +91 -0
- sentry_sdk/integrations/grpc/consts.py +1 -0
- sentry_sdk/integrations/grpc/server.py +66 -0
- sentry_sdk/integrations/httpx.py +178 -0
- sentry_sdk/integrations/huey.py +174 -0
- sentry_sdk/integrations/huggingface_hub.py +378 -0
- sentry_sdk/integrations/langchain.py +1132 -0
- sentry_sdk/integrations/langgraph.py +337 -0
- sentry_sdk/integrations/launchdarkly.py +61 -0
- sentry_sdk/integrations/litellm.py +287 -0
- sentry_sdk/integrations/litestar.py +315 -0
- sentry_sdk/integrations/logging.py +307 -96
- sentry_sdk/integrations/loguru.py +213 -0
- sentry_sdk/integrations/mcp.py +566 -0
- sentry_sdk/integrations/modules.py +14 -31
- sentry_sdk/integrations/openai.py +725 -0
- sentry_sdk/integrations/openai_agents/__init__.py +61 -0
- sentry_sdk/integrations/openai_agents/consts.py +1 -0
- sentry_sdk/integrations/openai_agents/patches/__init__.py +5 -0
- sentry_sdk/integrations/openai_agents/patches/agent_run.py +140 -0
- sentry_sdk/integrations/openai_agents/patches/error_tracing.py +77 -0
- sentry_sdk/integrations/openai_agents/patches/models.py +50 -0
- sentry_sdk/integrations/openai_agents/patches/runner.py +45 -0
- sentry_sdk/integrations/openai_agents/patches/tools.py +77 -0
- sentry_sdk/integrations/openai_agents/spans/__init__.py +5 -0
- sentry_sdk/integrations/openai_agents/spans/agent_workflow.py +21 -0
- sentry_sdk/integrations/openai_agents/spans/ai_client.py +42 -0
- sentry_sdk/integrations/openai_agents/spans/execute_tool.py +48 -0
- sentry_sdk/integrations/openai_agents/spans/handoff.py +19 -0
- sentry_sdk/integrations/openai_agents/spans/invoke_agent.py +86 -0
- sentry_sdk/integrations/openai_agents/utils.py +199 -0
- sentry_sdk/integrations/openfeature.py +35 -0
- sentry_sdk/integrations/opentelemetry/__init__.py +7 -0
- sentry_sdk/integrations/opentelemetry/consts.py +5 -0
- sentry_sdk/integrations/opentelemetry/integration.py +58 -0
- sentry_sdk/integrations/opentelemetry/propagator.py +117 -0
- sentry_sdk/integrations/opentelemetry/span_processor.py +391 -0
- sentry_sdk/integrations/otlp.py +82 -0
- sentry_sdk/integrations/pure_eval.py +141 -0
- sentry_sdk/integrations/pydantic_ai/__init__.py +47 -0
- sentry_sdk/integrations/pydantic_ai/consts.py +1 -0
- sentry_sdk/integrations/pydantic_ai/patches/__init__.py +4 -0
- sentry_sdk/integrations/pydantic_ai/patches/agent_run.py +215 -0
- sentry_sdk/integrations/pydantic_ai/patches/graph_nodes.py +110 -0
- sentry_sdk/integrations/pydantic_ai/patches/model_request.py +40 -0
- sentry_sdk/integrations/pydantic_ai/patches/tools.py +98 -0
- sentry_sdk/integrations/pydantic_ai/spans/__init__.py +3 -0
- sentry_sdk/integrations/pydantic_ai/spans/ai_client.py +246 -0
- sentry_sdk/integrations/pydantic_ai/spans/execute_tool.py +49 -0
- sentry_sdk/integrations/pydantic_ai/spans/invoke_agent.py +112 -0
- sentry_sdk/integrations/pydantic_ai/utils.py +223 -0
- sentry_sdk/integrations/pymongo.py +214 -0
- sentry_sdk/integrations/pyramid.py +112 -68
- sentry_sdk/integrations/quart.py +237 -0
- sentry_sdk/integrations/ray.py +165 -0
- sentry_sdk/integrations/redis/__init__.py +48 -0
- sentry_sdk/integrations/redis/_async_common.py +116 -0
- sentry_sdk/integrations/redis/_sync_common.py +119 -0
- sentry_sdk/integrations/redis/consts.py +19 -0
- sentry_sdk/integrations/redis/modules/__init__.py +0 -0
- sentry_sdk/integrations/redis/modules/caches.py +118 -0
- sentry_sdk/integrations/redis/modules/queries.py +65 -0
- sentry_sdk/integrations/redis/rb.py +32 -0
- sentry_sdk/integrations/redis/redis.py +69 -0
- sentry_sdk/integrations/redis/redis_cluster.py +107 -0
- sentry_sdk/integrations/redis/redis_py_cluster_legacy.py +50 -0
- sentry_sdk/integrations/redis/utils.py +148 -0
- sentry_sdk/integrations/rq.py +95 -37
- sentry_sdk/integrations/rust_tracing.py +284 -0
- sentry_sdk/integrations/sanic.py +294 -123
- sentry_sdk/integrations/serverless.py +48 -19
- sentry_sdk/integrations/socket.py +96 -0
- sentry_sdk/integrations/spark/__init__.py +4 -0
- sentry_sdk/integrations/spark/spark_driver.py +316 -0
- sentry_sdk/integrations/spark/spark_worker.py +116 -0
- sentry_sdk/integrations/sqlalchemy.py +142 -0
- sentry_sdk/integrations/starlette.py +737 -0
- sentry_sdk/integrations/starlite.py +292 -0
- sentry_sdk/integrations/statsig.py +37 -0
- sentry_sdk/integrations/stdlib.py +235 -29
- sentry_sdk/integrations/strawberry.py +394 -0
- sentry_sdk/integrations/sys_exit.py +70 -0
- sentry_sdk/integrations/threading.py +158 -28
- sentry_sdk/integrations/tornado.py +84 -52
- sentry_sdk/integrations/trytond.py +50 -0
- sentry_sdk/integrations/typer.py +60 -0
- sentry_sdk/integrations/unleash.py +33 -0
- sentry_sdk/integrations/unraisablehook.py +53 -0
- sentry_sdk/integrations/wsgi.py +201 -119
- sentry_sdk/logger.py +96 -0
- sentry_sdk/metrics.py +81 -0
- sentry_sdk/monitor.py +120 -0
- sentry_sdk/profiler/__init__.py +49 -0
- sentry_sdk/profiler/continuous_profiler.py +730 -0
- sentry_sdk/profiler/transaction_profiler.py +839 -0
- sentry_sdk/profiler/utils.py +195 -0
- sentry_sdk/py.typed +0 -0
- sentry_sdk/scope.py +1713 -85
- sentry_sdk/scrubber.py +177 -0
- sentry_sdk/serializer.py +405 -0
- sentry_sdk/session.py +177 -0
- sentry_sdk/sessions.py +275 -0
- sentry_sdk/spotlight.py +242 -0
- sentry_sdk/tracing.py +1486 -0
- sentry_sdk/tracing_utils.py +1236 -0
- sentry_sdk/transport.py +806 -134
- sentry_sdk/types.py +52 -0
- sentry_sdk/utils.py +1625 -465
- sentry_sdk/worker.py +54 -25
- sentry_sdk-2.46.0.dist-info/METADATA +268 -0
- sentry_sdk-2.46.0.dist-info/RECORD +189 -0
- {sentry_sdk-0.7.5.dist-info → sentry_sdk-2.46.0.dist-info}/WHEEL +1 -1
- sentry_sdk-2.46.0.dist-info/entry_points.txt +2 -0
- sentry_sdk-2.46.0.dist-info/licenses/LICENSE +21 -0
- sentry_sdk/integrations/celery.py +0 -119
- sentry_sdk-0.7.5.dist-info/LICENSE +0 -9
- sentry_sdk-0.7.5.dist-info/METADATA +0 -36
- sentry_sdk-0.7.5.dist-info/RECORD +0 -39
- {sentry_sdk-0.7.5.dist-info → sentry_sdk-2.46.0.dist-info}/top_level.txt +0 -0
sentry_sdk/tracing.py
ADDED
|
@@ -0,0 +1,1486 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
import warnings
|
|
3
|
+
from datetime import datetime, timedelta, timezone
|
|
4
|
+
from enum import Enum
|
|
5
|
+
|
|
6
|
+
import sentry_sdk
|
|
7
|
+
from sentry_sdk.consts import INSTRUMENTER, SPANSTATUS, SPANDATA, SPANTEMPLATE
|
|
8
|
+
from sentry_sdk.profiler.continuous_profiler import get_profiler_id
|
|
9
|
+
from sentry_sdk.utils import (
|
|
10
|
+
capture_internal_exceptions,
|
|
11
|
+
get_current_thread_meta,
|
|
12
|
+
is_valid_sample_rate,
|
|
13
|
+
logger,
|
|
14
|
+
nanosecond_time,
|
|
15
|
+
should_be_treated_as_error,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
from typing import TYPE_CHECKING
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from collections.abc import Callable, Mapping, MutableMapping
|
|
23
|
+
from typing import Any
|
|
24
|
+
from typing import Dict
|
|
25
|
+
from typing import Iterator
|
|
26
|
+
from typing import List
|
|
27
|
+
from typing import Optional
|
|
28
|
+
from typing import overload
|
|
29
|
+
from typing import ParamSpec
|
|
30
|
+
from typing import Tuple
|
|
31
|
+
from typing import Union
|
|
32
|
+
from typing import TypeVar
|
|
33
|
+
from typing import Set
|
|
34
|
+
|
|
35
|
+
from typing_extensions import TypedDict, Unpack
|
|
36
|
+
|
|
37
|
+
P = ParamSpec("P")
|
|
38
|
+
R = TypeVar("R")
|
|
39
|
+
|
|
40
|
+
from sentry_sdk.profiler.continuous_profiler import ContinuousProfile
|
|
41
|
+
from sentry_sdk.profiler.transaction_profiler import Profile
|
|
42
|
+
from sentry_sdk._types import (
|
|
43
|
+
Event,
|
|
44
|
+
MeasurementUnit,
|
|
45
|
+
SamplingContext,
|
|
46
|
+
MeasurementValue,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
class SpanKwargs(TypedDict, total=False):
|
|
50
|
+
trace_id: str
|
|
51
|
+
"""
|
|
52
|
+
The trace ID of the root span. If this new span is to be the root span,
|
|
53
|
+
omit this parameter, and a new trace ID will be generated.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
span_id: str
|
|
57
|
+
"""The span ID of this span. If omitted, a new span ID will be generated."""
|
|
58
|
+
|
|
59
|
+
parent_span_id: str
|
|
60
|
+
"""The span ID of the parent span, if applicable."""
|
|
61
|
+
|
|
62
|
+
same_process_as_parent: bool
|
|
63
|
+
"""Whether this span is in the same process as the parent span."""
|
|
64
|
+
|
|
65
|
+
sampled: bool
|
|
66
|
+
"""
|
|
67
|
+
Whether the span should be sampled. Overrides the default sampling decision
|
|
68
|
+
for this span when provided.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
op: str
|
|
72
|
+
"""
|
|
73
|
+
The span's operation. A list of recommended values is available here:
|
|
74
|
+
https://develop.sentry.dev/sdk/performance/span-operations/
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
description: str
|
|
78
|
+
"""A description of what operation is being performed within the span. This argument is DEPRECATED. Please use the `name` parameter, instead."""
|
|
79
|
+
|
|
80
|
+
hub: Optional["sentry_sdk.Hub"]
|
|
81
|
+
"""The hub to use for this span. This argument is DEPRECATED. Please use the `scope` parameter, instead."""
|
|
82
|
+
|
|
83
|
+
status: str
|
|
84
|
+
"""The span's status. Possible values are listed at https://develop.sentry.dev/sdk/event-payloads/span/"""
|
|
85
|
+
|
|
86
|
+
containing_transaction: Optional["Transaction"]
|
|
87
|
+
"""The transaction that this span belongs to."""
|
|
88
|
+
|
|
89
|
+
start_timestamp: Optional[Union[datetime, float]]
|
|
90
|
+
"""
|
|
91
|
+
The timestamp when the span started. If omitted, the current time
|
|
92
|
+
will be used.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
scope: "sentry_sdk.Scope"
|
|
96
|
+
"""The scope to use for this span. If not provided, we use the current scope."""
|
|
97
|
+
|
|
98
|
+
origin: str
|
|
99
|
+
"""
|
|
100
|
+
The origin of the span.
|
|
101
|
+
See https://develop.sentry.dev/sdk/performance/trace-origin/
|
|
102
|
+
Default "manual".
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
name: str
|
|
106
|
+
"""A string describing what operation is being performed within the span/transaction."""
|
|
107
|
+
|
|
108
|
+
class TransactionKwargs(SpanKwargs, total=False):
|
|
109
|
+
source: str
|
|
110
|
+
"""
|
|
111
|
+
A string describing the source of the transaction name. This will be used to determine the transaction's type.
|
|
112
|
+
See https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations for more information.
|
|
113
|
+
Default "custom".
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
parent_sampled: bool
|
|
117
|
+
"""Whether the parent transaction was sampled. If True this transaction will be kept, if False it will be discarded."""
|
|
118
|
+
|
|
119
|
+
baggage: "Baggage"
|
|
120
|
+
"""The W3C baggage header value. (see https://www.w3.org/TR/baggage/)"""
|
|
121
|
+
|
|
122
|
+
ProfileContext = TypedDict(
|
|
123
|
+
"ProfileContext",
|
|
124
|
+
{
|
|
125
|
+
"profiler_id": str,
|
|
126
|
+
},
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
BAGGAGE_HEADER_NAME = "baggage"
|
|
130
|
+
SENTRY_TRACE_HEADER_NAME = "sentry-trace"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# Transaction source
|
|
134
|
+
# see https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations
|
|
135
|
+
class TransactionSource(str, Enum):
|
|
136
|
+
COMPONENT = "component"
|
|
137
|
+
CUSTOM = "custom"
|
|
138
|
+
ROUTE = "route"
|
|
139
|
+
TASK = "task"
|
|
140
|
+
URL = "url"
|
|
141
|
+
VIEW = "view"
|
|
142
|
+
|
|
143
|
+
def __str__(self):
|
|
144
|
+
# type: () -> str
|
|
145
|
+
return self.value
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# These are typically high cardinality and the server hates them
|
|
149
|
+
LOW_QUALITY_TRANSACTION_SOURCES = [
|
|
150
|
+
TransactionSource.URL,
|
|
151
|
+
]
|
|
152
|
+
|
|
153
|
+
SOURCE_FOR_STYLE = {
|
|
154
|
+
"endpoint": TransactionSource.COMPONENT,
|
|
155
|
+
"function_name": TransactionSource.COMPONENT,
|
|
156
|
+
"handler_name": TransactionSource.COMPONENT,
|
|
157
|
+
"method_and_path_pattern": TransactionSource.ROUTE,
|
|
158
|
+
"path": TransactionSource.URL,
|
|
159
|
+
"route_name": TransactionSource.COMPONENT,
|
|
160
|
+
"route_pattern": TransactionSource.ROUTE,
|
|
161
|
+
"uri_template": TransactionSource.ROUTE,
|
|
162
|
+
"url": TransactionSource.ROUTE,
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def get_span_status_from_http_code(http_status_code):
|
|
167
|
+
# type: (int) -> str
|
|
168
|
+
"""
|
|
169
|
+
Returns the Sentry status corresponding to the given HTTP status code.
|
|
170
|
+
|
|
171
|
+
See: https://develop.sentry.dev/sdk/event-payloads/contexts/#trace-context
|
|
172
|
+
"""
|
|
173
|
+
if http_status_code < 400:
|
|
174
|
+
return SPANSTATUS.OK
|
|
175
|
+
|
|
176
|
+
elif 400 <= http_status_code < 500:
|
|
177
|
+
if http_status_code == 403:
|
|
178
|
+
return SPANSTATUS.PERMISSION_DENIED
|
|
179
|
+
elif http_status_code == 404:
|
|
180
|
+
return SPANSTATUS.NOT_FOUND
|
|
181
|
+
elif http_status_code == 429:
|
|
182
|
+
return SPANSTATUS.RESOURCE_EXHAUSTED
|
|
183
|
+
elif http_status_code == 413:
|
|
184
|
+
return SPANSTATUS.FAILED_PRECONDITION
|
|
185
|
+
elif http_status_code == 401:
|
|
186
|
+
return SPANSTATUS.UNAUTHENTICATED
|
|
187
|
+
elif http_status_code == 409:
|
|
188
|
+
return SPANSTATUS.ALREADY_EXISTS
|
|
189
|
+
else:
|
|
190
|
+
return SPANSTATUS.INVALID_ARGUMENT
|
|
191
|
+
|
|
192
|
+
elif 500 <= http_status_code < 600:
|
|
193
|
+
if http_status_code == 504:
|
|
194
|
+
return SPANSTATUS.DEADLINE_EXCEEDED
|
|
195
|
+
elif http_status_code == 501:
|
|
196
|
+
return SPANSTATUS.UNIMPLEMENTED
|
|
197
|
+
elif http_status_code == 503:
|
|
198
|
+
return SPANSTATUS.UNAVAILABLE
|
|
199
|
+
else:
|
|
200
|
+
return SPANSTATUS.INTERNAL_ERROR
|
|
201
|
+
|
|
202
|
+
return SPANSTATUS.UNKNOWN_ERROR
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class _SpanRecorder:
|
|
206
|
+
"""Limits the number of spans recorded in a transaction."""
|
|
207
|
+
|
|
208
|
+
__slots__ = ("maxlen", "spans", "dropped_spans")
|
|
209
|
+
|
|
210
|
+
def __init__(self, maxlen):
|
|
211
|
+
# type: (int) -> None
|
|
212
|
+
# FIXME: this is `maxlen - 1` only to preserve historical behavior
|
|
213
|
+
# enforced by tests.
|
|
214
|
+
# Either this should be changed to `maxlen` or the JS SDK implementation
|
|
215
|
+
# should be changed to match a consistent interpretation of what maxlen
|
|
216
|
+
# limits: either transaction+spans or only child spans.
|
|
217
|
+
self.maxlen = maxlen - 1
|
|
218
|
+
self.spans = [] # type: List[Span]
|
|
219
|
+
self.dropped_spans = 0 # type: int
|
|
220
|
+
|
|
221
|
+
def add(self, span):
|
|
222
|
+
# type: (Span) -> None
|
|
223
|
+
if len(self.spans) > self.maxlen:
|
|
224
|
+
span._span_recorder = None
|
|
225
|
+
self.dropped_spans += 1
|
|
226
|
+
else:
|
|
227
|
+
self.spans.append(span)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class Span:
|
|
231
|
+
"""A span holds timing information of a block of code.
|
|
232
|
+
Spans can have multiple child spans thus forming a span tree.
|
|
233
|
+
|
|
234
|
+
:param trace_id: The trace ID of the root span. If this new span is to be the root span,
|
|
235
|
+
omit this parameter, and a new trace ID will be generated.
|
|
236
|
+
:param span_id: The span ID of this span. If omitted, a new span ID will be generated.
|
|
237
|
+
:param parent_span_id: The span ID of the parent span, if applicable.
|
|
238
|
+
:param same_process_as_parent: Whether this span is in the same process as the parent span.
|
|
239
|
+
:param sampled: Whether the span should be sampled. Overrides the default sampling decision
|
|
240
|
+
for this span when provided.
|
|
241
|
+
:param op: The span's operation. A list of recommended values is available here:
|
|
242
|
+
https://develop.sentry.dev/sdk/performance/span-operations/
|
|
243
|
+
:param description: A description of what operation is being performed within the span.
|
|
244
|
+
|
|
245
|
+
.. deprecated:: 2.15.0
|
|
246
|
+
Please use the `name` parameter, instead.
|
|
247
|
+
:param name: A string describing what operation is being performed within the span.
|
|
248
|
+
:param hub: The hub to use for this span.
|
|
249
|
+
|
|
250
|
+
.. deprecated:: 2.0.0
|
|
251
|
+
Please use the `scope` parameter, instead.
|
|
252
|
+
:param status: The span's status. Possible values are listed at
|
|
253
|
+
https://develop.sentry.dev/sdk/event-payloads/span/
|
|
254
|
+
:param containing_transaction: The transaction that this span belongs to.
|
|
255
|
+
:param start_timestamp: The timestamp when the span started. If omitted, the current time
|
|
256
|
+
will be used.
|
|
257
|
+
:param scope: The scope to use for this span. If not provided, we use the current scope.
|
|
258
|
+
"""
|
|
259
|
+
|
|
260
|
+
__slots__ = (
|
|
261
|
+
"_trace_id",
|
|
262
|
+
"_span_id",
|
|
263
|
+
"parent_span_id",
|
|
264
|
+
"same_process_as_parent",
|
|
265
|
+
"sampled",
|
|
266
|
+
"op",
|
|
267
|
+
"description",
|
|
268
|
+
"_measurements",
|
|
269
|
+
"start_timestamp",
|
|
270
|
+
"_start_timestamp_monotonic_ns",
|
|
271
|
+
"status",
|
|
272
|
+
"timestamp",
|
|
273
|
+
"_tags",
|
|
274
|
+
"_data",
|
|
275
|
+
"_span_recorder",
|
|
276
|
+
"hub",
|
|
277
|
+
"_context_manager_state",
|
|
278
|
+
"_containing_transaction",
|
|
279
|
+
"scope",
|
|
280
|
+
"origin",
|
|
281
|
+
"name",
|
|
282
|
+
"_flags",
|
|
283
|
+
"_flags_capacity",
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
def __init__(
|
|
287
|
+
self,
|
|
288
|
+
trace_id=None, # type: Optional[str]
|
|
289
|
+
span_id=None, # type: Optional[str]
|
|
290
|
+
parent_span_id=None, # type: Optional[str]
|
|
291
|
+
same_process_as_parent=True, # type: bool
|
|
292
|
+
sampled=None, # type: Optional[bool]
|
|
293
|
+
op=None, # type: Optional[str]
|
|
294
|
+
description=None, # type: Optional[str]
|
|
295
|
+
hub=None, # type: Optional[sentry_sdk.Hub] # deprecated
|
|
296
|
+
status=None, # type: Optional[str]
|
|
297
|
+
containing_transaction=None, # type: Optional[Transaction]
|
|
298
|
+
start_timestamp=None, # type: Optional[Union[datetime, float]]
|
|
299
|
+
scope=None, # type: Optional[sentry_sdk.Scope]
|
|
300
|
+
origin="manual", # type: str
|
|
301
|
+
name=None, # type: Optional[str]
|
|
302
|
+
):
|
|
303
|
+
# type: (...) -> None
|
|
304
|
+
self._trace_id = trace_id
|
|
305
|
+
self._span_id = span_id
|
|
306
|
+
self.parent_span_id = parent_span_id
|
|
307
|
+
self.same_process_as_parent = same_process_as_parent
|
|
308
|
+
self.sampled = sampled
|
|
309
|
+
self.op = op
|
|
310
|
+
self.description = name or description
|
|
311
|
+
self.status = status
|
|
312
|
+
self.hub = hub # backwards compatibility
|
|
313
|
+
self.scope = scope
|
|
314
|
+
self.origin = origin
|
|
315
|
+
self._measurements = {} # type: Dict[str, MeasurementValue]
|
|
316
|
+
self._tags = {} # type: MutableMapping[str, str]
|
|
317
|
+
self._data = {} # type: Dict[str, Any]
|
|
318
|
+
self._containing_transaction = containing_transaction
|
|
319
|
+
self._flags = {} # type: Dict[str, bool]
|
|
320
|
+
self._flags_capacity = 10
|
|
321
|
+
|
|
322
|
+
if hub is not None:
|
|
323
|
+
warnings.warn(
|
|
324
|
+
"The `hub` parameter is deprecated. Please use `scope` instead.",
|
|
325
|
+
DeprecationWarning,
|
|
326
|
+
stacklevel=2,
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
self.scope = self.scope or hub.scope
|
|
330
|
+
|
|
331
|
+
if start_timestamp is None:
|
|
332
|
+
start_timestamp = datetime.now(timezone.utc)
|
|
333
|
+
elif isinstance(start_timestamp, float):
|
|
334
|
+
start_timestamp = datetime.fromtimestamp(start_timestamp, timezone.utc)
|
|
335
|
+
self.start_timestamp = start_timestamp
|
|
336
|
+
try:
|
|
337
|
+
# profiling depends on this value and requires that
|
|
338
|
+
# it is measured in nanoseconds
|
|
339
|
+
self._start_timestamp_monotonic_ns = nanosecond_time()
|
|
340
|
+
except AttributeError:
|
|
341
|
+
pass
|
|
342
|
+
|
|
343
|
+
#: End timestamp of span
|
|
344
|
+
self.timestamp = None # type: Optional[datetime]
|
|
345
|
+
|
|
346
|
+
self._span_recorder = None # type: Optional[_SpanRecorder]
|
|
347
|
+
|
|
348
|
+
self.update_active_thread()
|
|
349
|
+
self.set_profiler_id(get_profiler_id())
|
|
350
|
+
|
|
351
|
+
# TODO this should really live on the Transaction class rather than the Span
|
|
352
|
+
# class
|
|
353
|
+
def init_span_recorder(self, maxlen):
|
|
354
|
+
# type: (int) -> None
|
|
355
|
+
if self._span_recorder is None:
|
|
356
|
+
self._span_recorder = _SpanRecorder(maxlen)
|
|
357
|
+
|
|
358
|
+
@property
|
|
359
|
+
def trace_id(self):
|
|
360
|
+
# type: () -> str
|
|
361
|
+
if not self._trace_id:
|
|
362
|
+
self._trace_id = uuid.uuid4().hex
|
|
363
|
+
|
|
364
|
+
return self._trace_id
|
|
365
|
+
|
|
366
|
+
@trace_id.setter
|
|
367
|
+
def trace_id(self, value):
|
|
368
|
+
# type: (str) -> None
|
|
369
|
+
self._trace_id = value
|
|
370
|
+
|
|
371
|
+
@property
|
|
372
|
+
def span_id(self):
|
|
373
|
+
# type: () -> str
|
|
374
|
+
if not self._span_id:
|
|
375
|
+
self._span_id = uuid.uuid4().hex[16:]
|
|
376
|
+
|
|
377
|
+
return self._span_id
|
|
378
|
+
|
|
379
|
+
@span_id.setter
|
|
380
|
+
def span_id(self, value):
|
|
381
|
+
# type: (str) -> None
|
|
382
|
+
self._span_id = value
|
|
383
|
+
|
|
384
|
+
def __repr__(self):
|
|
385
|
+
# type: () -> str
|
|
386
|
+
return (
|
|
387
|
+
"<%s(op=%r, description:%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r, origin=%r)>"
|
|
388
|
+
% (
|
|
389
|
+
self.__class__.__name__,
|
|
390
|
+
self.op,
|
|
391
|
+
self.description,
|
|
392
|
+
self.trace_id,
|
|
393
|
+
self.span_id,
|
|
394
|
+
self.parent_span_id,
|
|
395
|
+
self.sampled,
|
|
396
|
+
self.origin,
|
|
397
|
+
)
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
def __enter__(self):
|
|
401
|
+
# type: () -> Span
|
|
402
|
+
scope = self.scope or sentry_sdk.get_current_scope()
|
|
403
|
+
old_span = scope.span
|
|
404
|
+
scope.span = self
|
|
405
|
+
self._context_manager_state = (scope, old_span)
|
|
406
|
+
return self
|
|
407
|
+
|
|
408
|
+
def __exit__(self, ty, value, tb):
|
|
409
|
+
# type: (Optional[Any], Optional[Any], Optional[Any]) -> None
|
|
410
|
+
if value is not None and should_be_treated_as_error(ty, value):
|
|
411
|
+
if self.status != SPANSTATUS.ERROR:
|
|
412
|
+
self.set_status(SPANSTATUS.INTERNAL_ERROR)
|
|
413
|
+
|
|
414
|
+
with capture_internal_exceptions():
|
|
415
|
+
scope, old_span = self._context_manager_state
|
|
416
|
+
del self._context_manager_state
|
|
417
|
+
self.finish(scope)
|
|
418
|
+
scope.span = old_span
|
|
419
|
+
|
|
420
|
+
@property
|
|
421
|
+
def containing_transaction(self):
|
|
422
|
+
# type: () -> Optional[Transaction]
|
|
423
|
+
"""The ``Transaction`` that this span belongs to.
|
|
424
|
+
The ``Transaction`` is the root of the span tree,
|
|
425
|
+
so one could also think of this ``Transaction`` as the "root span"."""
|
|
426
|
+
|
|
427
|
+
# this is a getter rather than a regular attribute so that transactions
|
|
428
|
+
# can return `self` here instead (as a way to prevent them circularly
|
|
429
|
+
# referencing themselves)
|
|
430
|
+
return self._containing_transaction
|
|
431
|
+
|
|
432
|
+
def start_child(self, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
|
|
433
|
+
# type: (str, **Any) -> Span
|
|
434
|
+
"""
|
|
435
|
+
Start a sub-span from the current span or transaction.
|
|
436
|
+
|
|
437
|
+
Takes the same arguments as the initializer of :py:class:`Span`. The
|
|
438
|
+
trace id, sampling decision, transaction pointer, and span recorder are
|
|
439
|
+
inherited from the current span/transaction.
|
|
440
|
+
|
|
441
|
+
The instrumenter parameter is deprecated for user code, and it will
|
|
442
|
+
be removed in the next major version. Going forward, it should only
|
|
443
|
+
be used by the SDK itself.
|
|
444
|
+
"""
|
|
445
|
+
if kwargs.get("description") is not None:
|
|
446
|
+
warnings.warn(
|
|
447
|
+
"The `description` parameter is deprecated. Please use `name` instead.",
|
|
448
|
+
DeprecationWarning,
|
|
449
|
+
stacklevel=2,
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
configuration_instrumenter = sentry_sdk.get_client().options["instrumenter"]
|
|
453
|
+
|
|
454
|
+
if instrumenter != configuration_instrumenter:
|
|
455
|
+
return NoOpSpan()
|
|
456
|
+
|
|
457
|
+
kwargs.setdefault("sampled", self.sampled)
|
|
458
|
+
|
|
459
|
+
child = Span(
|
|
460
|
+
trace_id=self.trace_id,
|
|
461
|
+
parent_span_id=self.span_id,
|
|
462
|
+
containing_transaction=self.containing_transaction,
|
|
463
|
+
**kwargs,
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
span_recorder = (
|
|
467
|
+
self.containing_transaction and self.containing_transaction._span_recorder
|
|
468
|
+
)
|
|
469
|
+
if span_recorder:
|
|
470
|
+
span_recorder.add(child)
|
|
471
|
+
|
|
472
|
+
return child
|
|
473
|
+
|
|
474
|
+
@classmethod
|
|
475
|
+
def continue_from_environ(
|
|
476
|
+
cls,
|
|
477
|
+
environ, # type: Mapping[str, str]
|
|
478
|
+
**kwargs, # type: Any
|
|
479
|
+
):
|
|
480
|
+
# type: (...) -> Transaction
|
|
481
|
+
"""
|
|
482
|
+
Create a Transaction with the given params, then add in data pulled from
|
|
483
|
+
the ``sentry-trace`` and ``baggage`` headers from the environ (if any)
|
|
484
|
+
before returning the Transaction.
|
|
485
|
+
|
|
486
|
+
This is different from :py:meth:`~sentry_sdk.tracing.Span.continue_from_headers`
|
|
487
|
+
in that it assumes header names in the form ``HTTP_HEADER_NAME`` -
|
|
488
|
+
such as you would get from a WSGI/ASGI environ -
|
|
489
|
+
rather than the form ``header-name``.
|
|
490
|
+
|
|
491
|
+
:param environ: The ASGI/WSGI environ to pull information from.
|
|
492
|
+
"""
|
|
493
|
+
if cls is Span:
|
|
494
|
+
logger.warning(
|
|
495
|
+
"Deprecated: use Transaction.continue_from_environ "
|
|
496
|
+
"instead of Span.continue_from_environ."
|
|
497
|
+
)
|
|
498
|
+
return Transaction.continue_from_headers(EnvironHeaders(environ), **kwargs)
|
|
499
|
+
|
|
500
|
+
@classmethod
|
|
501
|
+
def continue_from_headers(
|
|
502
|
+
cls,
|
|
503
|
+
headers, # type: Mapping[str, str]
|
|
504
|
+
*,
|
|
505
|
+
_sample_rand=None, # type: Optional[str]
|
|
506
|
+
**kwargs, # type: Any
|
|
507
|
+
):
|
|
508
|
+
# type: (...) -> Transaction
|
|
509
|
+
"""
|
|
510
|
+
Create a transaction with the given params (including any data pulled from
|
|
511
|
+
the ``sentry-trace`` and ``baggage`` headers).
|
|
512
|
+
|
|
513
|
+
:param headers: The dictionary with the HTTP headers to pull information from.
|
|
514
|
+
:param _sample_rand: If provided, we override the sample_rand value from the
|
|
515
|
+
incoming headers with this value. (internal use only)
|
|
516
|
+
"""
|
|
517
|
+
# TODO move this to the Transaction class
|
|
518
|
+
if cls is Span:
|
|
519
|
+
logger.warning(
|
|
520
|
+
"Deprecated: use Transaction.continue_from_headers "
|
|
521
|
+
"instead of Span.continue_from_headers."
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
# TODO-neel move away from this kwargs stuff, it's confusing and opaque
|
|
525
|
+
# make more explicit
|
|
526
|
+
baggage = Baggage.from_incoming_header(
|
|
527
|
+
headers.get(BAGGAGE_HEADER_NAME), _sample_rand=_sample_rand
|
|
528
|
+
)
|
|
529
|
+
kwargs.update({BAGGAGE_HEADER_NAME: baggage})
|
|
530
|
+
|
|
531
|
+
sentrytrace_kwargs = extract_sentrytrace_data(
|
|
532
|
+
headers.get(SENTRY_TRACE_HEADER_NAME)
|
|
533
|
+
)
|
|
534
|
+
|
|
535
|
+
if sentrytrace_kwargs is not None:
|
|
536
|
+
kwargs.update(sentrytrace_kwargs)
|
|
537
|
+
|
|
538
|
+
# If there's an incoming sentry-trace but no incoming baggage header,
|
|
539
|
+
# for instance in traces coming from older SDKs,
|
|
540
|
+
# baggage will be empty and immutable and won't be populated as head SDK.
|
|
541
|
+
baggage.freeze()
|
|
542
|
+
|
|
543
|
+
transaction = Transaction(**kwargs)
|
|
544
|
+
transaction.same_process_as_parent = False
|
|
545
|
+
|
|
546
|
+
return transaction
|
|
547
|
+
|
|
548
|
+
def iter_headers(self):
|
|
549
|
+
# type: () -> Iterator[Tuple[str, str]]
|
|
550
|
+
"""
|
|
551
|
+
Creates a generator which returns the span's ``sentry-trace`` and ``baggage`` headers.
|
|
552
|
+
If the span's containing transaction doesn't yet have a ``baggage`` value,
|
|
553
|
+
this will cause one to be generated and stored.
|
|
554
|
+
"""
|
|
555
|
+
if not self.containing_transaction:
|
|
556
|
+
# Do not propagate headers if there is no containing transaction. Otherwise, this
|
|
557
|
+
# span ends up being the root span of a new trace, and since it does not get sent
|
|
558
|
+
# to Sentry, the trace will be missing a root transaction. The dynamic sampling
|
|
559
|
+
# context will also be missing, breaking dynamic sampling & traces.
|
|
560
|
+
return
|
|
561
|
+
|
|
562
|
+
yield SENTRY_TRACE_HEADER_NAME, self.to_traceparent()
|
|
563
|
+
|
|
564
|
+
baggage = self.containing_transaction.get_baggage().serialize()
|
|
565
|
+
if baggage:
|
|
566
|
+
yield BAGGAGE_HEADER_NAME, baggage
|
|
567
|
+
|
|
568
|
+
@classmethod
|
|
569
|
+
def from_traceparent(
|
|
570
|
+
cls,
|
|
571
|
+
traceparent, # type: Optional[str]
|
|
572
|
+
**kwargs, # type: Any
|
|
573
|
+
):
|
|
574
|
+
# type: (...) -> Optional[Transaction]
|
|
575
|
+
"""
|
|
576
|
+
DEPRECATED: Use :py:meth:`sentry_sdk.tracing.Span.continue_from_headers`.
|
|
577
|
+
|
|
578
|
+
Create a ``Transaction`` with the given params, then add in data pulled from
|
|
579
|
+
the given ``sentry-trace`` header value before returning the ``Transaction``.
|
|
580
|
+
"""
|
|
581
|
+
logger.warning(
|
|
582
|
+
"Deprecated: Use Transaction.continue_from_headers(headers, **kwargs) "
|
|
583
|
+
"instead of from_traceparent(traceparent, **kwargs)"
|
|
584
|
+
)
|
|
585
|
+
|
|
586
|
+
if not traceparent:
|
|
587
|
+
return None
|
|
588
|
+
|
|
589
|
+
return cls.continue_from_headers(
|
|
590
|
+
{SENTRY_TRACE_HEADER_NAME: traceparent}, **kwargs
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
def to_traceparent(self):
|
|
594
|
+
# type: () -> str
|
|
595
|
+
if self.sampled is True:
|
|
596
|
+
sampled = "1"
|
|
597
|
+
elif self.sampled is False:
|
|
598
|
+
sampled = "0"
|
|
599
|
+
else:
|
|
600
|
+
sampled = None
|
|
601
|
+
|
|
602
|
+
traceparent = "%s-%s" % (self.trace_id, self.span_id)
|
|
603
|
+
if sampled is not None:
|
|
604
|
+
traceparent += "-%s" % (sampled,)
|
|
605
|
+
|
|
606
|
+
return traceparent
|
|
607
|
+
|
|
608
|
+
def to_baggage(self):
|
|
609
|
+
# type: () -> Optional[Baggage]
|
|
610
|
+
"""Returns the :py:class:`~sentry_sdk.tracing_utils.Baggage`
|
|
611
|
+
associated with this ``Span``, if any. (Taken from the root of the span tree.)
|
|
612
|
+
"""
|
|
613
|
+
if self.containing_transaction:
|
|
614
|
+
return self.containing_transaction.get_baggage()
|
|
615
|
+
return None
|
|
616
|
+
|
|
617
|
+
def set_tag(self, key, value):
|
|
618
|
+
# type: (str, Any) -> None
|
|
619
|
+
self._tags[key] = value
|
|
620
|
+
|
|
621
|
+
def set_data(self, key, value):
|
|
622
|
+
# type: (str, Any) -> None
|
|
623
|
+
self._data[key] = value
|
|
624
|
+
|
|
625
|
+
def update_data(self, data):
|
|
626
|
+
# type: (Dict[str, Any]) -> None
|
|
627
|
+
self._data.update(data)
|
|
628
|
+
|
|
629
|
+
def set_flag(self, flag, result):
|
|
630
|
+
# type: (str, bool) -> None
|
|
631
|
+
if len(self._flags) < self._flags_capacity:
|
|
632
|
+
self._flags[flag] = result
|
|
633
|
+
|
|
634
|
+
def set_status(self, value):
|
|
635
|
+
# type: (str) -> None
|
|
636
|
+
self.status = value
|
|
637
|
+
|
|
638
|
+
def set_measurement(self, name, value, unit=""):
|
|
639
|
+
# type: (str, float, MeasurementUnit) -> None
|
|
640
|
+
"""
|
|
641
|
+
.. deprecated:: 2.28.0
|
|
642
|
+
This function is deprecated and will be removed in the next major release.
|
|
643
|
+
"""
|
|
644
|
+
|
|
645
|
+
warnings.warn(
|
|
646
|
+
"`set_measurement()` is deprecated and will be removed in the next major version. Please use `set_data()` instead.",
|
|
647
|
+
DeprecationWarning,
|
|
648
|
+
stacklevel=2,
|
|
649
|
+
)
|
|
650
|
+
self._measurements[name] = {"value": value, "unit": unit}
|
|
651
|
+
|
|
652
|
+
def set_thread(self, thread_id, thread_name):
|
|
653
|
+
# type: (Optional[int], Optional[str]) -> None
|
|
654
|
+
|
|
655
|
+
if thread_id is not None:
|
|
656
|
+
self.set_data(SPANDATA.THREAD_ID, str(thread_id))
|
|
657
|
+
|
|
658
|
+
if thread_name is not None:
|
|
659
|
+
self.set_data(SPANDATA.THREAD_NAME, thread_name)
|
|
660
|
+
|
|
661
|
+
def set_profiler_id(self, profiler_id):
|
|
662
|
+
# type: (Optional[str]) -> None
|
|
663
|
+
if profiler_id is not None:
|
|
664
|
+
self.set_data(SPANDATA.PROFILER_ID, profiler_id)
|
|
665
|
+
|
|
666
|
+
def set_http_status(self, http_status):
|
|
667
|
+
# type: (int) -> None
|
|
668
|
+
self.set_tag(
|
|
669
|
+
"http.status_code", str(http_status)
|
|
670
|
+
) # we keep this for backwards compatibility
|
|
671
|
+
self.set_data(SPANDATA.HTTP_STATUS_CODE, http_status)
|
|
672
|
+
self.set_status(get_span_status_from_http_code(http_status))
|
|
673
|
+
|
|
674
|
+
def is_success(self):
|
|
675
|
+
# type: () -> bool
|
|
676
|
+
return self.status == "ok"
|
|
677
|
+
|
|
678
|
+
def finish(self, scope=None, end_timestamp=None):
|
|
679
|
+
# type: (Optional[sentry_sdk.Scope], Optional[Union[float, datetime]]) -> Optional[str]
|
|
680
|
+
"""
|
|
681
|
+
Sets the end timestamp of the span.
|
|
682
|
+
|
|
683
|
+
Additionally it also creates a breadcrumb from the span,
|
|
684
|
+
if the span represents a database or HTTP request.
|
|
685
|
+
|
|
686
|
+
:param scope: The scope to use for this transaction.
|
|
687
|
+
If not provided, the current scope will be used.
|
|
688
|
+
:param end_timestamp: Optional timestamp that should
|
|
689
|
+
be used as timestamp instead of the current time.
|
|
690
|
+
|
|
691
|
+
:return: Always ``None``. The type is ``Optional[str]`` to match
|
|
692
|
+
the return value of :py:meth:`sentry_sdk.tracing.Transaction.finish`.
|
|
693
|
+
"""
|
|
694
|
+
if self.timestamp is not None:
|
|
695
|
+
# This span is already finished, ignore.
|
|
696
|
+
return None
|
|
697
|
+
|
|
698
|
+
try:
|
|
699
|
+
if end_timestamp:
|
|
700
|
+
if isinstance(end_timestamp, float):
|
|
701
|
+
end_timestamp = datetime.fromtimestamp(end_timestamp, timezone.utc)
|
|
702
|
+
self.timestamp = end_timestamp
|
|
703
|
+
else:
|
|
704
|
+
elapsed = nanosecond_time() - self._start_timestamp_monotonic_ns
|
|
705
|
+
self.timestamp = self.start_timestamp + timedelta(
|
|
706
|
+
microseconds=elapsed / 1000
|
|
707
|
+
)
|
|
708
|
+
except AttributeError:
|
|
709
|
+
self.timestamp = datetime.now(timezone.utc)
|
|
710
|
+
|
|
711
|
+
scope = scope or sentry_sdk.get_current_scope()
|
|
712
|
+
maybe_create_breadcrumbs_from_span(scope, self)
|
|
713
|
+
|
|
714
|
+
return None
|
|
715
|
+
|
|
716
|
+
def to_json(self):
|
|
717
|
+
# type: () -> Dict[str, Any]
|
|
718
|
+
"""Returns a JSON-compatible representation of the span."""
|
|
719
|
+
|
|
720
|
+
rv = {
|
|
721
|
+
"trace_id": self.trace_id,
|
|
722
|
+
"span_id": self.span_id,
|
|
723
|
+
"parent_span_id": self.parent_span_id,
|
|
724
|
+
"same_process_as_parent": self.same_process_as_parent,
|
|
725
|
+
"op": self.op,
|
|
726
|
+
"description": self.description,
|
|
727
|
+
"start_timestamp": self.start_timestamp,
|
|
728
|
+
"timestamp": self.timestamp,
|
|
729
|
+
"origin": self.origin,
|
|
730
|
+
} # type: Dict[str, Any]
|
|
731
|
+
|
|
732
|
+
if self.status:
|
|
733
|
+
self._tags["status"] = self.status
|
|
734
|
+
|
|
735
|
+
if len(self._measurements) > 0:
|
|
736
|
+
rv["measurements"] = self._measurements
|
|
737
|
+
|
|
738
|
+
tags = self._tags
|
|
739
|
+
if tags:
|
|
740
|
+
rv["tags"] = tags
|
|
741
|
+
|
|
742
|
+
data = {}
|
|
743
|
+
data.update(self._flags)
|
|
744
|
+
data.update(self._data)
|
|
745
|
+
if data:
|
|
746
|
+
rv["data"] = data
|
|
747
|
+
|
|
748
|
+
return rv
|
|
749
|
+
|
|
750
|
+
def get_trace_context(self):
|
|
751
|
+
# type: () -> Any
|
|
752
|
+
rv = {
|
|
753
|
+
"trace_id": self.trace_id,
|
|
754
|
+
"span_id": self.span_id,
|
|
755
|
+
"parent_span_id": self.parent_span_id,
|
|
756
|
+
"op": self.op,
|
|
757
|
+
"description": self.description,
|
|
758
|
+
"origin": self.origin,
|
|
759
|
+
} # type: Dict[str, Any]
|
|
760
|
+
if self.status:
|
|
761
|
+
rv["status"] = self.status
|
|
762
|
+
|
|
763
|
+
if self.containing_transaction:
|
|
764
|
+
rv["dynamic_sampling_context"] = (
|
|
765
|
+
self.containing_transaction.get_baggage().dynamic_sampling_context()
|
|
766
|
+
)
|
|
767
|
+
|
|
768
|
+
data = {}
|
|
769
|
+
|
|
770
|
+
thread_id = self._data.get(SPANDATA.THREAD_ID)
|
|
771
|
+
if thread_id is not None:
|
|
772
|
+
data["thread.id"] = thread_id
|
|
773
|
+
|
|
774
|
+
thread_name = self._data.get(SPANDATA.THREAD_NAME)
|
|
775
|
+
if thread_name is not None:
|
|
776
|
+
data["thread.name"] = thread_name
|
|
777
|
+
|
|
778
|
+
if data:
|
|
779
|
+
rv["data"] = data
|
|
780
|
+
|
|
781
|
+
return rv
|
|
782
|
+
|
|
783
|
+
def get_profile_context(self):
|
|
784
|
+
# type: () -> Optional[ProfileContext]
|
|
785
|
+
profiler_id = self._data.get(SPANDATA.PROFILER_ID)
|
|
786
|
+
if profiler_id is None:
|
|
787
|
+
return None
|
|
788
|
+
|
|
789
|
+
return {
|
|
790
|
+
"profiler_id": profiler_id,
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
def update_active_thread(self):
|
|
794
|
+
# type: () -> None
|
|
795
|
+
thread_id, thread_name = get_current_thread_meta()
|
|
796
|
+
self.set_thread(thread_id, thread_name)
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
class Transaction(Span):
|
|
800
|
+
"""The Transaction is the root element that holds all the spans
|
|
801
|
+
for Sentry performance instrumentation.
|
|
802
|
+
|
|
803
|
+
:param name: Identifier of the transaction.
|
|
804
|
+
Will show up in the Sentry UI.
|
|
805
|
+
:param parent_sampled: Whether the parent transaction was sampled.
|
|
806
|
+
If True this transaction will be kept, if False it will be discarded.
|
|
807
|
+
:param baggage: The W3C baggage header value.
|
|
808
|
+
(see https://www.w3.org/TR/baggage/)
|
|
809
|
+
:param source: A string describing the source of the transaction name.
|
|
810
|
+
This will be used to determine the transaction's type.
|
|
811
|
+
See https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations
|
|
812
|
+
for more information. Default "custom".
|
|
813
|
+
:param kwargs: Additional arguments to be passed to the Span constructor.
|
|
814
|
+
See :py:class:`sentry_sdk.tracing.Span` for available arguments.
|
|
815
|
+
"""
|
|
816
|
+
|
|
817
|
+
__slots__ = (
|
|
818
|
+
"name",
|
|
819
|
+
"source",
|
|
820
|
+
"parent_sampled",
|
|
821
|
+
# used to create baggage value for head SDKs in dynamic sampling
|
|
822
|
+
"sample_rate",
|
|
823
|
+
"_measurements",
|
|
824
|
+
"_contexts",
|
|
825
|
+
"_profile",
|
|
826
|
+
"_continuous_profile",
|
|
827
|
+
"_baggage",
|
|
828
|
+
"_sample_rand",
|
|
829
|
+
)
|
|
830
|
+
|
|
831
|
+
def __init__( # type: ignore[misc]
|
|
832
|
+
self,
|
|
833
|
+
name="", # type: str
|
|
834
|
+
parent_sampled=None, # type: Optional[bool]
|
|
835
|
+
baggage=None, # type: Optional[Baggage]
|
|
836
|
+
source=TransactionSource.CUSTOM, # type: str
|
|
837
|
+
**kwargs, # type: Unpack[SpanKwargs]
|
|
838
|
+
):
|
|
839
|
+
# type: (...) -> None
|
|
840
|
+
super().__init__(**kwargs)
|
|
841
|
+
|
|
842
|
+
self.name = name
|
|
843
|
+
self.source = source
|
|
844
|
+
self.sample_rate = None # type: Optional[float]
|
|
845
|
+
self.parent_sampled = parent_sampled
|
|
846
|
+
self._measurements = {} # type: Dict[str, MeasurementValue]
|
|
847
|
+
self._contexts = {} # type: Dict[str, Any]
|
|
848
|
+
self._profile = None # type: Optional[Profile]
|
|
849
|
+
self._continuous_profile = None # type: Optional[ContinuousProfile]
|
|
850
|
+
self._baggage = baggage
|
|
851
|
+
|
|
852
|
+
baggage_sample_rand = (
|
|
853
|
+
None if self._baggage is None else self._baggage._sample_rand()
|
|
854
|
+
)
|
|
855
|
+
if baggage_sample_rand is not None:
|
|
856
|
+
self._sample_rand = baggage_sample_rand
|
|
857
|
+
else:
|
|
858
|
+
self._sample_rand = _generate_sample_rand(self.trace_id)
|
|
859
|
+
|
|
860
|
+
def __repr__(self):
|
|
861
|
+
# type: () -> str
|
|
862
|
+
return (
|
|
863
|
+
"<%s(name=%r, op=%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r, source=%r, origin=%r)>"
|
|
864
|
+
% (
|
|
865
|
+
self.__class__.__name__,
|
|
866
|
+
self.name,
|
|
867
|
+
self.op,
|
|
868
|
+
self.trace_id,
|
|
869
|
+
self.span_id,
|
|
870
|
+
self.parent_span_id,
|
|
871
|
+
self.sampled,
|
|
872
|
+
self.source,
|
|
873
|
+
self.origin,
|
|
874
|
+
)
|
|
875
|
+
)
|
|
876
|
+
|
|
877
|
+
def _possibly_started(self):
|
|
878
|
+
# type: () -> bool
|
|
879
|
+
"""Returns whether the transaction might have been started.
|
|
880
|
+
|
|
881
|
+
If this returns False, we know that the transaction was not started
|
|
882
|
+
with sentry_sdk.start_transaction, and therefore the transaction will
|
|
883
|
+
be discarded.
|
|
884
|
+
"""
|
|
885
|
+
|
|
886
|
+
# We must explicitly check self.sampled is False since self.sampled can be None
|
|
887
|
+
return self._span_recorder is not None or self.sampled is False
|
|
888
|
+
|
|
889
|
+
def __enter__(self):
|
|
890
|
+
# type: () -> Transaction
|
|
891
|
+
if not self._possibly_started():
|
|
892
|
+
logger.debug(
|
|
893
|
+
"Transaction was entered without being started with sentry_sdk.start_transaction."
|
|
894
|
+
"The transaction will not be sent to Sentry. To fix, start the transaction by"
|
|
895
|
+
"passing it to sentry_sdk.start_transaction."
|
|
896
|
+
)
|
|
897
|
+
|
|
898
|
+
super().__enter__()
|
|
899
|
+
|
|
900
|
+
if self._profile is not None:
|
|
901
|
+
self._profile.__enter__()
|
|
902
|
+
|
|
903
|
+
return self
|
|
904
|
+
|
|
905
|
+
def __exit__(self, ty, value, tb):
|
|
906
|
+
# type: (Optional[Any], Optional[Any], Optional[Any]) -> None
|
|
907
|
+
if self._profile is not None:
|
|
908
|
+
self._profile.__exit__(ty, value, tb)
|
|
909
|
+
|
|
910
|
+
if self._continuous_profile is not None:
|
|
911
|
+
self._continuous_profile.stop()
|
|
912
|
+
|
|
913
|
+
super().__exit__(ty, value, tb)
|
|
914
|
+
|
|
915
|
+
@property
|
|
916
|
+
def containing_transaction(self):
|
|
917
|
+
# type: () -> Transaction
|
|
918
|
+
"""The root element of the span tree.
|
|
919
|
+
In the case of a transaction it is the transaction itself.
|
|
920
|
+
"""
|
|
921
|
+
|
|
922
|
+
# Transactions (as spans) belong to themselves (as transactions). This
|
|
923
|
+
# is a getter rather than a regular attribute to avoid having a circular
|
|
924
|
+
# reference.
|
|
925
|
+
return self
|
|
926
|
+
|
|
927
|
+
def _get_scope_from_finish_args(
|
|
928
|
+
self,
|
|
929
|
+
scope_arg, # type: Optional[Union[sentry_sdk.Scope, sentry_sdk.Hub]]
|
|
930
|
+
hub_arg, # type: Optional[Union[sentry_sdk.Scope, sentry_sdk.Hub]]
|
|
931
|
+
):
|
|
932
|
+
# type: (...) -> Optional[sentry_sdk.Scope]
|
|
933
|
+
"""
|
|
934
|
+
Logic to get the scope from the arguments passed to finish. This
|
|
935
|
+
function exists for backwards compatibility with the old finish.
|
|
936
|
+
|
|
937
|
+
TODO: Remove this function in the next major version.
|
|
938
|
+
"""
|
|
939
|
+
scope_or_hub = scope_arg
|
|
940
|
+
if hub_arg is not None:
|
|
941
|
+
warnings.warn(
|
|
942
|
+
"The `hub` parameter is deprecated. Please use the `scope` parameter, instead.",
|
|
943
|
+
DeprecationWarning,
|
|
944
|
+
stacklevel=3,
|
|
945
|
+
)
|
|
946
|
+
|
|
947
|
+
scope_or_hub = hub_arg
|
|
948
|
+
|
|
949
|
+
if isinstance(scope_or_hub, sentry_sdk.Hub):
|
|
950
|
+
warnings.warn(
|
|
951
|
+
"Passing a Hub to finish is deprecated. Please pass a Scope, instead.",
|
|
952
|
+
DeprecationWarning,
|
|
953
|
+
stacklevel=3,
|
|
954
|
+
)
|
|
955
|
+
|
|
956
|
+
return scope_or_hub.scope
|
|
957
|
+
|
|
958
|
+
return scope_or_hub
|
|
959
|
+
|
|
960
|
+
def _get_log_representation(self):
|
|
961
|
+
# type: () -> str
|
|
962
|
+
return "{op}transaction <{name}>".format(
|
|
963
|
+
op=("<" + self.op + "> " if self.op else ""), name=self.name
|
|
964
|
+
)
|
|
965
|
+
|
|
966
|
+
def finish(
|
|
967
|
+
self,
|
|
968
|
+
scope=None, # type: Optional[sentry_sdk.Scope]
|
|
969
|
+
end_timestamp=None, # type: Optional[Union[float, datetime]]
|
|
970
|
+
*,
|
|
971
|
+
hub=None, # type: Optional[sentry_sdk.Hub]
|
|
972
|
+
):
|
|
973
|
+
# type: (...) -> Optional[str]
|
|
974
|
+
"""Finishes the transaction and sends it to Sentry.
|
|
975
|
+
All finished spans in the transaction will also be sent to Sentry.
|
|
976
|
+
|
|
977
|
+
:param scope: The Scope to use for this transaction.
|
|
978
|
+
If not provided, the current Scope will be used.
|
|
979
|
+
:param end_timestamp: Optional timestamp that should
|
|
980
|
+
be used as timestamp instead of the current time.
|
|
981
|
+
:param hub: The hub to use for this transaction.
|
|
982
|
+
This argument is DEPRECATED. Please use the `scope`
|
|
983
|
+
parameter, instead.
|
|
984
|
+
|
|
985
|
+
:return: The event ID if the transaction was sent to Sentry,
|
|
986
|
+
otherwise None.
|
|
987
|
+
"""
|
|
988
|
+
if self.timestamp is not None:
|
|
989
|
+
# This transaction is already finished, ignore.
|
|
990
|
+
return None
|
|
991
|
+
|
|
992
|
+
# For backwards compatibility, we must handle the case where `scope`
|
|
993
|
+
# or `hub` could both either be a `Scope` or a `Hub`.
|
|
994
|
+
scope = self._get_scope_from_finish_args(scope, hub) # type: Optional[sentry_sdk.Scope]
|
|
995
|
+
|
|
996
|
+
scope = scope or self.scope or sentry_sdk.get_current_scope()
|
|
997
|
+
client = sentry_sdk.get_client()
|
|
998
|
+
|
|
999
|
+
if not client.is_active():
|
|
1000
|
+
# We have no active client and therefore nowhere to send this transaction.
|
|
1001
|
+
return None
|
|
1002
|
+
|
|
1003
|
+
if self._span_recorder is None:
|
|
1004
|
+
# Explicit check against False needed because self.sampled might be None
|
|
1005
|
+
if self.sampled is False:
|
|
1006
|
+
logger.debug("Discarding transaction because sampled = False")
|
|
1007
|
+
else:
|
|
1008
|
+
logger.debug(
|
|
1009
|
+
"Discarding transaction because it was not started with sentry_sdk.start_transaction"
|
|
1010
|
+
)
|
|
1011
|
+
|
|
1012
|
+
# This is not entirely accurate because discards here are not
|
|
1013
|
+
# exclusively based on sample rate but also traces sampler, but
|
|
1014
|
+
# we handle this the same here.
|
|
1015
|
+
if client.transport and has_tracing_enabled(client.options):
|
|
1016
|
+
if client.monitor and client.monitor.downsample_factor > 0:
|
|
1017
|
+
reason = "backpressure"
|
|
1018
|
+
else:
|
|
1019
|
+
reason = "sample_rate"
|
|
1020
|
+
|
|
1021
|
+
client.transport.record_lost_event(reason, data_category="transaction")
|
|
1022
|
+
|
|
1023
|
+
# Only one span (the transaction itself) is discarded, since we did not record any spans here.
|
|
1024
|
+
client.transport.record_lost_event(reason, data_category="span")
|
|
1025
|
+
return None
|
|
1026
|
+
|
|
1027
|
+
if not self.name:
|
|
1028
|
+
logger.warning(
|
|
1029
|
+
"Transaction has no name, falling back to `<unlabeled transaction>`."
|
|
1030
|
+
)
|
|
1031
|
+
self.name = "<unlabeled transaction>"
|
|
1032
|
+
|
|
1033
|
+
super().finish(scope, end_timestamp)
|
|
1034
|
+
|
|
1035
|
+
status_code = self._data.get(SPANDATA.HTTP_STATUS_CODE)
|
|
1036
|
+
if (
|
|
1037
|
+
status_code is not None
|
|
1038
|
+
and status_code in client.options["trace_ignore_status_codes"]
|
|
1039
|
+
):
|
|
1040
|
+
logger.debug(
|
|
1041
|
+
"[Tracing] Discarding {transaction_description} because the HTTP status code {status_code} is matched by trace_ignore_status_codes: {trace_ignore_status_codes}".format(
|
|
1042
|
+
transaction_description=self._get_log_representation(),
|
|
1043
|
+
status_code=self._data[SPANDATA.HTTP_STATUS_CODE],
|
|
1044
|
+
trace_ignore_status_codes=client.options[
|
|
1045
|
+
"trace_ignore_status_codes"
|
|
1046
|
+
],
|
|
1047
|
+
)
|
|
1048
|
+
)
|
|
1049
|
+
if client.transport:
|
|
1050
|
+
client.transport.record_lost_event(
|
|
1051
|
+
"event_processor", data_category="transaction"
|
|
1052
|
+
)
|
|
1053
|
+
|
|
1054
|
+
num_spans = len(self._span_recorder.spans) + 1
|
|
1055
|
+
client.transport.record_lost_event(
|
|
1056
|
+
"event_processor", data_category="span", quantity=num_spans
|
|
1057
|
+
)
|
|
1058
|
+
|
|
1059
|
+
self.sampled = False
|
|
1060
|
+
|
|
1061
|
+
if not self.sampled:
|
|
1062
|
+
# At this point a `sampled = None` should have already been resolved
|
|
1063
|
+
# to a concrete decision.
|
|
1064
|
+
if self.sampled is None:
|
|
1065
|
+
logger.warning("Discarding transaction without sampling decision.")
|
|
1066
|
+
|
|
1067
|
+
return None
|
|
1068
|
+
|
|
1069
|
+
finished_spans = [
|
|
1070
|
+
span.to_json()
|
|
1071
|
+
for span in self._span_recorder.spans
|
|
1072
|
+
if span.timestamp is not None
|
|
1073
|
+
]
|
|
1074
|
+
|
|
1075
|
+
len_diff = len(self._span_recorder.spans) - len(finished_spans)
|
|
1076
|
+
dropped_spans = len_diff + self._span_recorder.dropped_spans
|
|
1077
|
+
|
|
1078
|
+
# we do this to break the circular reference of transaction -> span
|
|
1079
|
+
# recorder -> span -> containing transaction (which is where we started)
|
|
1080
|
+
# before either the spans or the transaction goes out of scope and has
|
|
1081
|
+
# to be garbage collected
|
|
1082
|
+
self._span_recorder = None
|
|
1083
|
+
|
|
1084
|
+
contexts = {}
|
|
1085
|
+
contexts.update(self._contexts)
|
|
1086
|
+
contexts.update({"trace": self.get_trace_context()})
|
|
1087
|
+
profile_context = self.get_profile_context()
|
|
1088
|
+
if profile_context is not None:
|
|
1089
|
+
contexts.update({"profile": profile_context})
|
|
1090
|
+
|
|
1091
|
+
event = {
|
|
1092
|
+
"type": "transaction",
|
|
1093
|
+
"transaction": self.name,
|
|
1094
|
+
"transaction_info": {"source": self.source},
|
|
1095
|
+
"contexts": contexts,
|
|
1096
|
+
"tags": self._tags,
|
|
1097
|
+
"timestamp": self.timestamp,
|
|
1098
|
+
"start_timestamp": self.start_timestamp,
|
|
1099
|
+
"spans": finished_spans,
|
|
1100
|
+
} # type: Event
|
|
1101
|
+
|
|
1102
|
+
if dropped_spans > 0:
|
|
1103
|
+
event["_dropped_spans"] = dropped_spans
|
|
1104
|
+
|
|
1105
|
+
if self._profile is not None and self._profile.valid():
|
|
1106
|
+
event["profile"] = self._profile
|
|
1107
|
+
self._profile = None
|
|
1108
|
+
|
|
1109
|
+
event["measurements"] = self._measurements
|
|
1110
|
+
|
|
1111
|
+
return scope.capture_event(event)
|
|
1112
|
+
|
|
1113
|
+
def set_measurement(self, name, value, unit=""):
|
|
1114
|
+
# type: (str, float, MeasurementUnit) -> None
|
|
1115
|
+
"""
|
|
1116
|
+
.. deprecated:: 2.28.0
|
|
1117
|
+
This function is deprecated and will be removed in the next major release.
|
|
1118
|
+
"""
|
|
1119
|
+
|
|
1120
|
+
warnings.warn(
|
|
1121
|
+
"`set_measurement()` is deprecated and will be removed in the next major version. Please use `set_data()` instead.",
|
|
1122
|
+
DeprecationWarning,
|
|
1123
|
+
stacklevel=2,
|
|
1124
|
+
)
|
|
1125
|
+
self._measurements[name] = {"value": value, "unit": unit}
|
|
1126
|
+
|
|
1127
|
+
def set_context(self, key, value):
|
|
1128
|
+
# type: (str, dict[str, Any]) -> None
|
|
1129
|
+
"""Sets a context. Transactions can have multiple contexts
|
|
1130
|
+
and they should follow the format described in the "Contexts Interface"
|
|
1131
|
+
documentation.
|
|
1132
|
+
|
|
1133
|
+
:param key: The name of the context.
|
|
1134
|
+
:param value: The information about the context.
|
|
1135
|
+
"""
|
|
1136
|
+
self._contexts[key] = value
|
|
1137
|
+
|
|
1138
|
+
def set_http_status(self, http_status):
|
|
1139
|
+
# type: (int) -> None
|
|
1140
|
+
"""Sets the status of the Transaction according to the given HTTP status.
|
|
1141
|
+
|
|
1142
|
+
:param http_status: The HTTP status code."""
|
|
1143
|
+
super().set_http_status(http_status)
|
|
1144
|
+
self.set_context("response", {"status_code": http_status})
|
|
1145
|
+
|
|
1146
|
+
def to_json(self):
|
|
1147
|
+
# type: () -> Dict[str, Any]
|
|
1148
|
+
"""Returns a JSON-compatible representation of the transaction."""
|
|
1149
|
+
rv = super().to_json()
|
|
1150
|
+
|
|
1151
|
+
rv["name"] = self.name
|
|
1152
|
+
rv["source"] = self.source
|
|
1153
|
+
rv["sampled"] = self.sampled
|
|
1154
|
+
|
|
1155
|
+
return rv
|
|
1156
|
+
|
|
1157
|
+
def get_trace_context(self):
|
|
1158
|
+
# type: () -> Any
|
|
1159
|
+
trace_context = super().get_trace_context()
|
|
1160
|
+
|
|
1161
|
+
if self._data:
|
|
1162
|
+
trace_context["data"] = self._data
|
|
1163
|
+
|
|
1164
|
+
return trace_context
|
|
1165
|
+
|
|
1166
|
+
def get_baggage(self):
|
|
1167
|
+
# type: () -> Baggage
|
|
1168
|
+
"""Returns the :py:class:`~sentry_sdk.tracing_utils.Baggage`
|
|
1169
|
+
associated with the Transaction.
|
|
1170
|
+
|
|
1171
|
+
The first time a new baggage with Sentry items is made,
|
|
1172
|
+
it will be frozen."""
|
|
1173
|
+
if not self._baggage or self._baggage.mutable:
|
|
1174
|
+
self._baggage = Baggage.populate_from_transaction(self)
|
|
1175
|
+
|
|
1176
|
+
return self._baggage
|
|
1177
|
+
|
|
1178
|
+
def _set_initial_sampling_decision(self, sampling_context):
|
|
1179
|
+
# type: (SamplingContext) -> None
|
|
1180
|
+
"""
|
|
1181
|
+
Sets the transaction's sampling decision, according to the following
|
|
1182
|
+
precedence rules:
|
|
1183
|
+
|
|
1184
|
+
1. If a sampling decision is passed to `start_transaction`
|
|
1185
|
+
(`start_transaction(name: "my transaction", sampled: True)`), that
|
|
1186
|
+
decision will be used, regardless of anything else
|
|
1187
|
+
|
|
1188
|
+
2. If `traces_sampler` is defined, its decision will be used. It can
|
|
1189
|
+
choose to keep or ignore any parent sampling decision, or use the
|
|
1190
|
+
sampling context data to make its own decision or to choose a sample
|
|
1191
|
+
rate for the transaction.
|
|
1192
|
+
|
|
1193
|
+
3. If `traces_sampler` is not defined, but there's a parent sampling
|
|
1194
|
+
decision, the parent sampling decision will be used.
|
|
1195
|
+
|
|
1196
|
+
4. If `traces_sampler` is not defined and there's no parent sampling
|
|
1197
|
+
decision, `traces_sample_rate` will be used.
|
|
1198
|
+
"""
|
|
1199
|
+
client = sentry_sdk.get_client()
|
|
1200
|
+
|
|
1201
|
+
transaction_description = self._get_log_representation()
|
|
1202
|
+
|
|
1203
|
+
# nothing to do if tracing is disabled
|
|
1204
|
+
if not has_tracing_enabled(client.options):
|
|
1205
|
+
self.sampled = False
|
|
1206
|
+
return
|
|
1207
|
+
|
|
1208
|
+
# if the user has forced a sampling decision by passing a `sampled`
|
|
1209
|
+
# value when starting the transaction, go with that
|
|
1210
|
+
if self.sampled is not None:
|
|
1211
|
+
self.sample_rate = float(self.sampled)
|
|
1212
|
+
return
|
|
1213
|
+
|
|
1214
|
+
# we would have bailed already if neither `traces_sampler` nor
|
|
1215
|
+
# `traces_sample_rate` were defined, so one of these should work; prefer
|
|
1216
|
+
# the hook if so
|
|
1217
|
+
sample_rate = (
|
|
1218
|
+
client.options["traces_sampler"](sampling_context)
|
|
1219
|
+
if callable(client.options.get("traces_sampler"))
|
|
1220
|
+
# default inheritance behavior
|
|
1221
|
+
else (
|
|
1222
|
+
sampling_context["parent_sampled"]
|
|
1223
|
+
if sampling_context["parent_sampled"] is not None
|
|
1224
|
+
else client.options["traces_sample_rate"]
|
|
1225
|
+
)
|
|
1226
|
+
)
|
|
1227
|
+
|
|
1228
|
+
# Since this is coming from the user (or from a function provided by the
|
|
1229
|
+
# user), who knows what we might get. (The only valid values are
|
|
1230
|
+
# booleans or numbers between 0 and 1.)
|
|
1231
|
+
if not is_valid_sample_rate(sample_rate, source="Tracing"):
|
|
1232
|
+
logger.warning(
|
|
1233
|
+
"[Tracing] Discarding {transaction_description} because of invalid sample rate.".format(
|
|
1234
|
+
transaction_description=transaction_description,
|
|
1235
|
+
)
|
|
1236
|
+
)
|
|
1237
|
+
self.sampled = False
|
|
1238
|
+
return
|
|
1239
|
+
|
|
1240
|
+
self.sample_rate = float(sample_rate)
|
|
1241
|
+
|
|
1242
|
+
if client.monitor:
|
|
1243
|
+
self.sample_rate /= 2**client.monitor.downsample_factor
|
|
1244
|
+
|
|
1245
|
+
# if the function returned 0 (or false), or if `traces_sample_rate` is
|
|
1246
|
+
# 0, it's a sign the transaction should be dropped
|
|
1247
|
+
if not self.sample_rate:
|
|
1248
|
+
logger.debug(
|
|
1249
|
+
"[Tracing] Discarding {transaction_description} because {reason}".format(
|
|
1250
|
+
transaction_description=transaction_description,
|
|
1251
|
+
reason=(
|
|
1252
|
+
"traces_sampler returned 0 or False"
|
|
1253
|
+
if callable(client.options.get("traces_sampler"))
|
|
1254
|
+
else "traces_sample_rate is set to 0"
|
|
1255
|
+
),
|
|
1256
|
+
)
|
|
1257
|
+
)
|
|
1258
|
+
self.sampled = False
|
|
1259
|
+
return
|
|
1260
|
+
|
|
1261
|
+
# Now we roll the dice.
|
|
1262
|
+
self.sampled = self._sample_rand < self.sample_rate
|
|
1263
|
+
|
|
1264
|
+
if self.sampled:
|
|
1265
|
+
logger.debug(
|
|
1266
|
+
"[Tracing] Starting {transaction_description}".format(
|
|
1267
|
+
transaction_description=transaction_description,
|
|
1268
|
+
)
|
|
1269
|
+
)
|
|
1270
|
+
else:
|
|
1271
|
+
logger.debug(
|
|
1272
|
+
"[Tracing] Discarding {transaction_description} because it's not included in the random sample (sampling rate = {sample_rate})".format(
|
|
1273
|
+
transaction_description=transaction_description,
|
|
1274
|
+
sample_rate=self.sample_rate,
|
|
1275
|
+
)
|
|
1276
|
+
)
|
|
1277
|
+
|
|
1278
|
+
|
|
1279
|
+
class NoOpSpan(Span):
|
|
1280
|
+
def __repr__(self):
|
|
1281
|
+
# type: () -> str
|
|
1282
|
+
return "<%s>" % self.__class__.__name__
|
|
1283
|
+
|
|
1284
|
+
@property
|
|
1285
|
+
def containing_transaction(self):
|
|
1286
|
+
# type: () -> Optional[Transaction]
|
|
1287
|
+
return None
|
|
1288
|
+
|
|
1289
|
+
def start_child(self, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
|
|
1290
|
+
# type: (str, **Any) -> NoOpSpan
|
|
1291
|
+
return NoOpSpan()
|
|
1292
|
+
|
|
1293
|
+
def to_traceparent(self):
|
|
1294
|
+
# type: () -> str
|
|
1295
|
+
return ""
|
|
1296
|
+
|
|
1297
|
+
def to_baggage(self):
|
|
1298
|
+
# type: () -> Optional[Baggage]
|
|
1299
|
+
return None
|
|
1300
|
+
|
|
1301
|
+
def get_baggage(self):
|
|
1302
|
+
# type: () -> Optional[Baggage]
|
|
1303
|
+
return None
|
|
1304
|
+
|
|
1305
|
+
def iter_headers(self):
|
|
1306
|
+
# type: () -> Iterator[Tuple[str, str]]
|
|
1307
|
+
return iter(())
|
|
1308
|
+
|
|
1309
|
+
def set_tag(self, key, value):
|
|
1310
|
+
# type: (str, Any) -> None
|
|
1311
|
+
pass
|
|
1312
|
+
|
|
1313
|
+
def set_data(self, key, value):
|
|
1314
|
+
# type: (str, Any) -> None
|
|
1315
|
+
pass
|
|
1316
|
+
|
|
1317
|
+
def update_data(self, data):
|
|
1318
|
+
# type: (Dict[str, Any]) -> None
|
|
1319
|
+
pass
|
|
1320
|
+
|
|
1321
|
+
def set_status(self, value):
|
|
1322
|
+
# type: (str) -> None
|
|
1323
|
+
pass
|
|
1324
|
+
|
|
1325
|
+
def set_http_status(self, http_status):
|
|
1326
|
+
# type: (int) -> None
|
|
1327
|
+
pass
|
|
1328
|
+
|
|
1329
|
+
def is_success(self):
|
|
1330
|
+
# type: () -> bool
|
|
1331
|
+
return True
|
|
1332
|
+
|
|
1333
|
+
def to_json(self):
|
|
1334
|
+
# type: () -> Dict[str, Any]
|
|
1335
|
+
return {}
|
|
1336
|
+
|
|
1337
|
+
def get_trace_context(self):
|
|
1338
|
+
# type: () -> Any
|
|
1339
|
+
return {}
|
|
1340
|
+
|
|
1341
|
+
def get_profile_context(self):
|
|
1342
|
+
# type: () -> Any
|
|
1343
|
+
return {}
|
|
1344
|
+
|
|
1345
|
+
def finish(
|
|
1346
|
+
self,
|
|
1347
|
+
scope=None, # type: Optional[sentry_sdk.Scope]
|
|
1348
|
+
end_timestamp=None, # type: Optional[Union[float, datetime]]
|
|
1349
|
+
*,
|
|
1350
|
+
hub=None, # type: Optional[sentry_sdk.Hub]
|
|
1351
|
+
):
|
|
1352
|
+
# type: (...) -> Optional[str]
|
|
1353
|
+
"""
|
|
1354
|
+
The `hub` parameter is deprecated. Please use the `scope` parameter, instead.
|
|
1355
|
+
"""
|
|
1356
|
+
pass
|
|
1357
|
+
|
|
1358
|
+
def set_measurement(self, name, value, unit=""):
|
|
1359
|
+
# type: (str, float, MeasurementUnit) -> None
|
|
1360
|
+
pass
|
|
1361
|
+
|
|
1362
|
+
def set_context(self, key, value):
|
|
1363
|
+
# type: (str, dict[str, Any]) -> None
|
|
1364
|
+
pass
|
|
1365
|
+
|
|
1366
|
+
def init_span_recorder(self, maxlen):
|
|
1367
|
+
# type: (int) -> None
|
|
1368
|
+
pass
|
|
1369
|
+
|
|
1370
|
+
def _set_initial_sampling_decision(self, sampling_context):
|
|
1371
|
+
# type: (SamplingContext) -> None
|
|
1372
|
+
pass
|
|
1373
|
+
|
|
1374
|
+
|
|
1375
|
+
if TYPE_CHECKING:
|
|
1376
|
+
|
|
1377
|
+
@overload
|
|
1378
|
+
def trace(
|
|
1379
|
+
func=None, *, op=None, name=None, attributes=None, template=SPANTEMPLATE.DEFAULT
|
|
1380
|
+
):
|
|
1381
|
+
# type: (None, Optional[str], Optional[str], Optional[dict[str, Any]], SPANTEMPLATE) -> Callable[[Callable[P, R]], Callable[P, R]]
|
|
1382
|
+
# Handles: @trace() and @trace(op="custom")
|
|
1383
|
+
pass
|
|
1384
|
+
|
|
1385
|
+
@overload
|
|
1386
|
+
def trace(func):
|
|
1387
|
+
# type: (Callable[P, R]) -> Callable[P, R]
|
|
1388
|
+
# Handles: @trace
|
|
1389
|
+
pass
|
|
1390
|
+
|
|
1391
|
+
|
|
1392
|
+
def trace(
|
|
1393
|
+
func=None, *, op=None, name=None, attributes=None, template=SPANTEMPLATE.DEFAULT
|
|
1394
|
+
):
|
|
1395
|
+
# type: (Optional[Callable[P, R]], Optional[str], Optional[str], Optional[dict[str, Any]], SPANTEMPLATE) -> Union[Callable[P, R], Callable[[Callable[P, R]], Callable[P, R]]]
|
|
1396
|
+
"""
|
|
1397
|
+
Decorator to start a child span around a function call.
|
|
1398
|
+
|
|
1399
|
+
This decorator automatically creates a new span when the decorated function
|
|
1400
|
+
is called, and finishes the span when the function returns or raises an exception.
|
|
1401
|
+
|
|
1402
|
+
:param func: The function to trace. When used as a decorator without parentheses,
|
|
1403
|
+
this is the function being decorated. When used with parameters (e.g.,
|
|
1404
|
+
``@trace(op="custom")``, this should be None.
|
|
1405
|
+
:type func: Callable or None
|
|
1406
|
+
|
|
1407
|
+
:param op: The operation name for the span. This is a high-level description
|
|
1408
|
+
of what the span represents (e.g., "http.client", "db.query").
|
|
1409
|
+
You can use predefined constants from :py:class:`sentry_sdk.consts.OP`
|
|
1410
|
+
or provide your own string. If not provided, a default operation will
|
|
1411
|
+
be assigned based on the template.
|
|
1412
|
+
:type op: str or None
|
|
1413
|
+
|
|
1414
|
+
:param name: The human-readable name/description for the span. If not provided,
|
|
1415
|
+
defaults to the function name. This provides more specific details about
|
|
1416
|
+
what the span represents (e.g., "GET /api/users", "process_user_data").
|
|
1417
|
+
:type name: str or None
|
|
1418
|
+
|
|
1419
|
+
:param attributes: A dictionary of key-value pairs to add as attributes to the span.
|
|
1420
|
+
Attribute values must be strings, integers, floats, or booleans. These
|
|
1421
|
+
attributes provide additional context about the span's execution.
|
|
1422
|
+
:type attributes: dict[str, Any] or None
|
|
1423
|
+
|
|
1424
|
+
:param template: The type of span to create. This determines what kind of
|
|
1425
|
+
span instrumentation and data collection will be applied. Use predefined
|
|
1426
|
+
constants from :py:class:`sentry_sdk.consts.SPANTEMPLATE`.
|
|
1427
|
+
The default is `SPANTEMPLATE.DEFAULT` which is the right choice for most
|
|
1428
|
+
use cases.
|
|
1429
|
+
:type template: :py:class:`sentry_sdk.consts.SPANTEMPLATE`
|
|
1430
|
+
|
|
1431
|
+
:returns: When used as ``@trace``, returns the decorated function. When used as
|
|
1432
|
+
``@trace(...)`` with parameters, returns a decorator function.
|
|
1433
|
+
:rtype: Callable or decorator function
|
|
1434
|
+
|
|
1435
|
+
Example::
|
|
1436
|
+
|
|
1437
|
+
import sentry_sdk
|
|
1438
|
+
from sentry_sdk.consts import OP, SPANTEMPLATE
|
|
1439
|
+
|
|
1440
|
+
# Simple usage with default values
|
|
1441
|
+
@sentry_sdk.trace
|
|
1442
|
+
def process_data():
|
|
1443
|
+
# Function implementation
|
|
1444
|
+
pass
|
|
1445
|
+
|
|
1446
|
+
# With custom parameters
|
|
1447
|
+
@sentry_sdk.trace(
|
|
1448
|
+
op=OP.DB_QUERY,
|
|
1449
|
+
name="Get user data",
|
|
1450
|
+
attributes={"postgres": True}
|
|
1451
|
+
)
|
|
1452
|
+
def make_db_query(sql):
|
|
1453
|
+
# Function implementation
|
|
1454
|
+
pass
|
|
1455
|
+
|
|
1456
|
+
# With a custom template
|
|
1457
|
+
@sentry_sdk.trace(template=SPANTEMPLATE.AI_TOOL)
|
|
1458
|
+
def calculate_interest_rate(amount, rate, years):
|
|
1459
|
+
# Function implementation
|
|
1460
|
+
pass
|
|
1461
|
+
"""
|
|
1462
|
+
from sentry_sdk.tracing_utils import create_span_decorator
|
|
1463
|
+
|
|
1464
|
+
decorator = create_span_decorator(
|
|
1465
|
+
op=op,
|
|
1466
|
+
name=name,
|
|
1467
|
+
attributes=attributes,
|
|
1468
|
+
template=template,
|
|
1469
|
+
)
|
|
1470
|
+
|
|
1471
|
+
if func:
|
|
1472
|
+
return decorator(func)
|
|
1473
|
+
else:
|
|
1474
|
+
return decorator
|
|
1475
|
+
|
|
1476
|
+
|
|
1477
|
+
# Circular imports
|
|
1478
|
+
|
|
1479
|
+
from sentry_sdk.tracing_utils import (
|
|
1480
|
+
Baggage,
|
|
1481
|
+
EnvironHeaders,
|
|
1482
|
+
extract_sentrytrace_data,
|
|
1483
|
+
_generate_sample_rand,
|
|
1484
|
+
has_tracing_enabled,
|
|
1485
|
+
maybe_create_breadcrumbs_from_span,
|
|
1486
|
+
)
|