From b5232ad8fddce819612ac5c182a4261bac0c850e Mon Sep 17 00:00:00 2001 From: Anton Pirker Date: Thu, 17 Apr 2025 14:47:19 +0200 Subject: [PATCH 1/4] Add type hints to code snippets --- .../python/configuration/filtering/index.mdx | 4 ++-- .../before-send-fingerprint/python.mdx | 15 ++++++++++----- .../configuration/before-send-hint/python.mdx | 15 ++++++++++----- .../database-connection/python.mdx | 3 ++- 4 files changed, 24 insertions(+), 13 deletions(-) diff --git a/docs/platforms/python/configuration/filtering/index.mdx b/docs/platforms/python/configuration/filtering/index.mdx index 00c5f844f28bf5..53bd20ccc230e3 100644 --- a/docs/platforms/python/configuration/filtering/index.mdx +++ b/docs/platforms/python/configuration/filtering/index.mdx @@ -30,7 +30,7 @@ Suppose that you wish prevent all errors of type `ZeroDivisionError` from being import sentry_sdk from sentry_sdk.types import Event, Hint -def my_before_send(event: Event, hint: Hint) -> Event | None: +def before_send(event: Event, hint: Hint) -> Event | None: # Filter out all ZeroDivisionError events. # Note that the exception type is available in the hint, # but we should handle the case where the exception info @@ -48,7 +48,7 @@ def my_before_send(event: Event, hint: Hint) -> Event | None: sentry_sdk.init( # ... - before_send=my_before_send, + before_send=before_send, ) ``` diff --git a/platform-includes/configuration/before-send-fingerprint/python.mdx b/platform-includes/configuration/before-send-fingerprint/python.mdx index 2efabe76823f37..fc81e4cc29198b 100644 --- a/platform-includes/configuration/before-send-fingerprint/python.mdx +++ b/platform-includes/configuration/before-send-fingerprint/python.mdx @@ -1,11 +1,16 @@ ```python import sentry_sdk +from sentry_sdk.types import Event, Hint + +def before_send(event: Event, hint: Hint) -> Event | None: + if 'exc_info' not in hint: + return event + + exception = hint['exc_info'][1] + + if isinstance(exception, DatabaseUnavailable): + event['fingerprint'] = ['database-unavailable'] -def before_send(event, hint): - if 'exc_info' in hint: - exc_type, exc_value, tb = hint['exc_info'] - if isinstance(exc_value, DatabaseUnavailable): - event['fingerprint'] = ['database-unavailable'] return event sentry_sdk.init( diff --git a/platform-includes/configuration/before-send-hint/python.mdx b/platform-includes/configuration/before-send-hint/python.mdx index afe3b878576f8c..011cee2e4b4164 100644 --- a/platform-includes/configuration/before-send-hint/python.mdx +++ b/platform-includes/configuration/before-send-hint/python.mdx @@ -1,11 +1,16 @@ ```python import sentry_sdk +from sentry_sdk.types import Event, Hint + +def before_send(event: Event, hint: Hint) -> Event | None: + if 'exc_info' not in hint: + return event + + exception = hint['exc_info'][1] + + if isinstance(exception, DatabaseUnavailable): + event['fingerprint'] = ['database-unavailable'] -def before_send(event, hint): - if 'exc_info' in hint: - exc_type, exc_value, tb = hint['exc_info'] - if isinstance(exc_value, DatabaseUnavailable): - event['fingerprint'] = ['database-unavailable'] return event sentry_sdk.init( diff --git a/platform-includes/set-fingerprint/database-connection/python.mdx b/platform-includes/set-fingerprint/database-connection/python.mdx index bf45e37b9156af..3fa90dca513cd8 100644 --- a/platform-includes/set-fingerprint/database-connection/python.mdx +++ b/platform-includes/set-fingerprint/database-connection/python.mdx @@ -1,10 +1,11 @@ ```python import sentry_sdk +from sentry_sdk.types import Event, Hint class DatabaseConnectionError(Exception): pass -def before_send(event, hint): +def before_send(event: Event, hint: Hint) -> Event | None: if 'exc_info' not in hint: return event From 39305dff21693bd237027214448c0d896deea587 Mon Sep 17 00:00:00 2001 From: Anton Pirker Date: Thu, 17 Apr 2025 15:09:17 +0200 Subject: [PATCH 2/4] Add type hints to code snippets --- docs/platforms/python/profiling/index.mdx | 3 ++- .../tracing/configure-sampling/index.mdx | 25 ++++++++++++++---- .../custom-instrumentation/index.mdx | 8 +++--- .../python/tracing/span-lifecycle/index.mdx | 26 +++++++++---------- .../python/tracing/span-metrics/index.mdx | 13 ++++++---- .../python/tracing/troubleshooting/index.mdx | 7 ++--- .../before-breadcrumb-hint/python.mdx | 4 ++- .../before-send-transaction/python.mdx | 7 +++-- .../breadcrumbs/before-breadcrumb/python.mdx | 3 ++- .../traces-sampler-as-filter/python.mdx | 5 +++- .../traces-sampler-as-sampler/python.mdx | 5 +++- 11 files changed, 70 insertions(+), 36 deletions(-) diff --git a/docs/platforms/python/profiling/index.mdx b/docs/platforms/python/profiling/index.mdx index db1cf9fbd2e141..e84220be824f53 100644 --- a/docs/platforms/python/profiling/index.mdx +++ b/docs/platforms/python/profiling/index.mdx @@ -97,8 +97,9 @@ Transaction-based profiling only runs in tandem with performance transactions th ```python import sentry_sdk +from sentry_sdk.types import SamplingContext -def profiles_sampler(sampling_context): +def profiles_sampler(sampling_context: SamplingContext) -> float: # ... # return a number between 0 and 1 or a boolean diff --git a/docs/platforms/python/tracing/configure-sampling/index.mdx b/docs/platforms/python/tracing/configure-sampling/index.mdx index b9abaab76aac81..8b4ede808ed36c 100644 --- a/docs/platforms/python/tracing/configure-sampling/index.mdx +++ b/docs/platforms/python/tracing/configure-sampling/index.mdx @@ -46,7 +46,10 @@ In distributed systems, implementing inheritance logic when trace information is 1. Prioritizing Critical User Flows ```python -def traces_sampler(sampling_context): +import sentry_sdk +from sentry_sdk.types import SamplingContext + +def traces_sampler(sampling_context: SamplingContext) -> float: # Use the parent sampling decision if we have an incoming trace. # Note: we strongly recommend respecting the parent sampling decision, # as this ensures your traces will be complete! @@ -79,7 +82,10 @@ sentry_sdk.init( 2. Handling Different Environments and Error Rates ```python -def traces_sampler(sampling_context): +import sentry_sdk +from sentry_sdk.types import SamplingContext + +def traces_sampler(sampling_context: SamplingContext) -> float: # Use the parent sampling decision if we have an incoming trace. # Note: we strongly recommend respecting the parent sampling decision, # 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 3. Controlling Sampling Based on User and Transaction Properties ```python -def traces_sampler(sampling_context): +import sentry_sdk +from sentry_sdk.types import SamplingContext + +def traces_sampler(sampling_context: SamplingContext) -> float: # Use the parent sampling decision if we have an incoming trace. # Note: we strongly recommend respecting the parent sampling decision, # 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 4. Complex Business Logic Sampling ```python -def traces_sampler(sampling_context): +import sentry_sdk +from sentry_sdk.types import SamplingContext + +def traces_sampler(sampling_context: SamplingContext) -> float: # Use the parent sampling decision if we have an incoming trace. # Note: we strongly recommend respecting the parent sampling decision, # as this ensures your traces will be complete! @@ -241,7 +253,10 @@ with sentry_sdk.start_transaction(name="Process Payment", op="payment.process") 5. Performance-Based Sampling ```python -def traces_sampler(sampling_context): +import sentry_sdk +from sentry_sdk.types import SamplingContext + +def traces_sampler(sampling_context: SamplingContext) -> float: # Use the parent sampling decision if we have an incoming trace. # Note: we strongly recommend respecting the parent sampling decision, # as this ensures your traces will be complete! diff --git a/docs/platforms/python/tracing/instrumentation/custom-instrumentation/index.mdx b/docs/platforms/python/tracing/instrumentation/custom-instrumentation/index.mdx index 9a8e921f9f85a3..502d1ab0748f4c 100644 --- a/docs/platforms/python/tracing/instrumentation/custom-instrumentation/index.mdx +++ b/docs/platforms/python/tracing/instrumentation/custom-instrumentation/index.mdx @@ -273,7 +273,10 @@ with sentry_sdk.start_span(name="my-span") as span: To attach data attributes to the transaction and all its spans, you can use `before_send_transaction`: ```python -def my_before_send_transaction(event, hint): +import sentry_sdk +from sentry_sdk.types import Event, Hint + +def before_send_transaction(event: Event, hint: Hint) -> Event | None: # Set the data attribute "foo" to "bar" on every span belonging to this # transaction event for span in event["spans"]: @@ -284,9 +287,8 @@ def my_before_send_transaction(event, hint): return event - sentry_sdk.init( traces_sample_rate=1.0, - before_send_transaction=my_before_send_transaction, + before_send_transaction=before_send_transaction, ) ``` diff --git a/docs/platforms/python/tracing/span-lifecycle/index.mdx b/docs/platforms/python/tracing/span-lifecycle/index.mdx index bd3b8180c25d5a..11fbae96e40fb7 100644 --- a/docs/platforms/python/tracing/span-lifecycle/index.mdx +++ b/docs/platforms/python/tracing/span-lifecycle/index.mdx @@ -41,11 +41,11 @@ import sentry_sdk with sentry_sdk.start_span(op="process", name="Process Data"): # This code is tracked in the "Process Data" span - + with sentry_sdk.start_span(op="task", name="Validate Input"): # This is now a child span of "Process Data" validate_data() - + with sentry_sdk.start_span(op="task", name="Transform Data"): # Another child span transform_data() @@ -71,7 +71,7 @@ import sentry_sdk with sentry_sdk.start_span(op="db", name="Query Users") as span: # Perform a database query users = db.query("SELECT * FROM users") - + # You can set data on the span span.set_data("user_count", len(users)) ``` @@ -113,7 +113,7 @@ import sentry_sdk with sentry_sdk.start_transaction(name="Background Task", op="task") as transaction: # Your code here - + # You can add child spans to the transaction with sentry_sdk.start_span(op="subtask", name="Data Processing"): # Process data @@ -132,7 +132,7 @@ import sentry_sdk with sentry_sdk.start_span(op="db", name="Query Users") as span: # Execute the query users = db.query("SELECT * FROM users WHERE active = true") - + # You can add more data during execution span.set_data("result_count", len(users)) ``` @@ -156,32 +156,33 @@ To add attributes to all spans, use the `before_send_transaction` callback: ```python import sentry_sdk +from sentry_sdk.types import Event, Hint -def before_send_transaction(event): +def before_send_transaction(event: Event, hint: Hint) -> Event | None: # Add attributes to the root span (transaction) if "trace" in event.get("contexts", {}): if "data" not in event["contexts"]["trace"]: event["contexts"]["trace"]["data"] = {} - + event["contexts"]["trace"]["data"].update({ "app_version": "1.2.3", "environment_region": "us-west-2" }) - + # Add attributes to all child spans for span in event.get("spans", []): if "data" not in span: span["data"] = {} - + span["data"].update({ "component_version": "2.0.0", "deployment_stage": "production" }) - + return event sentry_sdk.init( - # Your other Sentry configuration options here + # ... before_send_transaction=before_send_transaction ) ``` @@ -202,7 +203,7 @@ with sentry_sdk.start_span(op="http.client", name="Fetch User Data"): # Database operation with sentry_sdk.start_span(op="db", name="Save User"): db.execute( - "INSERT INTO users (name, email) VALUES (%s, %s)", + "INSERT INTO users (name, email) VALUES (%s, %s)", (user.name, user.email), ) @@ -233,4 +234,3 @@ with sentry_sdk.start_span(op="task", name="Process Payment") as span: # Span will automatically be marked as failed when an exception occurs raise ``` - diff --git a/docs/platforms/python/tracing/span-metrics/index.mdx b/docs/platforms/python/tracing/span-metrics/index.mdx index e6915ae24b3169..941f47be4563fe 100644 --- a/docs/platforms/python/tracing/span-metrics/index.mdx +++ b/docs/platforms/python/tracing/span-metrics/index.mdx @@ -25,7 +25,7 @@ if span: # Add individual metrics span.set_data("database.rows_affected", 42) span.set_data("cache.hit_rate", 0.85) - + # Add multiple metrics at once span.set_data({ "memory.heap_used": 1024000, @@ -70,12 +70,15 @@ For detailed examples of how to implement span metrics in common scenarios, see To consistently add metrics across all spans in your application, you can use the `before_send_transaction` callback: ```python -def before_send_transaction(event): +import sentry_sdk +from sentry_sdk.types import Event, Hint + +def before_send_transaction(event: Event, hint: Hint) -> Event | None: # Add metrics to the root span if "trace" in event.get("contexts", {}): if "data" not in event["contexts"]["trace"]: event["contexts"]["trace"]["data"] = {} - + event["contexts"]["trace"]["data"].update({ "app.version": "1.2.3", "environment.region": "us-west-2" @@ -85,7 +88,7 @@ def before_send_transaction(event): for span in event.get("spans", []): if "data" not in span: span["data"] = {} - + span["data"].update({ "app.component_version": "2.0.0", "app.deployment_stage": "production" @@ -94,7 +97,7 @@ def before_send_transaction(event): return event sentry_sdk.init( - # Your other Sentry configuration options here + # ... before_send_transaction=before_send_transaction ) ``` diff --git a/docs/platforms/python/tracing/troubleshooting/index.mdx b/docs/platforms/python/tracing/troubleshooting/index.mdx index 29763dc64e9353..b6c136095d57e9 100644 --- a/docs/platforms/python/tracing/troubleshooting/index.mdx +++ b/docs/platforms/python/tracing/troubleshooting/index.mdx @@ -25,18 +25,19 @@ You can define a custom `before_send_transaction` callback to modify transaction ```python import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration +from sentry_sdk.types import Event, Hint -def transaction_processor(event, hint): +def transaction_processor(event: Event, hint: Hint) -> Event | None: if event.get("type") == "transaction": # Extract path from transaction name transaction_name = event.get("transaction", "") - + # Remove variable IDs from URLs to reduce cardinality if "/user/" in transaction_name: # Convert /user/123/ to /user/:id/ import re event["transaction"] = re.sub(r'/user/\d+/', '/user/:id/', transaction_name) - + return event sentry_sdk.init( diff --git a/platform-includes/configuration/before-breadcrumb-hint/python.mdx b/platform-includes/configuration/before-breadcrumb-hint/python.mdx index 903fae326450a1..1fcc71794a935e 100644 --- a/platform-includes/configuration/before-breadcrumb-hint/python.mdx +++ b/platform-includes/configuration/before-breadcrumb-hint/python.mdx @@ -1,9 +1,11 @@ ```python import sentry_sdk +from sentry_sdk.types import Breadcrumb, BreadcrumbHint -def before_breadcrumb(crumb, hint): +def before_breadcrumb(crumb: Breadcrumb, hint: Hint) -> Breadcrumb | None: if 'log_record' in hint: crumb['data']['thread'] = hint['log_record'].threadName + return crumb sentry_sdk.init( diff --git a/platform-includes/configuration/before-send-transaction/python.mdx b/platform-includes/configuration/before-send-transaction/python.mdx index 84a34e28299702..320fdfb366cc0b 100644 --- a/platform-includes/configuration/before-send-transaction/python.mdx +++ b/platform-includes/configuration/before-send-transaction/python.mdx @@ -2,8 +2,9 @@ In Python, a function can be used to modify the transaction event or return a ne ```python import sentry_sdk +from sentry_sdk.types import Event, Hint -def strip_sensitive_data(event, hint): +def strip_sensitive_data(event: Event, hint: Hint) -> Event | None: # modify event here return event @@ -16,9 +17,11 @@ sentry_sdk.init( Addtionally, you may filter out transaction events based on the request URL, like `/healthcheck`. ```python +import sentry_sdk +from sentry_sdk.types import Event, Hint from urllib.parse import urlparse -def filter_transactions(event, hint): +def filter_transactions(event: Event, hint: Hint) -> Event | None: url_string = event["request"]["url"] parsed_url = urlparse(url_string) diff --git a/platform-includes/enriching-events/breadcrumbs/before-breadcrumb/python.mdx b/platform-includes/enriching-events/breadcrumbs/before-breadcrumb/python.mdx index e131df6150330d..4caabcd89b8eab 100644 --- a/platform-includes/enriching-events/breadcrumbs/before-breadcrumb/python.mdx +++ b/platform-includes/enriching-events/breadcrumbs/before-breadcrumb/python.mdx @@ -1,7 +1,8 @@ ```python import sentry_sdk +from sentry_sdk.types import Breadcrumb, BreadcrumbHint -def before_breadcrumb(crumb, hint): +def before_breadcrumb(crumb: Breadcrumb, hint: Hint) -> Breadcrumb | None: if crumb['category'] == 'a.spammy.Logger': return None diff --git a/platform-includes/performance/traces-sampler-as-filter/python.mdx b/platform-includes/performance/traces-sampler-as-filter/python.mdx index 6ebc3186ea67e4..98fac790484fd1 100644 --- a/platform-includes/performance/traces-sampler-as-filter/python.mdx +++ b/platform-includes/performance/traces-sampler-as-filter/python.mdx @@ -1,5 +1,8 @@ ```python -def traces_sampler(sampling_context): +import sentry_sdk +from sentry_sdk.types import SamplingContext + +def traces_sampler(sampling_context: SamplingContext) -> float: if "...": # Drop this transaction, by setting its sample rate to 0% return 0 diff --git a/platform-includes/performance/traces-sampler-as-sampler/python.mdx b/platform-includes/performance/traces-sampler-as-sampler/python.mdx index 33b4d26f04e6b0..08df0fbe96d9ed 100644 --- a/platform-includes/performance/traces-sampler-as-sampler/python.mdx +++ b/platform-includes/performance/traces-sampler-as-sampler/python.mdx @@ -1,5 +1,8 @@ ```python -def traces_sampler(sampling_context): +import sentry_sdk +from sentry_sdk.types import SamplingContext + +def traces_sampler(sampling_context: SamplingContext) -> float: # Examine provided context data (including parent decision, if any) # along with anything in the global namespace to compute the sample rate # or sampling decision for this transaction From 539d81cd7997b57853ac6414f51dcf1b4f664fa5 Mon Sep 17 00:00:00 2001 From: Anton Pirker Date: Thu, 17 Apr 2025 15:15:06 +0200 Subject: [PATCH 3/4] fixed breadcrumbhint --- .../configuration/before-breadcrumb-hint/python.mdx | 2 +- .../enriching-events/breadcrumbs/before-breadcrumb/python.mdx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/platform-includes/configuration/before-breadcrumb-hint/python.mdx b/platform-includes/configuration/before-breadcrumb-hint/python.mdx index 1fcc71794a935e..b35a2df43448fd 100644 --- a/platform-includes/configuration/before-breadcrumb-hint/python.mdx +++ b/platform-includes/configuration/before-breadcrumb-hint/python.mdx @@ -2,7 +2,7 @@ import sentry_sdk from sentry_sdk.types import Breadcrumb, BreadcrumbHint -def before_breadcrumb(crumb: Breadcrumb, hint: Hint) -> Breadcrumb | None: +def before_breadcrumb(crumb: Breadcrumb, hint: BreadcrumbHint) -> Breadcrumb | None: if 'log_record' in hint: crumb['data']['thread'] = hint['log_record'].threadName diff --git a/platform-includes/enriching-events/breadcrumbs/before-breadcrumb/python.mdx b/platform-includes/enriching-events/breadcrumbs/before-breadcrumb/python.mdx index 4caabcd89b8eab..63764ca86afb6b 100644 --- a/platform-includes/enriching-events/breadcrumbs/before-breadcrumb/python.mdx +++ b/platform-includes/enriching-events/breadcrumbs/before-breadcrumb/python.mdx @@ -2,7 +2,7 @@ import sentry_sdk from sentry_sdk.types import Breadcrumb, BreadcrumbHint -def before_breadcrumb(crumb: Breadcrumb, hint: Hint) -> Breadcrumb | None: +def before_breadcrumb(crumb: Breadcrumb, hint: BreadcrumbHint) -> Breadcrumb | None: if crumb['category'] == 'a.spammy.Logger': return None From f2e0220be5db0b133bb20d25f4abbc422b4429cb Mon Sep 17 00:00:00 2001 From: Anton Pirker Date: Thu, 17 Apr 2025 15:29:35 +0200 Subject: [PATCH 4/4] better name --- platform-includes/configuration/error-sampler/python.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/platform-includes/configuration/error-sampler/python.mdx b/platform-includes/configuration/error-sampler/python.mdx index 0ea11caf3f4b7a..5a314be607fd49 100644 --- a/platform-includes/configuration/error-sampler/python.mdx +++ b/platform-includes/configuration/error-sampler/python.mdx @@ -3,7 +3,7 @@ import sentry_sdk from sentry_sdk.types import Event, Hint -def my_error_sampler(event: Event, hint: Hint) -> float: +def error_sampler(event: Event, hint: Hint) -> float: error_class = hint["exc_info"][0] if error_class == MyException: @@ -17,6 +17,6 @@ def my_error_sampler(event: Event, hint: Hint) -> float: sentry_sdk.init( # ... - error_sampler=my_error_sampler, + error_sampler=error_sampler, ) ```