or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

breadcrumb-system.mdcontext-management.mdcore-client.mddata-processing.mdframework-integrations.mdindex.mdlogging-integration.mdtransport-layer.md

core-client.mddocs/

0

# Core Client

1

2

The Client class is the primary interface for capturing and sending events to Sentry. It manages configuration, event processing, context, and communication with Sentry servers.

3

4

## Capabilities

5

6

### Client Initialization

7

8

Initialize a Sentry client with DSN and configuration options.

9

10

```python { .api }

11

class Client:

12

def __init__(self, dsn=None, raise_send_errors=False, transport=None,

13

install_sys_hook=True, install_logging_hook=True,

14

hook_libraries=None, enable_breadcrumbs=True,

15

processors=None, _random_seed=None, **options):

16

"""

17

Initialize Sentry client.

18

19

Parameters:

20

- dsn (str): Sentry Data Source Name URL

21

- raise_send_errors (bool): Raise errors on send failures

22

- transport (Transport): Custom transport implementation

23

- install_sys_hook (bool): Install sys.excepthook handler

24

- install_logging_hook (bool): Install logging breadcrumb hook

25

- hook_libraries (list): Libraries to hook for breadcrumbs

26

- enable_breadcrumbs (bool): Enable breadcrumb collection

27

- processors (list): Data processing pipeline

28

"""

29

```

30

31

### Exception Capture

32

33

Capture and report exceptions with full stack traces and context.

34

35

```python { .api }

36

def captureException(self, exc_info=None, **kwargs):

37

"""

38

Capture exception and send to Sentry.

39

40

Parameters:

41

- exc_info (tuple): Exception info tuple (type, value, traceback)

42

- data (dict): Additional event data

43

- extra (dict): Extra context data

44

- fingerprint (list): Custom fingerprint for grouping

45

- level (str): Event level ('error', 'warning', 'info', etc.)

46

- logger (str): Logger name

47

- tags (dict): Event tags

48

49

Returns:

50

str: Event ID

51

"""

52

```

53

54

### Message Capture

55

56

Capture custom messages and log entries.

57

58

```python { .api }

59

def captureMessage(self, message, **kwargs):

60

"""

61

Capture message event.

62

63

Parameters:

64

- message (str): Message text

65

- level (str): Log level ('debug', 'info', 'warning', 'error', 'fatal')

66

- data (dict): Additional event data

67

- extra (dict): Extra context data

68

- params (tuple): Message formatting parameters

69

- stack (bool): Include stack trace

70

71

Returns:

72

str: Event ID

73

"""

74

```

75

76

### Query Capture

77

78

Capture SQL queries and database operations for performance monitoring.

79

80

```python { .api }

81

def captureQuery(self, query, params=(), engine=None, **kwargs):

82

"""

83

Capture SQL query event.

84

85

Parameters:

86

- query (str): SQL query string

87

- params (tuple): Query parameters

88

- engine (str): Database engine name

89

- time_spent (float): Query execution time

90

91

Returns:

92

str: Event ID

93

"""

94

```

95

96

### Generic Event Capture

97

98

Capture custom event types with arbitrary data.

99

100

```python { .api }

101

def capture(self, event_type, **kwargs):

102

"""

103

Capture generic event.

104

105

Parameters:

106

- event_type (str): Event type identifier

107

- message (str): Event message

108

- data (dict): Event-specific data

109

- extra (dict): Extra context data

110

- fingerprint (list): Custom fingerprint

111

112

Returns:

113

str: Event ID

114

"""

115

```

116

117

### Context Management

118

119

Set context information that will be included with all events.

120

121

```python { .api }

122

def user_context(self, data):

123

"""

124

Set user context information.

125

126

Parameters:

127

- data (dict): User data with keys like 'id', 'username', 'email', 'ip_address'

128

"""

129

130

def tags_context(self, data):

131

"""

132

Set tags for event categorization and filtering.

133

134

Parameters:

135

- data (dict): Tag key-value pairs

136

"""

137

138

def extra_context(self, data):

139

"""

140

Set extra context data for debugging.

141

142

Parameters:

143

- data (dict): Additional context information

144

"""

145

146

def http_context(self, data):

147

"""

148

Set HTTP request context.

149

150

Parameters:

151

- data (dict): HTTP context with 'url', 'method', 'headers', etc.

152

"""

153

```

154

155

### Breadcrumb Management

156

157

Record breadcrumbs for tracking user actions and application state.

158

159

```python { .api }

160

def captureBreadcrumb(self, message=None, timestamp=None, level=None,

161

category=None, data=None, type=None, processor=None):

162

"""

163

Record breadcrumb for context tracking.

164

165

Parameters:

166

- message (str): Breadcrumb message

167

- timestamp (datetime): Breadcrumb timestamp

168

- level (str): Breadcrumb level

169

- category (str): Breadcrumb category

170

- data (dict): Additional breadcrumb data

171

- type (str): Breadcrumb type

172

- processor (callable): Custom breadcrumb processor

173

"""

174

```

175

176

### Event Building and Sending

177

178

Build event data structures and send to Sentry.

179

180

```python { .api }

181

def build_msg(self, event_type, data=None, date=None, time_spent=None,

182

extra=None, stack=None, tags=None, fingerprint=None, **kwargs):

183

"""

184

Build event data structure.

185

186

Parameters:

187

- event_type (str): Type of event

188

- data (dict): Event-specific data

189

- date (datetime): Event timestamp

190

- time_spent (float): Time spent processing

191

- extra (dict): Extra context

192

- stack (bool): Include stack trace

193

- tags (dict): Event tags

194

- fingerprint (list): Custom fingerprint

195

196

Returns:

197

dict: Event data structure

198

"""

199

200

def send(self, **data):

201

"""

202

Send event data to Sentry.

203

204

Parameters:

205

- **data: Event data dictionary

206

207

Returns:

208

str: Event ID

209

"""

210

```

211

212

### Exception Handling Context Manager

213

214

Automatic exception capture using context manager or decorator.

215

216

```python { .api }

217

def capture_exceptions(self, function_or_exceptions=None, **kwargs):

218

"""

219

Wrap function or code block to automatically capture exceptions.

220

221

Can be used as a decorator or context manager.

222

223

Parameters:

224

- function_or_exceptions (callable|tuple): Function to wrap or exception types to catch

225

- **kwargs: Additional parameters passed to captureException

226

227

Returns:

228

callable|contextmanager: Decorator or context manager

229

"""

230

```

231

232

### Client State and Utilities

233

234

Check client status and get version information.

235

236

```python { .api }

237

def is_enabled(self):

238

"""

239

Check if client should attempt to send events.

240

241

Returns:

242

bool: True if client is enabled and can send events

243

"""

244

245

def should_capture(self, exc_info):

246

"""

247

Determine if exception should be captured based on ignore rules.

248

249

Parameters:

250

- exc_info (tuple): Exception info tuple (type, value, traceback)

251

252

Returns:

253

bool: True if exception should be captured

254

"""

255

256

def get_module_versions(self):

257

"""

258

Get version information for included modules.

259

260

Returns:

261

dict: Module name to version mapping

262

"""

263

```

264

265

### Configuration and Utilities

266

267

Access client configuration and utility methods.

268

269

```python { .api }

270

def get_public_dsn(self, scheme=None):

271

"""

272

Get public DSN for client-side usage.

273

274

Parameters:

275

- scheme (str): URL scheme override

276

277

Returns:

278

str: Public DSN URL

279

"""

280

281

@property

282

def context(self):

283

"""

284

Get thread-local context manager.

285

286

Returns:

287

Context: Context instance for current thread

288

"""

289

290

@property

291

def last_event_id(self):

292

"""

293

Get ID of last captured event.

294

295

Returns:

296

str: Last event ID

297

"""

298

```

299

300

## Usage Examples

301

302

### Basic Error Capture

303

304

```python

305

from raven import Client

306

307

client = Client('https://your-dsn@sentry.io/project-id')

308

309

try:

310

result = risky_operation()

311

except Exception as e:

312

event_id = client.captureException()

313

print(f"Error captured with ID: {event_id}")

314

```

315

316

### Message Logging

317

318

```python

319

# Log different severity levels

320

client.captureMessage('User login successful', level='info')

321

client.captureMessage('Database connection slow', level='warning')

322

client.captureMessage('Critical system failure', level='error')

323

```

324

325

### Context Usage

326

327

```python

328

# Set user context

329

client.user_context({

330

'id': 123,

331

'username': 'john_doe',

332

'email': 'john@example.com'

333

})

334

335

# Set custom tags

336

client.tags_context({

337

'environment': 'production',

338

'version': '1.2.3',

339

'feature_flag': 'new_checkout'

340

})

341

342

# Add extra debugging info

343

client.extra_context({

344

'request_id': 'req_abc123',

345

'user_agent': 'Mozilla/5.0...',

346

'session_duration': 1847

347

})

348

```

349

350

### Breadcrumb Tracking

351

352

```python

353

# Record user actions

354

client.captureBreadcrumb(

355

message='User clicked checkout button',

356

category='ui.click',

357

level='info',

358

data={'button_id': 'checkout-btn'}

359

)

360

361

client.captureBreadcrumb(

362

message='Payment processing started',

363

category='payment',

364

level='info',

365

data={'amount': 99.99, 'currency': 'USD'}

366

)

367

368

# When an error occurs, breadcrumbs provide context

369

try:

370

process_payment()

371

except PaymentError:

372

client.captureException() # Includes breadcrumb history

373

```

374

375

### Exception Context Manager Usage

376

377

```python

378

# As a decorator

379

@client.capture_exceptions

380

def risky_function():

381

return 1 / 0 # Exception automatically captured

382

383

# As a context manager

384

with client.capture_exceptions():

385

risky_operation() # Any exception is captured and re-raised

386

387

# Specify specific exceptions to capture

388

@client.capture_exceptions((IOError, ValueError))

389

def file_operation():

390

with open('nonexistent.txt') as f:

391

return f.read()

392

393

# With additional context

394

with client.capture_exceptions(extra={'operation': 'file_upload'}):

395

upload_file()

396

```

397

398

### Client State Checking

399

400

```python

401

# Check if client is enabled before expensive operations

402

if client.is_enabled():

403

try:

404

expensive_operation()

405

except Exception:

406

client.captureException()

407

408

# Check if specific exception should be captured

409

try:

410

risky_operation()

411

except Exception as e:

412

exc_info = sys.exc_info()

413

if client.should_capture(exc_info):

414

client.captureException(exc_info)

415

416

# Get module version information

417

versions = client.get_module_versions()

418

print(f"Python version: {versions.get('python')}")

419

print(f"Django version: {versions.get('django', 'Not installed')}")

420

```