CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-winston

A comprehensive, multi-transport logging library for Node.js applications providing flexible and extensible logging capabilities.

Pending
Overview
Eval results
Files

container-management.mddocs/

Container Management

Container class for managing multiple named logger instances with shared configurations and lifecycle management.

Capabilities

Container Class

The Container class provides an inversion of control pattern for managing multiple Winston logger instances by string identifiers.

/**
 * Container for managing multiple named logger instances
 */
class Container {
  constructor(options?: LoggerOptions);
  
  /** Map of logger instances by ID */
  loggers: Map<string, Logger>;
  /** Default options for new loggers */
  options: LoggerOptions;
}

interface LoggerOptions {
  /** Custom logging levels configuration */
  levels?: object;
  /** Suppress all logging output */
  silent?: boolean;
  /** Log message formatting configuration */
  format?: Format;
  /** Minimum logging level */
  level?: string;
  /** Controls process exit behavior on error */
  exitOnError?: Function | boolean;
  /** Default metadata to include with all log messages */
  defaultMeta?: any;
  /** Transport or array of transports for log output */
  transports?: Transport[] | Transport;
  /** Automatically handle uncaught exceptions */
  handleExceptions?: boolean;
  /** Automatically handle unhandled promise rejections */
  handleRejections?: boolean;
  /** Transports specifically for exception handling */
  exceptionHandlers?: any;
  /** Transports specifically for rejection handling */
  rejectionHandlers?: any;
}

Usage Examples:

const winston = require('winston');

// Create container with default options
const container = new winston.Container({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.Console()
  ]
});

// Create container with shared transports
const sharedContainer = new winston.Container({
  transports: [
    new winston.transports.File({ filename: 'shared.log' })
  ]
});

Logger Management

Methods for adding, retrieving, and managing logger instances within the container.

/**
 * Add or create a logger instance with the specified ID
 * @param id - Unique identifier for the logger
 * @param options - Optional configuration overriding container defaults
 * @returns Logger instance
 */
add(id: string, options?: LoggerOptions): Logger;

/**
 * Get a logger instance by ID, creating if it doesn't exist
 * @param id - Unique identifier for the logger
 * @param options - Optional configuration overriding container defaults
 * @returns Logger instance
 */
get(id: string, options?: LoggerOptions): Logger;

/**
 * Check if a logger with the specified ID exists
 * @param id - Logger identifier to check
 * @returns True if logger exists
 */
has(id: string): boolean;

/**
 * Close and remove logger(s) from the container
 * @param id - Optional logger ID to close (omit to close all)
 */
close(id?: string): void;

Usage Examples:

const winston = require('winston');

const container = new winston.Container({
  format: winston.format.json(),
  transports: [
    new winston.transports.Console()
  ]
});

// Add/create loggers
const apiLogger = container.add('api', {
  level: 'debug',
  defaultMeta: { service: 'api' }
});

const dbLogger = container.add('database', {
  level: 'warn',
  defaultMeta: { service: 'database' },
  transports: [
    new winston.transports.File({ filename: 'db.log' })
  ]
});

// Get existing logger (same as add if already exists)
const sameApiLogger = container.get('api');
console.log(apiLogger === sameApiLogger); // true

// Check existence
if (container.has('api')) {
  const logger = container.get('api');
  logger.info('API logger exists');
}

// Close specific logger
container.close('api');

// Close all loggers
container.close();

Default Container Instance

Winston provides a default container instance accessible via winston.loggers for convenient multi-logger management.

/**
 * Default container instance available on winston module
 */
const loggers: Container;

Usage Examples:

const winston = require('winston');

// Use default container
const userLogger = winston.loggers.get('user', {
  level: 'info',
  format: winston.format.simple(),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'user.log' })
  ]
});

const authLogger = winston.loggers.get('auth', {
  level: 'debug',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'auth.log' })
  ]
});

// Use loggers
userLogger.info('User registered', { userId: 123 });
authLogger.debug('Authentication attempt', { username: 'john' });

// In another file, get same logger instance
const sameUserLogger = winston.loggers.get('user');
sameUserLogger.info('User login'); // Uses same configuration

Advanced Container Patterns

Service-based logger organization:

const winston = require('winston');

// Create service-specific container
const serviceContainer = new winston.Container({
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.errors({ stack: true }),
    winston.format.json()
  ),
  transports: [
    new winston.transports.File({ filename: 'services.log' })
  ]
});

// Create loggers for different services
const services = ['auth', 'user', 'payment', 'notification'];
const loggers = {};

services.forEach(service => {
  loggers[service] = serviceContainer.add(service, {
    defaultMeta: { service },
    transports: [
      new winston.transports.File({ 
        filename: `${service}.log`,
        level: 'info'
      }),
      new winston.transports.Console({
        level: 'debug',
        format: winston.format.simple()
      })
    ]
  });
});

// Use service loggers
loggers.auth.info('User authenticated');
loggers.payment.error('Payment processing failed');

Environment-specific container configuration:

const winston = require('winston');

// Create environment-specific container
const createContainer = (env) => {
  const baseConfig = {
    level: env === 'production' ? 'info' : 'debug',
    format: winston.format.combine(
      winston.format.timestamp(),
      winston.format.json()
    )
  };

  if (env === 'production') {
    baseConfig.transports = [
      new winston.transports.File({ filename: 'app.log' })
    ];
  } else {
    baseConfig.transports = [
      new winston.transports.Console({
        format: winston.format.combine(
          winston.format.colorize(),
          winston.format.simple()
        )
      })
    ];
  }

  return new winston.Container(baseConfig);
};

const container = createContainer(process.env.NODE_ENV);

// Create environment-appropriate loggers
const appLogger = container.get('application');
const errorLogger = container.get('errors', {
  level: 'error',
  transports: [
    new winston.transports.File({ filename: 'error.log' })
  ]
});

Container Lifecycle Management

Proper cleanup and resource management:

const winston = require('winston');

class LoggerManager {
  constructor() {
    this.container = new winston.Container();
    this.loggers = new Map();
  }

  createLogger(name, options = {}) {
    const logger = this.container.add(name, {
      format: winston.format.json(),
      ...options
    });
    
    this.loggers.set(name, logger);
    return logger;
  }

  getLogger(name) {
    return this.loggers.get(name) || this.container.get(name);
  }

  removeLogger(name) {
    this.container.close(name);
    this.loggers.delete(name);
  }

  shutdown() {
    // Close all loggers and clean up resources
    this.container.close();
    this.loggers.clear();
  }
}

// Usage
const loggerManager = new LoggerManager();

const apiLogger = loggerManager.createLogger('api', {
  level: 'debug',
  transports: [new winston.transports.Console()]
});

// Graceful shutdown
process.on('SIGTERM', () => {
  loggerManager.shutdown();
  process.exit(0);
});

Install with Tessl CLI

npx tessl i tessl/npm-winston

docs

container-management.md

default-logger.md

exception-rejection-handling.md

formats.md

index.md

logger-management.md

profiling.md

transports.md

tile.json