Skip to content

Commit 6260465

Browse files
codydeclaude
andcommitted
Python: Enhance documentation structure with comprehensive examples
Improves Python SDK documentation with better organization and detailed examples: ## Key Improvements - Enhanced feature selection with clear onboarding options - Improved configuration examples with detailed explanations - Added comprehensive error handling patterns (automatic and manual) - Enhanced logging examples with structured attributes - Added custom tracing examples with meaningful span attributes - Better organized verification steps and troubleshooting ## Documentation Structure Changes - Restructured flow for clearer step-by-step guidance - Added user context and tagging examples - Enhanced logging with practical use cases and error handling - Improved tracing examples with nested spans and performance attributes - Better organized next steps and additional resources - Enhanced troubleshooting section with multiple support channels 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent d80be14 commit 6260465

File tree

1 file changed

+204
-47
lines changed

1 file changed

+204
-47
lines changed

docs/platforms/python/index.mdx

Lines changed: 204 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
title: Python
3-
description: Sentry's Python SDK enables automatic reporting of errors and performance data in your application.
3+
description: Learn how to set up and configure Sentry in your Python application, capture your first errors, and view them in Sentry.
44
caseStyle: snake_case
55
supportLevel: production
66
sdk: sentry.python
@@ -10,21 +10,23 @@ categories:
1010
- serverless
1111
---
1212

13-
## Prerequisites
1413

15-
- You need a Sentry [account](https://sentry.io/signup/) and [project](/product/projects/)
16-
- Read one of our dedicated guides if you use any of the <PlatformLink to="/integrations/#web-frameworks">frameworks</PlatformLink> we support
14+
<PlatformContent includePath="getting-started-prerequisites" />
1715

1816
## Features
1917

20-
<p className="mb-5">
21-
Select which Sentry features you'd like to install in addition to Error
22-
Monitoring to get the corresponding installation and configuration
23-
instructions below.
24-
</p>
18+
In addition to capturing errors, you can monitor interactions between multiple services or applications by [enabling tracing](/concepts/key-terms/tracing/).
19+
20+
Send <PlatformLink to="/platforms/python/logs/">structured logs</PlatformLink> to Sentry and correlate them with errors and traces.
21+
22+
Select which Sentry features you'd like to configure to get the corresponding setup instructions below.
2523

2624
<OnboardingOptionButtons
27-
options={["error-monitoring", "performance", "profiling", "logs"]}
25+
options={[
26+
{id: "error-monitoring", checked: true},
27+
{id: "performance", checked: true},
28+
{id: "logs", checked: true},
29+
]}
2830
/>
2931

3032
## Install
@@ -35,75 +37,230 @@ Install the Sentry SDK using [`pip`](https://pip.pypa.io/en/stable/):
3537
pip install "sentry-sdk"
3638
```
3739

38-
```bash {tabTitle:uv}
39-
uv add "sentry-sdk"
40-
```
41-
4240
## Configure
4341

4442
Configuration should happen as **early as possible** in your application's lifecycle.
4543

46-
```python
44+
45+
46+
```python {filename:main.py}
4747
import sentry_sdk
4848

4949
sentry_sdk.init(
5050
dsn="___PUBLIC_DSN___",
51-
# Add request headers and IP for users,
52-
# see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
51+
52+
# Adds request headers and IP for users, for more info visit:
53+
# https://docs.sentry.io/platforms/python/data-management/data-collected/
5354
send_default_pii=True,
55+
56+
# ___PRODUCT_OPTION_START___ logs
57+
# Enable logs to be sent to Sentry
58+
_experiments={"enable_logs": True},
59+
# ___PRODUCT_OPTION_END___ logs
60+
5461
# ___PRODUCT_OPTION_START___ performance
5562
# Set traces_sample_rate to 1.0 to capture 100%
5663
# of transactions for tracing.
64+
# We recommend adjusting this value in production
65+
# Learn more at
66+
# https://docs.sentry.io/platforms/python/configuration/options/#traces-sample-rate
5767
traces_sample_rate=1.0,
5868
# ___PRODUCT_OPTION_END___ performance
59-
# ___PRODUCT_OPTION_START___ profiling
60-
# To collect profiles for all profile sessions,
61-
# set `profile_session_sample_rate` to 1.0.
62-
profile_session_sample_rate=1.0,
63-
# Profiles will be automatically collected while
64-
# there is an active span.
65-
profile_lifecycle="trace",
66-
# ___PRODUCT_OPTION_END___ profiling
67-
# ___PRODUCT_OPTION_START___ logs
68-
69-
# Enable logs to be sent to Sentry
70-
enable_logs=True,
71-
# ___PRODUCT_OPTION_END___ logs
7269
)
7370
```
7471

75-
However, in async applications, you need to call `sentry_sdk.init()` inside an `async` function to ensure async code is instrumented properly. We recommend calling `sentry_sdk.init()` at the beginning of the first `async` function you call, as demonstrated in the example below.
72+
## Step 3: Capture Python Errors
73+
74+
The Sentry SDK automatically captures unhandled exceptions. You can also manually capture errors and add context:
75+
76+
### Automatic Error Capture
77+
78+
```python
79+
# This will be automatically captured by Sentry
80+
division_by_zero = 1 / 0
81+
```
82+
83+
### Manual Error Capture
7684

7785
```python
78-
import asyncio
7986
import sentry_sdk
8087

81-
async def main():
82-
sentry_sdk.init(
83-
... # same as above
88+
try:
89+
risky_operation()
90+
except Exception as e:
91+
# Capture the exception with additional context
92+
sentry_sdk.capture_exception(e)
93+
```
94+
95+
<Alert>
96+
97+
Learn more about manually capturing errors in our <PlatformLink to="/usage/">Usage documentation</PlatformLink>.
98+
99+
</Alert>
100+
101+
### Adding User Context
102+
103+
```python
104+
import sentry_sdk
105+
106+
# Set user context for all future events
107+
sentry_sdk.set_user({
108+
"id": "123",
109+
"username": "jane.doe",
110+
"email": "[email protected]"
111+
})
112+
113+
# Add custom tags
114+
sentry_sdk.set_tag("page_locale", "en-us")
115+
116+
# Add custom context
117+
sentry_sdk.set_context("character", {
118+
"name": "Mighty Fighter",
119+
"age": 19,
120+
"attack_type": "melee"
121+
})
122+
```
123+
124+
<OnboardingOption optionId="performance">
125+
126+
<OnboardingOption optionId="logs">
127+
128+
## Step 4: Sending Logs
129+
130+
Now let's add structured logging to capture application insights. Logs are enabled in your configuration above.
131+
132+
Use Python's logging module to capture structured logs with meaningful attributes that help you debug issues and understand user behavior.
133+
134+
```python
135+
import logging
136+
137+
# Configure Python logging
138+
logger = logging.getLogger(__name__)
139+
140+
# Send structured logs with attributes
141+
logger.info(
142+
"User completed checkout",
143+
extra={
144+
"user_id": 123,
145+
"order_id": "order_456",
146+
"amount": 99.99
147+
}
148+
)
149+
150+
logger.error(
151+
"Payment processing failed",
152+
extra={
153+
"error_code": "CARD_DECLINED",
154+
"user_id": 123,
155+
"attempt_count": 3
156+
}
157+
)
158+
159+
# Log with exception information
160+
try:
161+
process_payment()
162+
except PaymentError as e:
163+
logger.exception(
164+
"Payment failed with exception",
165+
extra={"transaction_id": "txn_789"}
84166
)
167+
```
168+
169+
</OnboardingOption>
170+
171+
## Step 5: Custom Traces with Attributes
85172

86-
asyncio.run(main())
173+
Create custom spans to measure specific operations and add meaningful attributes. This helps you understand performance bottlenecks and debug issues with detailed context.
174+
175+
```python
176+
import sentry_sdk
177+
178+
# Create custom spans to measure specific operations
179+
def process_user_data(user_id):
180+
with sentry_sdk.start_span(
181+
op="function",
182+
description="Process User Data",
183+
data={
184+
"user_id": user_id,
185+
"operation": "data_processing",
186+
"version": "2.1"
187+
}
188+
) as span:
189+
# Your business logic here
190+
user_data = fetch_user_data(user_id)
191+
192+
# Nested span for specific operations
193+
with sentry_sdk.start_span(
194+
op="transform",
195+
description="Transform Data",
196+
data={
197+
"record_count": len(user_data),
198+
"transform_type": "normalize"
199+
}
200+
) as inner_span:
201+
result = transform_user_data(user_data)
202+
203+
return result
204+
205+
# Add attributes to existing spans
206+
span = sentry_sdk.get_current_span()
207+
if span:
208+
span.set_data("cache_hit", True)
209+
span.set_data("region", "us-west-2")
210+
span.set_data("performance_score", 0.95)
87211
```
88212

89-
## Verify
213+
</OnboardingOption>
90214

91-
Add this intentional error to your application to test that everything is working right away.
215+
## Verify Your Setup
92216

93-
```py
94-
division_by_zero = 1 / 0
217+
Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project.
218+
219+
### Test Error Capturing
220+
221+
Add the following test code to one of your Python files to trigger an error that Sentry will capture:
222+
223+
```python
224+
def trigger_error():
225+
# ___PRODUCT_OPTION_START___ logs
226+
division_by_zero = 1 / 0
227+
# ___PRODUCT_OPTION_END___ logs
228+
229+
# Call this function to test
230+
trigger_error()
95231
```
96232

97-
<Alert>
233+
Run your application and trigger the error to send it to Sentry.
98234

99-
Learn more about manually capturing an error or message in our <PlatformLink to="/usage/">Usage documentation</PlatformLink>.
100235

101-
</Alert>
236+
<PlatformContent includePath="getting-started-browser-sandbox-warning" />
102237

103-
To view and resolve the recorded error, log into [sentry.io](https://sentry.io) and select your project. Clicking on the error's title will open a page where you can see detailed information and mark it as resolved.
238+
### View Captured Data in Sentry
104239

105-
<Alert>
240+
Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear).
106241

107-
Not seeing your error in Sentry? Make sure you're running the above example from a file and not from a Python shell like IPython.
242+
<PlatformContent includePath="getting-started-verify-locate-data" />
108243

109-
</Alert>
244+
## Next Steps
245+
246+
At this point, you should have integrated Sentry into your Python application and should already be sending error and performance data to your Sentry project.
247+
248+
Now's a good time to customize your setup and look into more advanced topics:
249+
250+
- Extend Sentry to your frontend using one of our [JavaScript SDKs](/)
251+
- Continue to <PlatformLink to="/configuration">customize your configuration</PlatformLink>
252+
- Learn about [instrumenting your specific framework](/platforms/python/integrations/)
253+
- Learn how to <PlatformLink to="/usage">manually capture errors</PlatformLink>
254+
- Set up <PlatformLink to="/configuration/releases/">release tracking</PlatformLink>
255+
256+
<PlatformContent includePath="getting-started-features-expandable" />
257+
258+
<PlatformContent includePath="getting-started-tunneling" />
259+
260+
<Expandable permalink={false} title="Are you having problems setting up the SDK?">
261+
262+
- Check our [troubleshooting guide](/platforms/python/troubleshooting/)
263+
- Search for your issue in our [GitHub issues](https://github.com/getsentry/sentry-python/issues)
264+
- [Get support](https://sentry.zendesk.com/hc/en-us/)
265+
266+
</Expandable>

0 commit comments

Comments
 (0)