CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-langfuse--core

Core functions and utilities for Langfuse packages including API client, logging, media handling, and OpenTelemetry tracing attributes

Overview
Eval results
Files

logger.mddocs/

Logger System

Configurable logging infrastructure for the Langfuse SDK with multiple severity levels, custom prefixes, timestamps, and both global singleton and instance-based usage patterns.

Capabilities

LogLevel Enum

Enumeration of log levels in order of severity (lowest to highest).

enum LogLevel {
  DEBUG = 0,
  INFO = 1,
  WARN = 2,
  ERROR = 3
}

Values:

  • DEBUG = 0 - Detailed debug information for troubleshooting development issues
  • INFO = 1 - General informational messages about application flow
  • WARN = 2 - Warning messages for potentially harmful situations
  • ERROR = 3 - Critical errors that may cause application failure

Import:

import { LogLevel } from '@langfuse/core';

Logger Class

A configurable logger class that supports different log levels, custom prefixes, and optional timestamps.

class Logger {
  constructor(config?: LoggerConfig);

  error(message: string, ...args: unknown[]): void;
  warn(message: string, ...args: unknown[]): void;
  info(message: string, ...args: unknown[]): void;
  debug(message: string, ...args: unknown[]): void;
  setLevel(level: LogLevel): void;
  getLevel(): LogLevel;
}

interface LoggerConfig {
  level: LogLevel;
  prefix?: string;
  enableTimestamp?: boolean;
}

Import:

import { Logger, LoggerConfig, LogLevel } from '@langfuse/core';

Constructor

Creates a new Logger instance with optional configuration.

constructor(config?: LoggerConfig)

Parameters:

  • config (optional) - Configuration object for the logger
    • level: LogLevel - The minimum log level to output (required if config provided)
    • prefix?: string - Optional prefix to prepend to all log messages
    • enableTimestamp?: boolean - Whether to include timestamps (default: true)

Usage Example:

import { Logger, LogLevel } from '@langfuse/core';

// Create logger with debug level
const logger = new Logger({
  level: LogLevel.DEBUG,
  prefix: 'Langfuse SDK',
  enableTimestamp: true
});

logger.debug('Initialization started');
logger.info('Connected to API');
logger.warn('Rate limit approaching');
logger.error('Failed to send batch', { batchSize: 10 });

error()

Logs an error message if the logger's level is ERROR or lower.

/**
 * Logs an error message with optional additional arguments
 * @param message - The error message to log
 * @param args - Additional arguments to log (objects, errors, etc.)
 */
error(message: string, ...args: unknown[]): void;

Usage Example:

logger.error('Failed to fetch trace', { traceId: 'abc123' });

try {
  // some operation
} catch (error) {
  logger.error('Operation failed', error);
}

warn()

Logs a warning message if the logger's level is WARN or lower.

/**
 * Logs a warning message with optional additional arguments
 * @param message - The warning message to log
 * @param args - Additional arguments to log
 */
warn(message: string, ...args: unknown[]): void;

Usage Example:

logger.warn('Retry attempt 3 of 5', { endpoint: '/api/traces' });

info()

Logs an informational message if the logger's level is INFO or lower.

/**
 * Logs an informational message with optional additional arguments
 * @param message - The info message to log
 * @param args - Additional arguments to log
 */
info(message: string, ...args: unknown[]): void;

Usage Example:

logger.info('Batch sent successfully', { batchSize: 50 });

debug()

Logs a debug message if the logger's level is DEBUG.

/**
 * Logs a debug message with optional additional arguments
 * @param message - The debug message to log
 * @param args - Additional arguments to log
 */
debug(message: string, ...args: unknown[]): void;

Usage Example:

logger.debug('Request details', { url: '/api/traces', method: 'POST' });

setLevel()

Updates the minimum log level for the logger.

/**
 * Sets the minimum log level
 * @param level - The new minimum log level
 */
setLevel(level: LogLevel): void;

Usage Example:

// Start with info level
const logger = new Logger({ level: LogLevel.INFO });

// Enable debug logging for troubleshooting
logger.setLevel(LogLevel.DEBUG);
logger.debug('Now debug messages will appear');

// Back to info for production
logger.setLevel(LogLevel.INFO);

getLevel()

Retrieves the current minimum log level.

/**
 * Gets the current minimum log level
 * @returns The current log level
 */
getLevel(): LogLevel;

Usage Example:

const currentLevel = logger.getLevel();
console.log(`Current log level: ${LogLevel[currentLevel]}`);

Global Logger Functions

Convenience functions for working with the global singleton logger instance.

function configureGlobalLogger(config: LoggerConfig): void;
function getGlobalLogger(): Logger;
function resetGlobalLogger(): void;

Import:

import {
  configureGlobalLogger,
  getGlobalLogger,
  resetGlobalLogger,
  LogLevel
} from '@langfuse/core';

configureGlobalLogger()

Configures the global logger with new settings. Should be called early in application initialization before any logging occurs.

/**
 * Configures the global singleton logger
 * @param config - Logger configuration
 */
function configureGlobalLogger(config: LoggerConfig): void;

Usage Example:

import { configureGlobalLogger, LogLevel } from '@langfuse/core';

// Configure at app startup
configureGlobalLogger({
  level: LogLevel.INFO,
  prefix: 'MyApp',
  enableTimestamp: true
});

getGlobalLogger()

Gets the global singleton logger instance.

/**
 * Gets the global singleton logger instance
 * @returns The global logger instance
 */
function getGlobalLogger(): Logger;

Usage Example:

import { getGlobalLogger } from '@langfuse/core';

const logger = getGlobalLogger();
logger.info('Using global logger');

resetGlobalLogger()

Resets the global logger instance and configuration. Primarily used for testing.

/**
 * Resets the global logger instance and configuration
 * Used primarily for testing purposes
 */
function resetGlobalLogger(): void;

Usage Example:

import { resetGlobalLogger } from '@langfuse/core';

// In test cleanup
afterEach(() => {
  resetGlobalLogger();
});

createLogger()

Creates a new independent Logger instance with the specified configuration. Unlike the global logger, this creates an isolated instance.

/**
 * Creates a new Logger instance independent of the global singleton
 * @param config - Optional logger configuration
 * @returns A new Logger instance
 */
function createLogger(config?: LoggerConfig): Logger;

Import:

import { createLogger, LogLevel } from '@langfuse/core';

Usage Example:

import { createLogger, LogLevel } from '@langfuse/core';

// Create custom logger for a specific module
const moduleLogger = createLogger({
  level: LogLevel.DEBUG,
  prefix: 'TraceProcessor',
  enableTimestamp: true
});

moduleLogger.debug('Processing trace batch');

logger (LoggerSingleton)

Direct access to the LoggerSingleton class for advanced usage patterns. This provides an alternative way to access the global logger singleton.

/**
 * The singleton logger instance for convenient access
 */
export const logger: typeof LoggerSingleton;

class LoggerSingleton {
  static getInstance(): Logger;
  static configure(config: LoggerConfig): void;
  static reset(): void;
}

Import:

import { logger } from '@langfuse/core';

Usage Example:

import { logger, LogLevel } from '@langfuse/core';

// Access global logger via singleton
const globalLogger = logger.getInstance();
globalLogger.info('Quick logging access');

// Configure via singleton
logger.configure({
  level: LogLevel.DEBUG,
  prefix: 'Langfuse SDK',
  enableTimestamp: true
});

// Reset via singleton (useful for testing)
logger.reset();

Usage Patterns

Global Logger Pattern

Use the global logger singleton for application-wide logging with consistent configuration.

import { configureGlobalLogger, getGlobalLogger, LogLevel } from '@langfuse/core';

// Configure once at application startup
configureGlobalLogger({
  level: process.env.NODE_ENV === 'production' ? LogLevel.INFO : LogLevel.DEBUG,
  prefix: 'Langfuse',
  enableTimestamp: true
});

// Use anywhere in your application
function processTraces() {
  const logger = getGlobalLogger();
  logger.info('Starting trace processing');
  // ... processing logic
}

Instance-Based Pattern

Create dedicated logger instances for different modules or components.

import { createLogger, LogLevel } from '@langfuse/core';

class TraceService {
  private logger: Logger;

  constructor() {
    this.logger = createLogger({
      level: LogLevel.INFO,
      prefix: 'TraceService'
    });
  }

  async processTrace(traceId: string) {
    this.logger.debug('Processing trace', { traceId });
    try {
      // ... processing
      this.logger.info('Trace processed successfully', { traceId });
    } catch (error) {
      this.logger.error('Failed to process trace', { traceId, error });
      throw error;
    }
  }
}

Environment-Based Configuration

Configure logging based on environment variables.

import { configureGlobalLogger, LogLevel, getEnv } from '@langfuse/core';

// Map environment variable to LogLevel
const logLevelMap: Record<string, LogLevel> = {
  'DEBUG': LogLevel.DEBUG,
  'INFO': LogLevel.INFO,
  'WARN': LogLevel.WARN,
  'ERROR': LogLevel.ERROR
};

const logLevelStr = getEnv('LANGFUSE_LOG_LEVEL') || 'INFO';
const logLevel = logLevelMap[logLevelStr] ?? LogLevel.INFO;

configureGlobalLogger({
  level: logLevel,
  prefix: 'Langfuse SDK',
  enableTimestamp: true
});

Conditional Debug Logging

Enable debug logging only when needed without affecting production.

import { Logger, LogLevel } from '@langfuse/core';

const logger = new Logger({
  level: process.env.DEBUG ? LogLevel.DEBUG : LogLevel.INFO
});

// Debug messages only appear when DEBUG env var is set
logger.debug('Detailed request information', {
  headers: { /* ... */ },
  body: { /* ... */ }
});

Type Definitions

enum LogLevel {
  DEBUG = 0,
  INFO = 1,
  WARN = 2,
  ERROR = 3
}

interface LoggerConfig {
  level: LogLevel;
  prefix?: string;
  enableTimestamp?: boolean;
}

class Logger {
  constructor(config?: LoggerConfig);
  error(message: string, ...args: unknown[]): void;
  warn(message: string, ...args: unknown[]): void;
  info(message: string, ...args: unknown[]): void;
  debug(message: string, ...args: unknown[]): void;
  setLevel(level: LogLevel): void;
  getLevel(): LogLevel;
}

Best Practices

  1. Configure Early: Set up the global logger at application startup before any SDK operations
  2. Use Appropriate Levels: Reserve ERROR for actual failures, WARN for potential issues, INFO for key events
  3. Include Context: Pass relevant context objects as additional arguments for better debugging
  4. Avoid Sensitive Data: Never log API keys, passwords, or other sensitive information
  5. Production Logging: Use INFO or WARN level in production to reduce noise
  6. Development Debugging: Enable DEBUG level during development for detailed troubleshooting
  7. Module Prefixes: Use unique prefixes for different modules when creating multiple logger instances
  8. Error Objects: Always pass Error objects to logging methods for proper stack traces

Install with Tessl CLI

npx tessl i tessl/npm-langfuse--core

docs

api-client.md

api-resources.md

constants.md

errors.md

index.md

logger.md

media.md

utils.md

tile.json