API

Complete API reference for Logger module

This page provides a complete API reference for all classes, interfaces, and utilities in the @vercube/logger package.

Logger (Abstract Class)

The Logger is an abstract base class that defines the interface for all logger implementations.

Signature

abstract class Logger {
  public abstract configure(options: LoggerTypes.Options): void;
  public abstract debug(...args: LoggerTypes.Arg[]): void;
  public abstract info(...args: LoggerTypes.Arg[]): void;
  public abstract warn(...args: LoggerTypes.Arg[]): void;
  public abstract error(...args: LoggerTypes.Arg[]): void;
}

Methods

configure()

Configures the logger with the provided options. Must be called before using the logger.

public abstract configure(options: LoggerTypes.Options): void

Parameters:

ParameterTypeDescription
optionsLoggerTypes.OptionsConfiguration options

Example:

container.get(Logger).configure({
  logLevel: 'info',
  providers: [
    {
      name: 'console',
      provider: ConsoleProvider
    }
  ]
});

debug()

Logs a debug message. Used for detailed debugging information.

public abstract debug(...args: LoggerTypes.Arg[]): void

Parameters:

ParameterTypeDescription
...argsLoggerTypes.Arg[]Any number of arguments to log

Examples:

logger.debug('User lookup started');
logger.debug('User data:', { id: 123, name: 'John' });
logger.debug('Query:', query, 'Result:', result);

info()

Logs an informational message. Used for general operational information.

public abstract info(...args: LoggerTypes.Arg[]): void

Parameters:

ParameterTypeDescription
...argsLoggerTypes.Arg[]Any number of arguments to log

Examples:

logger.info('Application started');
logger.info('User logged in', { userId: 'abc-123' });
logger.info('Request completed', { duration: 145, status: 200 });

warn()

Logs a warning message. Used for potentially harmful situations.

public abstract warn(...args: LoggerTypes.Arg[]): void

Parameters:

ParameterTypeDescription
...argsLoggerTypes.Arg[]Any number of arguments to log

Examples:

logger.warn('Rate limit approaching', { requests: 95, limit: 100 });
logger.warn('Deprecated API used', { endpoint: '/old/api' });
logger.warn('Slow query detected', { duration: 5000, query: '...' });

error()

Logs an error message. Used for serious problems that need attention.

public abstract error(...args: LoggerTypes.Arg[]): void

Parameters:

ParameterTypeDescription
...argsLoggerTypes.Arg[]Any number of arguments to log

Examples:

logger.error('Database connection failed', error);
logger.error('Payment processing failed', { orderId: '123', error });
logger.error('Unhandled exception', exception, { context: {...} });

BaseLogger (Class)

BaseLogger is the default implementation of the Logger abstract class. It manages providers and routes log messages to them based on log levels.

Signature

class BaseLogger implements Logger {
  public configure(options: LoggerTypes.Options): void;
  public debug(...args: LoggerTypes.Arg[]): void;
  public info(...args: LoggerTypes.Arg[]): void;
  public warn(...args: LoggerTypes.Arg[]): void;
  public error(...args: LoggerTypes.Arg[]): void;
  protected printMessage(message: LoggerTypes.Message): void;
}

Usage

Bind BaseLogger to Logger interface in your IOC container:

import { Logger, BaseLogger } from '@vercube/logger';

container.bind(Logger, BaseLogger);

Methods

All methods are inherited from Logger abstract class. See Logger section for details.

printMessage() (Protected)

Internal method that routes messages to providers based on log levels.

protected printMessage(message: LoggerTypes.Message): void

Note: This is a protected method not meant for direct use.


LoggerProvider (Abstract Class)

Abstract base class for implementing log providers. Providers handle the actual output of log messages.

Signature

abstract class LoggerProvider<T = unknown> {
  public abstract initialize(options: T): void | Promise<void>;
  public abstract processMessage(message: LoggerTypes.Message): void | Promise<void>;
}

Type Parameters

ParameterDescription
TType of options used to initialize the provider

Methods

initialize()

Initializes the provider with configuration options. Called once when the provider is registered.

public abstract initialize(options: T): void | Promise<void>

Parameters:

ParameterTypeDescription
optionsTProvider-specific configuration options

Example:

export class CustomProvider extends LoggerProvider<CustomOptions> {
  public initialize(options: CustomOptions): void {
    // Setup code: open files, connect to services, etc.
  }
}

processMessage()

Processes a log message. Called for every log message that passes the log level filter.

public abstract processMessage(message: LoggerTypes.Message): void | Promise<void>

Parameters:

ParameterTypeDescription
messageLoggerTypes.MessageThe log message to process

Example:

export class CustomProvider extends LoggerProvider {
  public processMessage(message: LoggerTypes.Message): void {
    const formatted = this.format(message);
    this.output(formatted);
  }
}

Types

LoggerTypes.Level

Log level enumeration.

type Level = 'debug' | 'info' | 'warn' | 'error'

Values:

LevelNumeric ValueDescription
debug1Detailed debugging information
info2General informational messages
warn3Warning messages
error4Error messages

Example:

const logLevel: LoggerTypes.Level = 'info';

LoggerTypes.Arg

Type for log arguments. Can be any value.

type Arg = any

Example:

const args: LoggerTypes.Arg[] = [
  'User logged in',
  { userId: 123 },
  new Date()
];

LoggerTypes.Message

Log message object structure passed to providers.

interface Message {
  level: Level;
  args: Arg[];
  tag?: string;
  pid?: number;
  type?: 'access_log' | 'application_log';
  timestamp?: number;
}

Properties:

PropertyTypeRequiredDescription
levelLevelYesLog level
argsArg[]YesArray of arguments to log
tagstringNoOptional tag for categorization
pidnumberNoProcess ID
typestringNoLog type (access_log or application_log)
timestampnumberNoUnix timestamp in milliseconds

Example:

const message: LoggerTypes.Message = {
  level: 'info',
  args: ['User logged in', { userId: 123 }],
  tag: 'AuthService',
  timestamp: Date.now(),
  type: 'application_log'
};

LoggerTypes.LogProviderOptions

Generic type for provider options.

type LogProviderOptions<T extends IOC.Newable<LoggerProvider>> = 
  Parameters<InstanceType<T>['initialize']>[0] & {
    logLevel?: Level;
  }

Type Parameters:

ParameterDescription
TProvider class type

Example:

interface CustomProviderOptions {
  endpoint: string;
  timeout?: number;
}

type CustomOptions = LoggerTypes.LogProviderOptions<typeof CustomProvider>;
// Result: CustomProviderOptions & { logLevel?: Level }

LoggerTypes.LogAppender

Configuration for a single provider.

interface LogAppender<T extends IOC.Newable<LoggerProvider>> {
  name: string;
  provider: T;
  logLevel?: Level;
  options?: LogProviderOptions<T>;
}

Properties:

PropertyTypeRequiredDescription
namestringYesUnique name for this provider instance
providerTYesProvider class reference
logLevelLevelNoOverride global log level for this provider
optionsobjectNoProvider-specific options

Example:

const appender: LoggerTypes.LogAppender<typeof ConsoleProvider> = {
  name: 'console',
  provider: ConsoleProvider,
  logLevel: 'debug'
};

LoggerTypes.Options

Complete logger configuration options.

interface Options {
  logLevel?: Level;
  providers?: LogAppender<any>[];
}

Properties:

PropertyTypeRequiredDescription
logLevelLevelNoGlobal log level (default: 'debug')
providersLogAppender[]NoArray of provider configurations

Example:

const options: LoggerTypes.Options = {
  logLevel: 'info',
  providers: [
    {
      name: 'console',
      provider: ConsoleProvider,
      logLevel: 'debug'
    },
    {
      name: 'json',
      provider: JSONProvider,
      logLevel: 'warn'
    }
  ]
};

Utilities

isLogLevelEnabled()

Checks if a target log level is enabled given the current log level.

function isLogLevelEnabled(
  targetLevel: LoggerTypes.Level,
  currentLevel: LoggerTypes.Level
): boolean

Parameters:

ParameterTypeDescription
targetLevelLevelThe level to check
currentLevelLevelThe currently configured level

Returns: boolean - True if target level should be logged

Example:

import { isLogLevelEnabled } from '@vercube/logger';

// Current level is 'info'
isLogLevelEnabled('debug', 'info');  // false - debug < info
isLogLevelEnabled('info', 'info');   // true - info === info
isLogLevelEnabled('warn', 'info');   // true - warn > info
isLogLevelEnabled('error', 'info');  // true - error > info

Usage in code:

if (isLogLevelEnabled('debug', currentLogLevel)) {
  // Only compute expensive debug data if debug logging is enabled
  const debugData = computeExpensiveDebugData();
  logger.debug('Debug data:', debugData);
}

colors

Object containing color functions for terminal output.

const colors: Record<string, ColorTextFn>

Type:

type ColorTextFn = (text: string) => string

Available colors:

FunctionDescription
colors.bold(text)Bold text
colors.green(text)Green text
colors.yellow(text)Yellow text
colors.red(text)Red text
colors.magentaBright(text)Bright magenta text
colors.cyanBright(text)Bright cyan text

Example:

import { colors } from '@vercube/logger';

console.log(colors.green('Success!'));
console.log(colors.red('Error!'));
console.log(colors.bold('Important message'));

Behavior:

  • Colors are automatically disabled when NO_COLOR environment variable is set
  • Colors work in terminals that support ANSI escape codes
  • Returns plain text in environments without color support

Type Declarations

Complete TypeScript type declarations for the logger module:

export namespace LoggerTypes {
  export type Level = 'debug' | 'info' | 'warn' | 'error';
  export type Arg = any;
  
  export interface Message {
    level: Level;
    args: Arg[];
    tag?: string;
    pid?: number;
    type?: 'access_log' | 'application_log';
    timestamp?: number;
  }
  
  export type LogProviderOptions<T extends IOC.Newable<LoggerProvider>> = 
    Parameters<InstanceType<T>['initialize']>[0] & {
      logLevel?: Level;
    };
  
  export interface LogAppender<T extends IOC.Newable<LoggerProvider>> {
    name: string;
    provider: T;
    logLevel?: Level;
    options?: LogProviderOptions<T>;
  }
  
  export interface Options {
    logLevel?: Level;
    providers?: LogAppender<any>[];
  }
}
Previous

Overview

Deploy your Vercube application to serverless platforms with zero configuration

Next