CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sentry--utils

Deprecated utilities package for Sentry JavaScript SDKs - all functionality moved to @sentry/core

Pending
Overview
Eval results
Files

logging.mddocs/

Logging & Console

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

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

Capabilities

Logger Interface

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

interface Logger {
  /** Disables all logging output */
  disable(): void;
  /** Enables logging output */
  enable(): void;
  /** Logs informational messages */
  log(...args: any[]): void;
  /** Logs warning messages */
  warn(...args: any[]): void;
  /** Logs error messages */
  error(...args: any[]): void;
  /** Logs debug messages (when debug level enabled) */
  debug(...args: any[]): void;
}

/**
 * Global logger instance used throughout Sentry SDKs
 */
declare const logger: Logger;

Usage Examples:

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

// Basic logging
logger.log('Processing user data...');
logger.warn('Deprecated API usage detected');
logger.error('Failed to send event to Sentry');
logger.debug('Detailed debugging information');

// Conditional logging
function processData(data: any) {
  logger.log('Starting data processing');
  
  try {
    // Process data
    const result = transformData(data);
    logger.log('Data processing completed successfully');
    return result;
  } catch (error) {
    logger.error('Data processing failed:', error);
    throw error;
  }
}

// Disable logging in production
if (process.env.NODE_ENV === 'production') {
  logger.disable();
}

Console Level Constants

Constants defining available console log levels.

/**
 * Array of available console log levels in priority order
 */
declare const CONSOLE_LEVELS: readonly [
  'debug',
  'info', 
  'warn',
  'error',
  'log',
  'assert',
  'trace'
];

Usage Example:

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

// Iterate through all console levels
CONSOLE_LEVELS.forEach(level => {
  console.log(`Console level: ${level}`);
});

// Check if a level is valid
function isValidConsoleLevel(level: string): level is typeof CONSOLE_LEVELS[number] {
  return CONSOLE_LEVELS.includes(level as any);
}

Console Sandboxing

Utility for executing code with temporarily modified console methods.

/**
 * Executes a callback with console methods temporarily replaced/modified
 * @param callback - Function to execute within the console sandbox
 * @returns Result of the callback function
 */
function consoleSandbox<T>(callback: () => T): T;

Usage Examples:

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

// Execute code without console output
const result = consoleSandbox(() => {
  console.log('This will not appear in console');
  console.warn('Neither will this');
  return performCalculation();
});

// Custom console behavior during testing
function runSilentTest() {
  const logs: string[] = [];
  
  const testResult = consoleSandbox(() => {
    // Temporarily capture console output instead of displaying it
    const originalLog = console.log;
    console.log = (...args) => {
      logs.push(args.join(' '));
    };
    
    try {
      return runTestSuite();
    } finally {
      console.log = originalLog;
    }
  });
  
  return { result: testResult, capturedLogs: logs };
}

Original Console Methods

Preserved references to original console methods before any instrumentation.

/**
 * Object containing references to original console methods before instrumentation
 */
declare const originalConsoleMethods: {
  /** Original console.log method */
  log: (...args: any[]) => void;
  /** Original console.warn method */
  warn: (...args: any[]) => void;
  /** Original console.error method */
  error: (...args: any[]) => void;
  /** Original console.debug method */
  debug: (...args: any[]) => void;
  /** Original console.info method */
  info: (...args: any[]) => void;
  /** Original console.trace method */
  trace: (...args: any[]) => void;
  /** Original console.assert method */
  assert: (condition?: boolean, ...data: any[]) => void;
};

Usage Examples:

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

// Always use original console methods, bypassing any instrumentation
function criticalErrorLogger(message: string, error: Error) {
  // This will always output to console even if console is instrumented
  originalConsoleMethods.error('CRITICAL ERROR:', message, error);
}

// Restore original console methods
function restoreConsole() {
  console.log = originalConsoleMethods.log;
  console.warn = originalConsoleMethods.warn;
  console.error = originalConsoleMethods.error;
  console.debug = originalConsoleMethods.debug;
}

// Compare instrumented vs original behavior
function debugConsoleInstrumentation() {
  console.log('This goes through instrumentation');
  originalConsoleMethods.log('This bypasses instrumentation');
}

Logging Patterns

Structured Logging

Pattern for consistent structured logging across an application:

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

interface LogContext {
  userId?: string;
  requestId?: string;
  component: string;
  action: string;
}

class StructuredLogger {
  constructor(private context: LogContext) {}
  
  info(message: string, data?: any) {
    logger.log(JSON.stringify({
      level: 'info',
      message,
      context: this.context,
      data,
      timestamp: new Date().toISOString()
    }));
  }
  
  warn(message: string, data?: any) {
    logger.warn(JSON.stringify({
      level: 'warn',
      message,
      context: this.context,
      data,
      timestamp: new Date().toISOString()
    }));
  }
  
  error(message: string, error?: Error) {
    logger.error(JSON.stringify({
      level: 'error',
      message,
      context: this.context,
      error: error ? {
        name: error.name,
        message: error.message,
        stack: error.stack
      } : undefined,
      timestamp: new Date().toISOString()
    }));
  }
}

// Usage
const apiLogger = new StructuredLogger({
  component: 'api',
  action: 'user-creation'
});

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

Conditional Development Logging

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

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

class DevelopmentLogger {
  private isDevelopment = process.env.NODE_ENV === 'development';
  
  dev(message: string, ...args: any[]) {
    if (this.isDevelopment) {
      logger.log(`[DEV] ${message}`, ...args);
    }
  }
  
  devWarn(message: string, ...args: any[]) {
    if (this.isDevelopment) {
      logger.warn(`[DEV] ${message}`, ...args);
    }
  }
  
  devError(message: string, ...args: any[]) {
    if (this.isDevelopment) {
      logger.error(`[DEV] ${message}`, ...args);
    }
  }
}

const devLogger = new DevelopmentLogger();

// These only log in development
devLogger.dev('User state changed', userState);
devLogger.devWarn('Performance warning: slow query detected');

Console Interception

Pattern for intercepting and processing console output:

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

class ConsoleInterceptor {
  private interceptedLogs: Array<{
    level: string;
    args: any[];
    timestamp: Date;
  }> = [];
  
  startInterception() {
    // Store original methods
    const originalLog = console.log;
    const originalWarn = console.warn;
    const originalError = console.error;
    
    // Replace with intercepting versions
    console.log = (...args) => {
      this.interceptedLogs.push({
        level: 'log',
        args,
        timestamp: new Date()
      });
      originalLog.apply(console, args);
    };
    
    console.warn = (...args) => {
      this.interceptedLogs.push({
        level: 'warn',
        args,
        timestamp: new Date()
      });
      originalWarn.apply(console, args);
    };
    
    console.error = (...args) => {
      this.interceptedLogs.push({
        level: 'error',
        args,
        timestamp: new Date()
      });
      originalError.apply(console, args);
    };
  }
  
  stopInterception() {
    console.log = originalConsoleMethods.log;
    console.warn = originalConsoleMethods.warn;
    console.error = originalConsoleMethods.error;
  }
  
  getInterceptedLogs() {
    return this.interceptedLogs.slice(); // Return copy
  }
  
  clearLogs() {
    this.interceptedLogs.length = 0;
  }
}

Silent Execution

Pattern for executing code without console output:

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

function executeSilently<T>(fn: () => T): T {
  return consoleSandbox(() => {
    // Temporarily silence all console output
    const noop = () => {};
    console.log = noop;
    console.warn = noop;
    console.error = noop;
    console.debug = noop;
    console.info = noop;
    
    try {
      return fn();
    } finally {
      // Console methods are automatically restored by consoleSandbox
    }
  });
}

// Usage
const result = executeSilently(() => {
  console.log('This will not appear');
  return performCalculation();
});

Logger Configuration

Environment-Based Configuration

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

function configureLogger() {
  const env = process.env.NODE_ENV;
  const logLevel = process.env.LOG_LEVEL;
  
  switch (env) {
    case 'production':
      // Minimal logging in production
      if (logLevel !== 'debug') {
        logger.disable();
      }
      break;
      
    case 'test':
      // Silent during tests unless explicitly enabled
      if (!process.env.ENABLE_TEST_LOGS) {
        logger.disable();
      }
      break;
      
    case 'development':
    default:
      // Full logging in development
      logger.enable();
      break;
  }
}

// Initialize logging configuration
configureLogger();

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

Install with Tessl CLI

npx tessl i tessl/npm-sentry--utils

docs

async-utilities.md

data-processing.md

envelopes.md

environment.md

error-handling.md

index.md

instrumentation.md

logging.md

stack-processing.md

type-guards.md

tile.json