Skip to content

Commit 4df9849

Browse files
antonpirkerbitsandfoxes
authored andcommitted
Add types to code snippets for hooks (#13437)
1 parent 8cd3f18 commit 4df9849

File tree

16 files changed

+96
-51
lines changed

16 files changed

+96
-51
lines changed

docs/platforms/python/configuration/filtering/index.mdx

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ Suppose that you wish prevent all errors of type `ZeroDivisionError` from being
3030
import sentry_sdk
3131
from sentry_sdk.types import Event, Hint
3232

33-
def my_before_send(event: Event, hint: Hint) -> Event | None:
33+
def before_send(event: Event, hint: Hint) -> Event | None:
3434
# Filter out all ZeroDivisionError events.
3535
# Note that the exception type is available in the hint,
3636
# but we should handle the case where the exception info
@@ -48,7 +48,7 @@ def my_before_send(event: Event, hint: Hint) -> Event | None:
4848
sentry_sdk.init(
4949
# ...
5050

51-
before_send=my_before_send,
51+
before_send=before_send,
5252
)
5353
```
5454

docs/platforms/python/profiling/index.mdx

+2-1
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,9 @@ Transaction-based profiling only runs in tandem with performance transactions th
9797

9898
```python
9999
import sentry_sdk
100+
from sentry_sdk.types import SamplingContext
100101

101-
def profiles_sampler(sampling_context):
102+
def profiles_sampler(sampling_context: SamplingContext) -> float:
102103
# ...
103104
# return a number between 0 and 1 or a boolean
104105

docs/platforms/python/tracing/configure-sampling/index.mdx

+20-5
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,10 @@ In distributed systems, implementing inheritance logic when trace information is
4646
1. Prioritizing Critical User Flows
4747

4848
```python
49-
def traces_sampler(sampling_context):
49+
import sentry_sdk
50+
from sentry_sdk.types import SamplingContext
51+
52+
def traces_sampler(sampling_context: SamplingContext) -> float:
5053
# Use the parent sampling decision if we have an incoming trace.
5154
# Note: we strongly recommend respecting the parent sampling decision,
5255
# as this ensures your traces will be complete!
@@ -79,7 +82,10 @@ sentry_sdk.init(
7982
2. Handling Different Environments and Error Rates
8083

8184
```python
82-
def traces_sampler(sampling_context):
85+
import sentry_sdk
86+
from sentry_sdk.types import SamplingContext
87+
88+
def traces_sampler(sampling_context: SamplingContext) -> float:
8389
# Use the parent sampling decision if we have an incoming trace.
8490
# Note: we strongly recommend respecting the parent sampling decision,
8591
# as this ensures your traces will be complete!
@@ -130,7 +136,10 @@ with sentry_sdk.start_transaction(name="GET /api/users", op="http.request") as t
130136
3. Controlling Sampling Based on User and Transaction Properties
131137

132138
```python
133-
def traces_sampler(sampling_context):
139+
import sentry_sdk
140+
from sentry_sdk.types import SamplingContext
141+
142+
def traces_sampler(sampling_context: SamplingContext) -> float:
134143
# Use the parent sampling decision if we have an incoming trace.
135144
# Note: we strongly recommend respecting the parent sampling decision,
136145
# as this ensures your traces will be complete!
@@ -183,7 +192,10 @@ with sentry_sdk.start_transaction(name="GET /api/users", op="http.request") as t
183192
4. Complex Business Logic Sampling
184193

185194
```python
186-
def traces_sampler(sampling_context):
195+
import sentry_sdk
196+
from sentry_sdk.types import SamplingContext
197+
198+
def traces_sampler(sampling_context: SamplingContext) -> float:
187199
# Use the parent sampling decision if we have an incoming trace.
188200
# Note: we strongly recommend respecting the parent sampling decision,
189201
# as this ensures your traces will be complete!
@@ -241,7 +253,10 @@ with sentry_sdk.start_transaction(name="Process Payment", op="payment.process")
241253
5. Performance-Based Sampling
242254

243255
```python
244-
def traces_sampler(sampling_context):
256+
import sentry_sdk
257+
from sentry_sdk.types import SamplingContext
258+
259+
def traces_sampler(sampling_context: SamplingContext) -> float:
245260
# Use the parent sampling decision if we have an incoming trace.
246261
# Note: we strongly recommend respecting the parent sampling decision,
247262
# as this ensures your traces will be complete!

docs/platforms/python/tracing/instrumentation/custom-instrumentation/index.mdx

+5-3
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,10 @@ with sentry_sdk.start_span(name="my-span") as span:
273273
To attach data attributes to the transaction and all its spans, you can use <PlatformLink to="/configuration/filtering/#using-before-send-transaction">`before_send_transaction`</PlatformLink>:
274274

275275
```python
276-
def my_before_send_transaction(event, hint):
276+
import sentry_sdk
277+
from sentry_sdk.types import Event, Hint
278+
279+
def before_send_transaction(event: Event, hint: Hint) -> Event | None:
277280
# Set the data attribute "foo" to "bar" on every span belonging to this
278281
# transaction event
279282
for span in event["spans"]:
@@ -284,9 +287,8 @@ def my_before_send_transaction(event, hint):
284287

285288
return event
286289

287-
288290
sentry_sdk.init(
289291
traces_sample_rate=1.0,
290-
before_send_transaction=my_before_send_transaction,
292+
before_send_transaction=before_send_transaction,
291293
)
292294
```

docs/platforms/python/tracing/span-lifecycle/index.mdx

+13-13
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,11 @@ import sentry_sdk
4141

4242
with sentry_sdk.start_span(op="process", name="Process Data"):
4343
# This code is tracked in the "Process Data" span
44-
44+
4545
with sentry_sdk.start_span(op="task", name="Validate Input"):
4646
# This is now a child span of "Process Data"
4747
validate_data()
48-
48+
4949
with sentry_sdk.start_span(op="task", name="Transform Data"):
5050
# Another child span
5151
transform_data()
@@ -71,7 +71,7 @@ import sentry_sdk
7171
with sentry_sdk.start_span(op="db", name="Query Users") as span:
7272
# Perform a database query
7373
users = db.query("SELECT * FROM users")
74-
74+
7575
# You can set data on the span
7676
span.set_data("user_count", len(users))
7777
```
@@ -113,7 +113,7 @@ import sentry_sdk
113113

114114
with sentry_sdk.start_transaction(name="Background Task", op="task") as transaction:
115115
# Your code here
116-
116+
117117
# You can add child spans to the transaction
118118
with sentry_sdk.start_span(op="subtask", name="Data Processing"):
119119
# Process data
@@ -132,7 +132,7 @@ import sentry_sdk
132132
with sentry_sdk.start_span(op="db", name="Query Users") as span:
133133
# Execute the query
134134
users = db.query("SELECT * FROM users WHERE active = true")
135-
135+
136136
# You can add more data during execution
137137
span.set_data("result_count", len(users))
138138
```
@@ -156,32 +156,33 @@ To add attributes to all spans, use the `before_send_transaction` callback:
156156

157157
```python
158158
import sentry_sdk
159+
from sentry_sdk.types import Event, Hint
159160

160-
def before_send_transaction(event):
161+
def before_send_transaction(event: Event, hint: Hint) -> Event | None:
161162
# Add attributes to the root span (transaction)
162163
if "trace" in event.get("contexts", {}):
163164
if "data" not in event["contexts"]["trace"]:
164165
event["contexts"]["trace"]["data"] = {}
165-
166+
166167
event["contexts"]["trace"]["data"].update({
167168
"app_version": "1.2.3",
168169
"environment_region": "us-west-2"
169170
})
170-
171+
171172
# Add attributes to all child spans
172173
for span in event.get("spans", []):
173174
if "data" not in span:
174175
span["data"] = {}
175-
176+
176177
span["data"].update({
177178
"component_version": "2.0.0",
178179
"deployment_stage": "production"
179180
})
180-
181+
181182
return event
182183

183184
sentry_sdk.init(
184-
# Your other Sentry configuration options here
185+
# ...
185186
before_send_transaction=before_send_transaction
186187
)
187188
```
@@ -202,7 +203,7 @@ with sentry_sdk.start_span(op="http.client", name="Fetch User Data"):
202203
# Database operation
203204
with sentry_sdk.start_span(op="db", name="Save User"):
204205
db.execute(
205-
"INSERT INTO users (name, email) VALUES (%s, %s)",
206+
"INSERT INTO users (name, email) VALUES (%s, %s)",
206207
(user.name, user.email),
207208
)
208209

@@ -233,4 +234,3 @@ with sentry_sdk.start_span(op="task", name="Process Payment") as span:
233234
# Span will automatically be marked as failed when an exception occurs
234235
raise
235236
```
236-

docs/platforms/python/tracing/span-metrics/index.mdx

+8-5
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ if span:
2525
# Add individual metrics
2626
span.set_data("database.rows_affected", 42)
2727
span.set_data("cache.hit_rate", 0.85)
28-
28+
2929
# Add multiple metrics at once
3030
span.set_data({
3131
"memory.heap_used": 1024000,
@@ -70,12 +70,15 @@ For detailed examples of how to implement span metrics in common scenarios, see
7070
To consistently add metrics across all spans in your application, you can use the `before_send_transaction` callback:
7171

7272
```python
73-
def before_send_transaction(event):
73+
import sentry_sdk
74+
from sentry_sdk.types import Event, Hint
75+
76+
def before_send_transaction(event: Event, hint: Hint) -> Event | None:
7477
# Add metrics to the root span
7578
if "trace" in event.get("contexts", {}):
7679
if "data" not in event["contexts"]["trace"]:
7780
event["contexts"]["trace"]["data"] = {}
78-
81+
7982
event["contexts"]["trace"]["data"].update({
8083
"app.version": "1.2.3",
8184
"environment.region": "us-west-2"
@@ -85,7 +88,7 @@ def before_send_transaction(event):
8588
for span in event.get("spans", []):
8689
if "data" not in span:
8790
span["data"] = {}
88-
91+
8992
span["data"].update({
9093
"app.component_version": "2.0.0",
9194
"app.deployment_stage": "production"
@@ -94,7 +97,7 @@ def before_send_transaction(event):
9497
return event
9598

9699
sentry_sdk.init(
97-
# Your other Sentry configuration options here
100+
# ...
98101
before_send_transaction=before_send_transaction
99102
)
100103
```

docs/platforms/python/tracing/troubleshooting/index.mdx

+4-3
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,19 @@ You can define a custom `before_send_transaction` callback to modify transaction
2525
```python
2626
import sentry_sdk
2727
from sentry_sdk.integrations.django import DjangoIntegration
28+
from sentry_sdk.types import Event, Hint
2829

29-
def transaction_processor(event, hint):
30+
def transaction_processor(event: Event, hint: Hint) -> Event | None:
3031
if event.get("type") == "transaction":
3132
# Extract path from transaction name
3233
transaction_name = event.get("transaction", "")
33-
34+
3435
# Remove variable IDs from URLs to reduce cardinality
3536
if "/user/" in transaction_name:
3637
# Convert /user/123/ to /user/:id/
3738
import re
3839
event["transaction"] = re.sub(r'/user/\d+/', '/user/:id/', transaction_name)
39-
40+
4041
return event
4142

4243
sentry_sdk.init(

platform-includes/configuration/before-breadcrumb-hint/python.mdx

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
```python
22
import sentry_sdk
3+
from sentry_sdk.types import Breadcrumb, BreadcrumbHint
34

4-
def before_breadcrumb(crumb, hint):
5+
def before_breadcrumb(crumb: Breadcrumb, hint: BreadcrumbHint) -> Breadcrumb | None:
56
if 'log_record' in hint:
67
crumb['data']['thread'] = hint['log_record'].threadName
8+
79
return crumb
810

911
sentry_sdk.init(

platform-includes/configuration/before-send-fingerprint/python.mdx

+10-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
```python
22
import sentry_sdk
3+
from sentry_sdk.types import Event, Hint
4+
5+
def before_send(event: Event, hint: Hint) -> Event | None:
6+
if 'exc_info' not in hint:
7+
return event
8+
9+
exception = hint['exc_info'][1]
10+
11+
if isinstance(exception, DatabaseUnavailable):
12+
event['fingerprint'] = ['database-unavailable']
313

4-
def before_send(event, hint):
5-
if 'exc_info' in hint:
6-
exc_type, exc_value, tb = hint['exc_info']
7-
if isinstance(exc_value, DatabaseUnavailable):
8-
event['fingerprint'] = ['database-unavailable']
914
return event
1015

1116
sentry_sdk.init(

platform-includes/configuration/before-send-hint/python.mdx

+10-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
```python
22
import sentry_sdk
3+
from sentry_sdk.types import Event, Hint
4+
5+
def before_send(event: Event, hint: Hint) -> Event | None:
6+
if 'exc_info' not in hint:
7+
return event
8+
9+
exception = hint['exc_info'][1]
10+
11+
if isinstance(exception, DatabaseUnavailable):
12+
event['fingerprint'] = ['database-unavailable']
313

4-
def before_send(event, hint):
5-
if 'exc_info' in hint:
6-
exc_type, exc_value, tb = hint['exc_info']
7-
if isinstance(exc_value, DatabaseUnavailable):
8-
event['fingerprint'] = ['database-unavailable']
914
return event
1015

1116
sentry_sdk.init(

platform-includes/configuration/before-send-transaction/python.mdx

+5-2
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@ In Python, a function can be used to modify the transaction event or return a ne
22

33
```python
44
import sentry_sdk
5+
from sentry_sdk.types import Event, Hint
56

6-
def strip_sensitive_data(event, hint):
7+
def strip_sensitive_data(event: Event, hint: Hint) -> Event | None:
78
# modify event here
89
return event
910

@@ -16,9 +17,11 @@ sentry_sdk.init(
1617
Addtionally, you may filter out transaction events based on the request URL, like `/healthcheck`.
1718

1819
```python
20+
import sentry_sdk
21+
from sentry_sdk.types import Event, Hint
1922
from urllib.parse import urlparse
2023

21-
def filter_transactions(event, hint):
24+
def filter_transactions(event: Event, hint: Hint) -> Event | None:
2225
url_string = event["request"]["url"]
2326
parsed_url = urlparse(url_string)
2427

platform-includes/configuration/error-sampler/python.mdx

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import sentry_sdk
33
from sentry_sdk.types import Event, Hint
44

55

6-
def my_error_sampler(event: Event, hint: Hint) -> float:
6+
def error_sampler(event: Event, hint: Hint) -> float:
77
error_class = hint["exc_info"][0]
88

99
if error_class == MyException:
@@ -17,6 +17,6 @@ def my_error_sampler(event: Event, hint: Hint) -> float:
1717

1818
sentry_sdk.init(
1919
# ...
20-
error_sampler=my_error_sampler,
20+
error_sampler=error_sampler,
2121
)
2222
```

platform-includes/enriching-events/breadcrumbs/before-breadcrumb/python.mdx

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
```python
22
import sentry_sdk
3+
from sentry_sdk.types import Breadcrumb, BreadcrumbHint
34

4-
def before_breadcrumb(crumb, hint):
5+
def before_breadcrumb(crumb: Breadcrumb, hint: BreadcrumbHint) -> Breadcrumb | None:
56
if crumb['category'] == 'a.spammy.Logger':
67
return None
78

platform-includes/performance/traces-sampler-as-filter/python.mdx

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
```python
2-
def traces_sampler(sampling_context):
2+
import sentry_sdk
3+
from sentry_sdk.types import SamplingContext
4+
5+
def traces_sampler(sampling_context: SamplingContext) -> float:
36
if "...":
47
# Drop this transaction, by setting its sample rate to 0%
58
return 0

0 commit comments

Comments
 (0)