or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ai-monitoring.mdconfiguration.mdcontext-metadata.mdcron-monitoring.mdevent-capture.mdindex.mdintegrations.mdperformance-monitoring.mdprofiling.mdscope-management.mdstructured-logging.md

index.mddocs/

0

# Sentry SDK

1

2

The official Python SDK for Sentry, providing comprehensive error monitoring, performance tracking, and application observability. The SDK automatically captures exceptions, performance issues, and custom events from Python applications with extensive integration support for popular frameworks including Django, Flask, FastAPI, Celery, and 40+ other libraries.

3

4

## Package Information

5

6

- **Package Name**: sentry-sdk

7

- **Language**: Python

8

- **Installation**: `pip install sentry-sdk`

9

10

## Core Imports

11

12

```python

13

import sentry_sdk

14

```

15

16

For direct access to specific functions:

17

18

```python

19

from sentry_sdk import init, capture_exception, capture_message, start_transaction

20

```

21

22

## Basic Usage

23

24

```python

25

import sentry_sdk

26

27

# Initialize the SDK

28

sentry_sdk.init(

29

dsn="https://your-dsn@sentry.io/project-id",

30

# Set traces_sample_rate to 1.0 to capture 100% of transactions for performance monitoring

31

traces_sample_rate=1.0,

32

)

33

34

# Automatic exception capture

35

try:

36

division_by_zero = 1 / 0

37

except Exception as e:

38

# Exception is automatically captured by Sentry

39

pass

40

41

# Manual event capture

42

sentry_sdk.capture_message("Something important happened!")

43

44

# Manual exception capture with additional context

45

try:

46

risky_operation()

47

except Exception as e:

48

sentry_sdk.capture_exception(e)

49

50

# Performance monitoring

51

with sentry_sdk.start_transaction(name="my-transaction"):

52

# Your application logic here

53

process_data()

54

```

55

56

## Architecture

57

58

The Sentry SDK uses a modern scope-based architecture with three distinct scope levels:

59

60

- **Global Scope**: Process-wide data (release, environment, server details)

61

- **Isolation Scope**: Request/user-level data (user context, request details)

62

- **Current Scope**: Local thread/async context data (span-specific tags, breadcrumbs)

63

64

This design enables proper context isolation in concurrent environments while maintaining performance and providing flexible configuration options for different deployment scenarios.

65

66

## Capabilities

67

68

### Initialization and Configuration

69

70

SDK initialization and configuration management including DSN setup, sampling rates, integrations, and client options.

71

72

```python { .api }

73

def init(*args, **kwargs) -> None: ...

74

def is_initialized() -> bool: ...

75

```

76

77

[Configuration](./configuration.md)

78

79

### Event Capture

80

81

Manual and automatic capture of exceptions, messages, and custom events with context preservation and filtering capabilities.

82

83

```python { .api }

84

def capture_exception(error=None, scope=None, **scope_kwargs) -> Optional[str]: ...

85

def capture_message(message, level=None, scope=None, **scope_kwargs) -> Optional[str]: ...

86

def capture_event(event, hint=None, scope=None, **scope_kwargs) -> Optional[str]: ...

87

```

88

89

[Event Capture](./event-capture.md)

90

91

### Scope Management

92

93

Context management through a three-tier scope system providing isolation and data organization across global, request, and local levels.

94

95

```python { .api }

96

def get_global_scope() -> Scope: ...

97

def get_isolation_scope() -> Scope: ...

98

def get_current_scope() -> Scope: ...

99

def new_scope() -> ContextManager[Scope]: ...

100

def isolation_scope() -> ContextManager[Scope]: ...

101

```

102

103

[Scope Management](./scope-management.md)

104

105

### Context and Metadata

106

107

Setting user information, tags, extra data, context objects, and breadcrumbs for enhanced debugging and event correlation.

108

109

```python { .api }

110

def set_user(value) -> None: ...

111

def set_tag(key, value) -> None: ...

112

def set_tags(tags) -> None: ...

113

def set_extra(key, value) -> None: ...

114

def set_context(key, value) -> None: ...

115

def add_breadcrumb(crumb=None, hint=None, **kwargs) -> None: ...

116

```

117

118

[Context and Metadata](./context-metadata.md)

119

120

### Performance Monitoring

121

122

Distributed tracing with transactions and spans for monitoring application performance, database queries, and external service calls.

123

124

```python { .api }

125

def start_transaction(transaction=None, **kwargs) -> Union[Transaction, NoOpSpan]: ...

126

def start_span(**kwargs) -> Span: ...

127

def get_current_span(scope=None) -> Optional[Span]: ...

128

def continue_trace(environ_or_headers, op=None, name=None, source=None, origin="manual") -> Transaction: ...

129

def trace(func) -> Callable: ...

130

```

131

132

[Performance Monitoring](./performance-monitoring.md)

133

134

### Integrations

135

136

Framework and library integrations for automatic instrumentation including web frameworks, databases, HTTP clients, task queues, and AI/ML libraries.

137

138

```python { .api }

139

class Integration(ABC):

140

identifier: str

141

@staticmethod

142

@abstractmethod

143

def setup_once() -> None: ...

144

```

145

146

Available integrations include Django, Flask, FastAPI, Celery, SQLAlchemy, Redis, AWS Lambda, OpenAI, Anthropic, and 30+ others.

147

148

[Integrations](./integrations.md)

149

150

### Structured Logging

151

152

OpenTelemetry-compatible structured logging interface with automatic correlation to Sentry events and performance data.

153

154

```python { .api }

155

def trace(template, **kwargs) -> None: ...

156

def debug(template, **kwargs) -> None: ...

157

def info(template, **kwargs) -> None: ...

158

def warning(template, **kwargs) -> None: ...

159

def error(template, **kwargs) -> None: ...

160

def fatal(template, **kwargs) -> None: ...

161

```

162

163

[Structured Logging](./structured-logging.md)

164

165

### Cron Monitoring

166

167

Scheduled job monitoring with automatic check-ins, failure detection, and alerting for cron jobs and scheduled tasks.

168

169

```python { .api }

170

def monitor(monitor_slug: str = None, **monitor_config) -> Callable: ...

171

def capture_checkin(

172

monitor_slug: str = None,

173

check_in_id: str = None,

174

status: MonitorStatus = None,

175

duration: float = None,

176

**monitor_config

177

) -> str: ...

178

```

179

180

[Cron Monitoring](./cron-monitoring.md)

181

182

### Profiling

183

184

CPU profiling capabilities for performance analysis with support for different scheduling backends and continuous profiling.

185

186

```python { .api }

187

def start_profiler() -> None: ...

188

def stop_profiler() -> None: ...

189

class Profile:

190

def __init__(self, transaction: Transaction): ...

191

def finish(self) -> None: ...

192

```

193

194

[Profiling](./profiling.md)

195

196

### AI Monitoring

197

198

AI-native performance tracking and observability for artificial intelligence workflows, including LLM calls, AI pipeline execution, and token usage monitoring.

199

200

```python { .api }

201

def ai_track(description: str, **span_kwargs) -> Callable[[F], F]: ...

202

def set_ai_pipeline_name(name: Optional[str]) -> None: ...

203

def get_ai_pipeline_name() -> Optional[str]: ...

204

def record_token_usage(

205

span: Span,

206

input_tokens: Optional[int] = None,

207

input_tokens_cached: Optional[int] = None,

208

output_tokens: Optional[int] = None,

209

output_tokens_reasoning: Optional[int] = None,

210

total_tokens: Optional[int] = None

211

) -> None: ...

212

```

213

214

[AI Monitoring](./ai-monitoring.md)

215

216

## Core Classes

217

218

### Scope

219

220

Context container for events, spans, and metadata with hierarchical inheritance and isolated modification capabilities.

221

222

```python { .api }

223

class Scope:

224

@staticmethod

225

def get_current_scope() -> Scope: ...

226

@staticmethod

227

def get_isolation_scope() -> Scope: ...

228

@staticmethod

229

def get_global_scope() -> Scope: ...

230

231

def set_user(self, value) -> None: ...

232

def set_tag(self, key, value) -> None: ...

233

def set_extra(self, key, value) -> None: ...

234

def set_context(self, key, value) -> None: ...

235

def add_breadcrumb(self, crumb=None, hint=None, **kwargs) -> None: ...

236

def start_transaction(self, **kwargs) -> Union[Transaction, NoOpSpan]: ...

237

def start_span(self, **kwargs) -> Span: ...

238

```

239

240

### Client

241

242

Primary interface for event transport and SDK configuration with support for custom transports, event processing, and integration management.

243

244

```python { .api }

245

class Client:

246

def __init__(self, *args, **kwargs): ...

247

def is_active(self) -> bool: ...

248

def capture_event(self, event, hint=None, scope=None) -> Optional[str]: ...

249

def capture_exception(self, error=None, scope=None, **scope_kwargs) -> Optional[str]: ...

250

def capture_message(self, message, level=None, scope=None, **scope_kwargs) -> Optional[str]: ...

251

def flush(self, timeout=None, callback=None) -> bool: ...

252

def close(self, timeout=None, callback=None) -> bool: ...

253

```

254

255

### Transport

256

257

Event delivery mechanism with support for HTTP transport, custom backends, and envelope-based event batching.

258

259

```python { .api }

260

class Transport(ABC):

261

@abstractmethod

262

def capture_envelope(self, envelope) -> None: ...

263

264

class HttpTransport(Transport):

265

def __init__(self, options): ...

266

def capture_envelope(self, envelope) -> None: ...

267

```

268

269

## Utility Functions

270

271

```python { .api }

272

def flush(timeout=None, callback=None) -> bool: ...

273

def last_event_id() -> Optional[str]: ...

274

def get_traceparent() -> Optional[str]: ...

275

def get_baggage() -> Optional[str]: ...

276

def set_measurement(name, value, unit="") -> None: ... # Deprecated

277

def set_transaction_name(name, source=None) -> None: ...

278

def update_current_span(op=None, name=None, attributes=None, data=None) -> None: ...

279

```

280

281

## Constants and Types

282

283

```python { .api }

284

# Version

285

VERSION: str = "2.36.0"

286

287

# Enums

288

class LogLevel:

289

TRACE = "trace"

290

DEBUG = "debug"

291

INFO = "info"

292

WARNING = "warning"

293

ERROR = "error"

294

FATAL = "fatal"

295

296

class MonitorStatus:

297

OK = "ok"

298

ERROR = "error"

299

IN_PROGRESS = "in_progress"

300

TIMEOUT = "timeout"

301

UNKNOWN = "unknown"

302

303

class SPANTEMPLATE:

304

DEFAULT = "default"

305

AI_AGENT = "ai_agent"

306

AI_TOOL = "ai_tool"

307

AI_CHAT = "ai_chat"

308

309

class INSTRUMENTER:

310

SENTRY = "sentry"

311

OTEL = "otel"

312

313

class EndpointType:

314

ENVELOPE = "envelope"

315

316

class CompressionAlgo:

317

GZIP = "gzip"

318

BROTLI = "br"

319

320

# Configuration Constants

321

DEFAULT_MAX_VALUE_LENGTH: int = 100_000

322

DEFAULT_MAX_BREADCRUMBS: int = 100

323

DEFAULT_QUEUE_SIZE: int = 100

324

325

# Type definitions

326

Breadcrumb = Dict[str, Any]

327

Event = Dict[str, Any]

328

Hint = Dict[str, Any]

329

ExcInfo = Tuple[Optional[type], Optional[BaseException], Optional[types.TracebackType]]

330

```