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

logging.mddocs/

0

# Logging & Console

1

2

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

3

4

Centralized logging system with console sandboxing, original method preservation, and configurable log levels for debugging and monitoring.

5

6

## Capabilities

7

8

### Logger Interface

9

10

Central logger instance with configurable levels and enable/disable functionality.

11

12

```typescript { .api }

13

interface Logger {

14

/** Disables all logging output */

15

disable(): void;

16

/** Enables logging output */

17

enable(): void;

18

/** Logs informational messages */

19

log(...args: any[]): void;

20

/** Logs warning messages */

21

warn(...args: any[]): void;

22

/** Logs error messages */

23

error(...args: any[]): void;

24

/** Logs debug messages (when debug level enabled) */

25

debug(...args: any[]): void;

26

}

27

28

/**

29

* Global logger instance used throughout Sentry SDKs

30

*/

31

declare const logger: Logger;

32

```

33

34

**Usage Examples:**

35

36

```typescript

37

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

38

39

// Basic logging

40

logger.log('Processing user data...');

41

logger.warn('Deprecated API usage detected');

42

logger.error('Failed to send event to Sentry');

43

logger.debug('Detailed debugging information');

44

45

// Conditional logging

46

function processData(data: any) {

47

logger.log('Starting data processing');

48

49

try {

50

// Process data

51

const result = transformData(data);

52

logger.log('Data processing completed successfully');

53

return result;

54

} catch (error) {

55

logger.error('Data processing failed:', error);

56

throw error;

57

}

58

}

59

60

// Disable logging in production

61

if (process.env.NODE_ENV === 'production') {

62

logger.disable();

63

}

64

```

65

66

### Console Level Constants

67

68

Constants defining available console log levels.

69

70

```typescript { .api }

71

/**

72

* Array of available console log levels in priority order

73

*/

74

declare const CONSOLE_LEVELS: readonly [

75

'debug',

76

'info',

77

'warn',

78

'error',

79

'log',

80

'assert',

81

'trace'

82

];

83

```

84

85

**Usage Example:**

86

87

```typescript

88

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

89

90

// Iterate through all console levels

91

CONSOLE_LEVELS.forEach(level => {

92

console.log(`Console level: ${level}`);

93

});

94

95

// Check if a level is valid

96

function isValidConsoleLevel(level: string): level is typeof CONSOLE_LEVELS[number] {

97

return CONSOLE_LEVELS.includes(level as any);

98

}

99

```

100

101

### Console Sandboxing

102

103

Utility for executing code with temporarily modified console methods.

104

105

```typescript { .api }

106

/**

107

* Executes a callback with console methods temporarily replaced/modified

108

* @param callback - Function to execute within the console sandbox

109

* @returns Result of the callback function

110

*/

111

function consoleSandbox<T>(callback: () => T): T;

112

```

113

114

**Usage Examples:**

115

116

```typescript

117

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

118

119

// Execute code without console output

120

const result = consoleSandbox(() => {

121

console.log('This will not appear in console');

122

console.warn('Neither will this');

123

return performCalculation();

124

});

125

126

// Custom console behavior during testing

127

function runSilentTest() {

128

const logs: string[] = [];

129

130

const testResult = consoleSandbox(() => {

131

// Temporarily capture console output instead of displaying it

132

const originalLog = console.log;

133

console.log = (...args) => {

134

logs.push(args.join(' '));

135

};

136

137

try {

138

return runTestSuite();

139

} finally {

140

console.log = originalLog;

141

}

142

});

143

144

return { result: testResult, capturedLogs: logs };

145

}

146

```

147

148

### Original Console Methods

149

150

Preserved references to original console methods before any instrumentation.

151

152

```typescript { .api }

153

/**

154

* Object containing references to original console methods before instrumentation

155

*/

156

declare const originalConsoleMethods: {

157

/** Original console.log method */

158

log: (...args: any[]) => void;

159

/** Original console.warn method */

160

warn: (...args: any[]) => void;

161

/** Original console.error method */

162

error: (...args: any[]) => void;

163

/** Original console.debug method */

164

debug: (...args: any[]) => void;

165

/** Original console.info method */

166

info: (...args: any[]) => void;

167

/** Original console.trace method */

168

trace: (...args: any[]) => void;

169

/** Original console.assert method */

170

assert: (condition?: boolean, ...data: any[]) => void;

171

};

172

```

173

174

**Usage Examples:**

175

176

```typescript

177

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

178

179

// Always use original console methods, bypassing any instrumentation

180

function criticalErrorLogger(message: string, error: Error) {

181

// This will always output to console even if console is instrumented

182

originalConsoleMethods.error('CRITICAL ERROR:', message, error);

183

}

184

185

// Restore original console methods

186

function restoreConsole() {

187

console.log = originalConsoleMethods.log;

188

console.warn = originalConsoleMethods.warn;

189

console.error = originalConsoleMethods.error;

190

console.debug = originalConsoleMethods.debug;

191

}

192

193

// Compare instrumented vs original behavior

194

function debugConsoleInstrumentation() {

195

console.log('This goes through instrumentation');

196

originalConsoleMethods.log('This bypasses instrumentation');

197

}

198

```

199

200

## Logging Patterns

201

202

### Structured Logging

203

204

Pattern for consistent structured logging across an application:

205

206

```typescript

207

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

208

209

interface LogContext {

210

userId?: string;

211

requestId?: string;

212

component: string;

213

action: string;

214

}

215

216

class StructuredLogger {

217

constructor(private context: LogContext) {}

218

219

info(message: string, data?: any) {

220

logger.log(JSON.stringify({

221

level: 'info',

222

message,

223

context: this.context,

224

data,

225

timestamp: new Date().toISOString()

226

}));

227

}

228

229

warn(message: string, data?: any) {

230

logger.warn(JSON.stringify({

231

level: 'warn',

232

message,

233

context: this.context,

234

data,

235

timestamp: new Date().toISOString()

236

}));

237

}

238

239

error(message: string, error?: Error) {

240

logger.error(JSON.stringify({

241

level: 'error',

242

message,

243

context: this.context,

244

error: error ? {

245

name: error.name,

246

message: error.message,

247

stack: error.stack

248

} : undefined,

249

timestamp: new Date().toISOString()

250

}));

251

}

252

}

253

254

// Usage

255

const apiLogger = new StructuredLogger({

256

component: 'api',

257

action: 'user-creation'

258

});

259

260

apiLogger.info('Creating new user', { email: 'user@example.com' });

261

```

262

263

### Conditional Development Logging

264

265

Pattern for development-only logging that's automatically removed in production:

266

267

```typescript

268

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

269

270

class DevelopmentLogger {

271

private isDevelopment = process.env.NODE_ENV === 'development';

272

273

dev(message: string, ...args: any[]) {

274

if (this.isDevelopment) {

275

logger.log(`[DEV] ${message}`, ...args);

276

}

277

}

278

279

devWarn(message: string, ...args: any[]) {

280

if (this.isDevelopment) {

281

logger.warn(`[DEV] ${message}`, ...args);

282

}

283

}

284

285

devError(message: string, ...args: any[]) {

286

if (this.isDevelopment) {

287

logger.error(`[DEV] ${message}`, ...args);

288

}

289

}

290

}

291

292

const devLogger = new DevelopmentLogger();

293

294

// These only log in development

295

devLogger.dev('User state changed', userState);

296

devLogger.devWarn('Performance warning: slow query detected');

297

```

298

299

### Console Interception

300

301

Pattern for intercepting and processing console output:

302

303

```typescript

304

import { originalConsoleMethods, consoleSandbox } from "@sentry/core";

305

306

class ConsoleInterceptor {

307

private interceptedLogs: Array<{

308

level: string;

309

args: any[];

310

timestamp: Date;

311

}> = [];

312

313

startInterception() {

314

// Store original methods

315

const originalLog = console.log;

316

const originalWarn = console.warn;

317

const originalError = console.error;

318

319

// Replace with intercepting versions

320

console.log = (...args) => {

321

this.interceptedLogs.push({

322

level: 'log',

323

args,

324

timestamp: new Date()

325

});

326

originalLog.apply(console, args);

327

};

328

329

console.warn = (...args) => {

330

this.interceptedLogs.push({

331

level: 'warn',

332

args,

333

timestamp: new Date()

334

});

335

originalWarn.apply(console, args);

336

};

337

338

console.error = (...args) => {

339

this.interceptedLogs.push({

340

level: 'error',

341

args,

342

timestamp: new Date()

343

});

344

originalError.apply(console, args);

345

};

346

}

347

348

stopInterception() {

349

console.log = originalConsoleMethods.log;

350

console.warn = originalConsoleMethods.warn;

351

console.error = originalConsoleMethods.error;

352

}

353

354

getInterceptedLogs() {

355

return this.interceptedLogs.slice(); // Return copy

356

}

357

358

clearLogs() {

359

this.interceptedLogs.length = 0;

360

}

361

}

362

```

363

364

### Silent Execution

365

366

Pattern for executing code without console output:

367

368

```typescript

369

import { consoleSandbox, originalConsoleMethods } from "@sentry/core";

370

371

function executeSilently<T>(fn: () => T): T {

372

return consoleSandbox(() => {

373

// Temporarily silence all console output

374

const noop = () => {};

375

console.log = noop;

376

console.warn = noop;

377

console.error = noop;

378

console.debug = noop;

379

console.info = noop;

380

381

try {

382

return fn();

383

} finally {

384

// Console methods are automatically restored by consoleSandbox

385

}

386

});

387

}

388

389

// Usage

390

const result = executeSilently(() => {

391

console.log('This will not appear');

392

return performCalculation();

393

});

394

```

395

396

## Logger Configuration

397

398

### Environment-Based Configuration

399

400

```typescript

401

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

402

403

function configureLogger() {

404

const env = process.env.NODE_ENV;

405

const logLevel = process.env.LOG_LEVEL;

406

407

switch (env) {

408

case 'production':

409

// Minimal logging in production

410

if (logLevel !== 'debug') {

411

logger.disable();

412

}

413

break;

414

415

case 'test':

416

// Silent during tests unless explicitly enabled

417

if (!process.env.ENABLE_TEST_LOGS) {

418

logger.disable();

419

}

420

break;

421

422

case 'development':

423

default:

424

// Full logging in development

425

logger.enable();

426

break;

427

}

428

}

429

430

// Initialize logging configuration

431

configureLogger();

432

```

433

434

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