Skip to main content

API Reference

This section covers the complete API surface of the InversifyJS Logger package, including interfaces, enums, and concrete logger implementations.

Core Interfaces and Types

The InversifyJS Logger package provides a clean abstraction for logging functionality, allowing you to inject different logger implementations while maintaining a consistent interface.

Logger

The main logger interface that defines the contract for all logger implementations.

interface Logger {
log(logType: LogLevel, message: string, context?: ContextMetadata): void;
error(message: string, context?: ContextMetadata): void;
warn(message: string, context?: ContextMetadata): void;
info(message: string, context?: ContextMetadata): void;
http(message: string, context?: ContextMetadata): void;
verbose(message: string, context?: ContextMetadata): void;
debug(message: string, context?: ContextMetadata): void;
silly(message: string, context?: ContextMetadata): void;
}

The Logger interface provides methods for all standard log levels, plus a generic log method that accepts a LogLevel parameter. All methods accept an optional context parameter for providing additional metadata.

Example: Using the Logger interface

import type { Logger } from '@inversifyjs/logger';
import { ConsoleLogger, LogLevel } from '@inversifyjs/logger';

// Using the Logger interface for dependency injection
class UserService {
constructor(private readonly logger: Logger) {}

public createUser(userData: { email: string; name: string }): void {
this.logger.info('Creating new user', { email: userData.email });

try {
// Simulate user creation logic
this.logger.debug('Validating user data', userData);

// Using the generic log method with LogLevel enum
this.logger.log(LogLevel.INFO, 'User created successfully', {
context: 'UserService',
email: userData.email,
userId: 'generated-id',
});
} catch (error) {
this.logger.error('Failed to create user', {
email: userData.email,
error: String(error),
});

throw error;
}
}
}

// Inject a concrete logger implementation
const logger: Logger = new ConsoleLogger('UserService');
const userService: UserService = new UserService(logger);

userService.createUser({ email: 'user@example.com', name: 'John Doe' });

LogLevel

An enumeration defining the available log levels in order of severity.

enum LogLevel {
ERROR = 'error',
WARN = 'warn',
INFO = 'info',
HTTP = 'http',
VERBOSE = 'verbose',
DEBUG = 'debug',
SILLY = 'silly',
}

Log levels are ordered by severity, with ERROR being the highest severity and SILLY being the lowest. When configuring logger options, you can specify which log levels should be processed.

LoggerOptions

Configuration interface for customizing logger behavior.

interface LoggerOptions {
json?: boolean;
logTypes?: LogLevel[];
timestamp?: boolean;
}

Parameters:

  • json (optional boolean): When true, formats logs as JSON.
  • logTypes (optional LogLevel[]): Array of log levels to process. Messages with log levels not in this array will be ignored.
  • timestamp (optional boolean): When true, includes timestamps in log messages.

Example: Configuring logger options

import { ConsoleLogger, LoggerOptions, LogLevel } from '@inversifyjs/logger';

// Logger with custom options
const options: LoggerOptions = {
json: true,
logTypes: [LogLevel.ERROR, LogLevel.WARN, LogLevel.INFO],
timestamp: true,
};

const logger: ConsoleLogger = new ConsoleLogger('ConfiguredLogger', options);

// These will be logged (included in logTypes)
logger.error('This error will be logged');
logger.warn('This warning will be logged');
logger.info('This info will be logged');

// These will be ignored (not included in logTypes)
logger.debug('This debug message will be ignored');
logger.verbose('This verbose message will be ignored');

// Logger with different configuration
const timestampLogger: ConsoleLogger = new ConsoleLogger('TimestampLogger', {
json: false,
timestamp: true,
});

timestampLogger.info('This message includes a timestamp');

ContextMetadata

Interface for providing additional context data with log messages.

interface ContextMetadata {
[key: string]: unknown;
context?: string | undefined;
}

The ContextMetadata interface allows you to attach arbitrary key-value pairs to log messages. The special context property can be used to override the logger's default context name for specific log messages.

Example: Using context metadata

import { ConsoleLogger } from '@inversifyjs/logger';

const logger: ConsoleLogger = new ConsoleLogger('UserService');

// Basic logging with context
const userContext: Record<string, unknown> = {
action: 'login',
context: 'Authentication',
userId: '12345',
};

logger.info('User login attempt', userContext);
logger.error('Login failed', { ...userContext, reason: 'Invalid password' });

// Using different log levels
logger.debug('Debug information', { requestId: 'req-001' });
logger.verbose('Verbose information', { module: 'UserService' });
logger.silly('Silly level logging', { details: 'Very detailed info' });

Logger Implementations

The InversifyJS Logger package provides several concrete logger implementations based on the Winston logging library. All implementations extend the base WinstonLoggerAdapter class and implement the Logger interface.

ConsoleLogger

A logger implementation that outputs to the console/terminal.

class ConsoleLogger extends WinstonLoggerAdapter {
constructor(context?: string, loggerOptions?: LoggerOptions)
}

Parameters:

  • context (optional string): A context name that will be included in log messages to identify the source.
  • loggerOptions (optional LoggerOptions): Configuration options for customizing logger behavior.

Example: Console logging

import { ConsoleLogger } from '@inversifyjs/logger';

const consoleLogger: ConsoleLogger = new ConsoleLogger('MyAwesomeApp');

consoleLogger.debug('This is a debug message');
consoleLogger.error('This is an error message');
consoleLogger.info('This is an info message');
consoleLogger.warn('This is a warning message');

FileLogger

A logger implementation that writes logs to a file.

class FileLogger extends WinstonLoggerAdapter {
constructor(fileName: string, context?: string, loggerOptions?: LoggerOptions)
}

Parameters:

  • fileName (string): Path to the log file. The file will be created if it doesn't exist.
  • context (optional string): A context name that will be included in log messages to identify the source.
  • loggerOptions (optional LoggerOptions): Configuration options for customizing logger behavior.

Example: File logging

import { FileLogger } from '@inversifyjs/logger';

const fileLogger: FileLogger = new FileLogger('./temp/app.log', 'MyAwesomeApp');

fileLogger.debug('This is a debug message');
fileLogger.error('This is an error message');
fileLogger.info('This is an info message');
fileLogger.warn('This is a warning message');

HttpLogger

A logger implementation that sends logs to an HTTP endpoint.

class HttpLogger extends WinstonLoggerAdapter {
constructor(url: URL | string, context?: string, loggerOptions?: LoggerOptions)
}

Parameters:

  • url (URL | string): The HTTP endpoint where logs should be sent. Can be a string URL or a URL object.
  • context (optional string): A context name that will be included in log messages to identify the source.
  • loggerOptions (optional LoggerOptions): Configuration options for customizing logger behavior.

Notes:

  • The HTTP logger sends log data via HTTP POST requests to the specified endpoint.
  • The target endpoint should be configured to accept and process log data.
  • Consider using HTTPS endpoints for production environments to ensure log data is transmitted securely.

Example: HTTP logging

import { HttpLogger } from '@inversifyjs/logger';

export const httpLogger: HttpLogger = new HttpLogger(
'http://localhost:5341/api/events/raw',
'MyAwesomeApp',
{
json: true,
},
);

httpLogger.debug('This is a debug message');
httpLogger.error('This is an error message');
httpLogger.info('This is an info message');
httpLogger.warn('This is a warning message');

StreamLogger

A logger implementation that writes to a Node.js writable stream.

class StreamLogger extends WinstonLoggerAdapter {
constructor(
stream: NodeJS.WritableStream,
eol?: string | undefined,
context?: string,
loggerOptions?: LoggerOptions
)
}

Parameters:

  • stream (NodeJS.WritableStream): The writable stream where logs should be written (e.g., process.stdout, process.stderr, or a file stream).
  • eol (optional string): End-of-line character(s) to use. Defaults to the system's default line ending.
  • context (optional string): A context name that will be included in log messages to identify the source.
  • loggerOptions (optional LoggerOptions): Configuration options for customizing logger behavior.

Example: Stream logging

import process from 'node:process';

import { StreamLogger } from '@inversifyjs/logger';

export const streamLogger: StreamLogger = new StreamLogger(
process.stdout,
'MyAwesomeApp',
);

streamLogger.debug('This is a debug message');
streamLogger.error('This is an error message');
streamLogger.info('This is an info message');
streamLogger.warn('This is a warning message');

Log Message Formatting

All logger implementations support two output formats:

Human-readable Format (default)

When json: false or when the json option is omitted, logs are formatted as:

[Context] - ProcessID Timestamp LogLevel: Message

Example:

[MyAwesomeApp] - 12345 2023-09-18 02:30:45.123 PM info: User login successful

JSON Format

When json: true, logs are formatted as structured JSON objects:

{
"level": "info",
"message": "User login successful",
"timestamp": "2023-09-18 02:30:45.123 PM",
"context": "MyAwesomeApp",
"userId": "12345",
"action": "login"
}