or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-utilities.mddata-processing.mdenvelopes.mdenvironment.mderror-handling.mdindex.mdinstrumentation.mdlogging.mdstack-processing.mdtype-guards.md

instrumentation.mddocs/

0

# Instrumentation & Event Handling

1

2

**DEPRECATED**: Import all functions from `@sentry/core` instead of `@sentry/utils`.

3

4

Instrumentation handlers for automatically capturing console logs, network requests, errors, and other events in web and Node.js environments.

5

6

## Capabilities

7

8

### Console Instrumentation

9

10

Captures console method calls (log, warn, error, etc.) for breadcrumb generation.

11

12

```typescript { .api }

13

interface ConsoleLevel {

14

0: 'log';

15

1: 'warn';

16

2: 'error';

17

3: 'info';

18

4: 'debug';

19

5: 'assert';

20

}

21

22

/**

23

* Adds a handler for console instrumentation

24

* @param handler - Callback function that receives console level and arguments

25

*/

26

function addConsoleInstrumentationHandler(

27

handler: (level: ConsoleLevel[keyof ConsoleLevel], ...args: any[]) => void

28

): void;

29

```

30

31

**Usage Example:**

32

33

```typescript

34

import { addConsoleInstrumentationHandler } from "@sentry/core";

35

36

addConsoleInstrumentationHandler((level, ...args) => {

37

console.log(`Console ${level} called with:`, args);

38

39

// Create breadcrumb from console call

40

addBreadcrumb({

41

message: args.join(' '),

42

level: level as SeverityLevel,

43

category: 'console',

44

});

45

});

46

```

47

48

### Fetch Instrumentation

49

50

Captures fetch API calls for network request monitoring.

51

52

```typescript { .api }

53

interface FetchBreadcrumbData {

54

method: string;

55

url: string;

56

status_code?: number;

57

reason?: string;

58

start_timestamp: number;

59

end_timestamp?: number;

60

}

61

62

/**

63

* Adds a handler for fetch request instrumentation

64

* @param handler - Callback function that receives fetch data

65

*/

66

function addFetchInstrumentationHandler(

67

handler: (data: FetchBreadcrumbData) => void

68

): void;

69

70

/**

71

* Adds a handler for fetch request completion

72

* @param handler - Callback function that receives completed fetch data

73

*/

74

function addFetchEndInstrumentationHandler(

75

handler: (data: FetchBreadcrumbData) => void

76

): void;

77

```

78

79

**Usage Examples:**

80

81

```typescript

82

import {

83

addFetchInstrumentationHandler,

84

addFetchEndInstrumentationHandler

85

} from "@sentry/core";

86

87

// Track fetch requests

88

addFetchInstrumentationHandler((data) => {

89

console.log(`Fetch started: ${data.method} ${data.url}`);

90

});

91

92

// Track fetch completions

93

addFetchEndInstrumentationHandler((data) => {

94

console.log(`Fetch completed: ${data.status_code} in ${data.end_timestamp! - data.start_timestamp}ms`);

95

96

addBreadcrumb({

97

category: 'fetch',

98

data: {

99

method: data.method,

100

url: data.url,

101

status_code: data.status_code,

102

},

103

level: data.status_code && data.status_code >= 400 ? 'error' : 'info',

104

});

105

});

106

```

107

108

### Error Instrumentation

109

110

Captures global error events and unhandled promise rejections.

111

112

```typescript { .api }

113

interface ErrorEventData {

114

msg: string;

115

url: string;

116

line: number;

117

column: number;

118

error: Error;

119

}

120

121

interface UnhandledRejectionEventData {

122

reason: any;

123

promise: Promise<any>;

124

}

125

126

/**

127

* Adds a handler for global error events (window.onerror, process.on('uncaughtException'))

128

* @param handler - Callback function that receives error event data

129

*/

130

function addGlobalErrorInstrumentationHandler(

131

handler: (data: ErrorEventData) => void

132

): void;

133

134

/**

135

* Adds a handler for unhandled promise rejections

136

* @param handler - Callback function that receives rejection data

137

*/

138

function addGlobalUnhandledRejectionInstrumentationHandler(

139

handler: (data: UnhandledRejectionEventData) => void

140

): void;

141

```

142

143

**Usage Examples:**

144

145

```typescript

146

import {

147

addGlobalErrorInstrumentationHandler,

148

addGlobalUnhandledRejectionInstrumentationHandler

149

} from "@sentry/core";

150

151

// Capture global errors

152

addGlobalErrorInstrumentationHandler((data) => {

153

console.error('Global error:', data.error);

154

155

captureException(data.error, {

156

contexts: {

157

errorInfo: {

158

url: data.url,

159

line: data.line,

160

column: data.column,

161

},

162

},

163

});

164

});

165

166

// Capture unhandled promise rejections

167

addGlobalUnhandledRejectionInstrumentationHandler((data) => {

168

console.error('Unhandled rejection:', data.reason);

169

170

captureException(data.reason, {

171

tags: {

172

unhandledRejection: true,

173

},

174

});

175

});

176

```

177

178

### Generic Handler Management

179

180

Low-level instrumentation handler management for custom instrumentation.

181

182

```typescript { .api }

183

/**

184

* Adds a generic instrumentation handler

185

* @param type - Type of instrumentation (e.g., 'console', 'fetch', 'error')

186

* @param handler - Handler function

187

*/

188

function addHandler(type: string, handler: (...args: any[]) => void): void;

189

190

/**

191

* Triggers all handlers for a specific instrumentation type

192

* @param type - Type of instrumentation to trigger

193

* @param data - Data to pass to handlers

194

*/

195

function triggerHandlers(type: string, data: any): void;

196

197

/**

198

* Resets all instrumentation handlers (useful for testing)

199

*/

200

function resetInstrumentationHandlers(): void;

201

```

202

203

### Conditional Instrumentation

204

205

Utility for conditionally applying instrumentation based on environment or configuration.

206

207

```typescript { .api }

208

/**

209

* Conditionally instruments a function or object method

210

* @param obj - Object containing the method to instrument

211

* @param name - Name of the method to instrument

212

* @param replacement - Replacement function

213

* @param isActive - Function that determines if instrumentation should be active

214

*/

215

function maybeInstrument<T extends Record<string, any>>(

216

obj: T,

217

name: keyof T,

218

replacement: T[keyof T],

219

isActive?: () => boolean,

220

): void;

221

```

222

223

**Usage Example:**

224

225

```typescript

226

import { maybeInstrument, isBrowser } from "@sentry/core";

227

228

// Only instrument fetch in browser environments

229

maybeInstrument(

230

window,

231

'fetch',

232

function instrumentedFetch(this: Window, ...args) {

233

console.log('Fetch called with:', args);

234

return originalFetch.apply(this, args);

235

},

236

() => isBrowser()

237

);

238

```

239

240

## Instrumentation Setup Pattern

241

242

A typical instrumentation setup combines multiple handlers:

243

244

```typescript

245

import {

246

addConsoleInstrumentationHandler,

247

addFetchInstrumentationHandler,

248

addGlobalErrorInstrumentationHandler,

249

addGlobalUnhandledRejectionInstrumentationHandler,

250

isBrowser

251

} from "@sentry/core";

252

253

function setupInstrumentation() {

254

// Console logging

255

addConsoleInstrumentationHandler((level, ...args) => {

256

addBreadcrumb({

257

message: args.join(' '),

258

level: level as SeverityLevel,

259

category: 'console',

260

});

261

});

262

263

// Network requests (browser only)

264

if (isBrowser()) {

265

addFetchInstrumentationHandler((data) => {

266

addBreadcrumb({

267

category: 'fetch',

268

data: {

269

method: data.method,

270

url: data.url,

271

},

272

level: 'info',

273

});

274

});

275

}

276

277

// Global errors

278

addGlobalErrorInstrumentationHandler((data) => {

279

captureException(data.error);

280

});

281

282

// Unhandled rejections

283

addGlobalUnhandledRejectionInstrumentationHandler((data) => {

284

captureException(data.reason);

285

});

286

}

287

```

288

289

## Handler Types

290

291

### Available Instrumentation Types

292

293

- `console` - Console method calls

294

- `fetch` - Fetch API requests

295

- `xhr` - XMLHttpRequest calls (if available)

296

- `error` - Global error events

297

- `unhandledrejection` - Promise rejections

298

- `history` - History API changes (pushState, replaceState)

299

- `dom` - DOM events and mutations

300

301

### Handler Lifecycle

302

303

1. **Registration**: Handlers are registered using `addXInstrumentationHandler` functions

304

2. **Activation**: Handlers are automatically activated when the corresponding API is called

305

3. **Execution**: Handler callbacks receive structured data about the instrumented event

306

4. **Reset**: All handlers can be cleared using `resetInstrumentationHandlers()` (useful for testing)

307

308

**Migration Note**: All instrumentation functions have been moved from `@sentry/utils` to `@sentry/core`. Update your imports accordingly.