npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sucoza/logger

v0.1.9

Published

Powerful logging library with console interception, metrics, and export capabilities

Readme

@sucoza/logger

A powerful, lightweight logging library with console interception, metrics collection, and flexible export capabilities.

Features

  • 📝 Multiple Log Levels - Trace, debug, info, warn, error, and fatal
  • 🎯 Category-based Filtering - Organize logs by categories with individual settings
  • 📊 Real-time Metrics - Track log rates, error rates, and performance metrics
  • 🎣 Console Interception - Automatically capture all console output
  • 👶 Child Loggers - Create scoped loggers with inherited settings
  • 💾 Export Formats - Export logs as JSON, CSV, or plain text
  • 🔄 Event System - Subscribe to log events and metrics updates
  • 📦 Zero Dependencies - Lightweight, framework-agnostic library
  • 📝 TypeScript First - Full type safety and IntelliSense support

Installation

npm install @sucoza/logger
# or
yarn add @sucoza/logger
# or
pnpm add @sucoza/logger

Quick Start

import { logger } from '@sucoza/logger';

// Basic logging
logger.info('Application started');
logger.warn('Low memory', { available: '256MB' });
logger.error('Failed to connect', new Error('Connection timeout'));

// Enable console capture
logger.enableConsoleCapture();
console.log('This will be captured!'); // Automatically logged

// Create a child logger
const dbLogger = logger.child({ 
  category: 'Database',
  context: { module: 'postgres' }
});
dbLogger.info('Connected to database');

Core Concepts

Log Levels

logger.trace('Detailed trace information');
logger.debug('Debug information');
logger.info('Informational message');
logger.warn('Warning message');
logger.error('Error message');
logger.fatal('Fatal error message');

Categories and Filtering

// Configure categories
logger.setCategoryConfig('API', {
  enabled: true,
  level: 'debug'
});

logger.setCategoryConfig('Database', {
  enabled: true,
  level: 'error' // Only log errors and above
});

// Use categories
logger.info('API request', { endpoint: '/users' }, { category: 'API' });
logger.debug('Query executed', { sql: 'SELECT * FROM users' }, { category: 'Database' });

Child Loggers

// Create scoped loggers with preset options
const apiLogger = logger.child({
  category: 'API',
  context: { service: 'user-service' },
  tags: ['backend', 'rest']
});

const dbLogger = logger.child({
  category: 'Database',
  context: { database: 'postgres' }
});

// All logs from child loggers include their context
apiLogger.info('Request received'); // Includes category: 'API', service: 'user-service'
dbLogger.error('Connection failed'); // Includes category: 'Database', database: 'postgres'

// Child loggers can create their own children
const authLogger = apiLogger.child({
  context: { module: 'authentication' }
});

Console Interception

// Enable console capture with options
logger.enableConsoleCapture({
  preserveOriginal: true,  // Still output to console
  includeTrace: true       // Include stack traces
});

// All console methods are intercepted
console.log('Regular log');      // Captured as 'info'
console.debug('Debug message');  // Captured as 'debug'
console.warn('Warning');         // Captured as 'warn'
console.error('Error occurred'); // Captured as 'error'

// Disable when needed
logger.disableConsoleCapture();

Real-time Metrics

// Get current metrics
const metrics = logger.getMetrics();
console.log(metrics);
/*
{
  totalLogs: 1523,
  logsPerSecond: 12,
  errorRate: 2.5,        // Percentage
  warningRate: 5.3,      // Percentage
  logsByLevel: {
    trace: 100,
    debug: 423,
    info: 750,
    warn: 200,
    error: 45,
    fatal: 5
  },
  logsByCategory: {
    'API': 523,
    'Database': 234,
    'Auth': 766
  },
  averageLogSize: 256,   // Bytes
  peakLogsPerSecond: 45,
  lastLogTime: 1699564234567
}
*/

// Subscribe to metrics updates
logger.on('metrics-updated', (metrics) => {
  console.log('Current log rate:', metrics.logsPerSecond);
});

API Reference

Logger Class

Configuration Methods

| Method | Description | |--------|-------------| | setEnabled(enabled: boolean) | Enable/disable logging globally | | setLevel(level: LogLevel) | Set global minimum log level | | setCategoryConfig(category, config) | Configure category-specific settings | | updateConfig(config: Partial<LoggerConfig>) | Update logger configuration | | getConfig() | Get current configuration |

Logging Methods

| Method | Description | |--------|-------------| | trace(message, data?, options?) | Log trace level message | | debug(message, data?, options?) | Log debug level message | | info(message, data?, options?) | Log info level message | | warn(message, data?, options?) | Log warning level message | | error(message, data?, options?) | Log error level message | | fatal(message, data?, options?) | Log fatal level message | | child(options: LoggerOptions) | Create child logger with preset options |

Console Capture

| Method | Description | |--------|-------------| | enableConsoleCapture(options?) | Enable console interception | | disableConsoleCapture() | Disable console interception | | isConsoleCaptureEnabled() | Check if console capture is active |

Data Management

| Method | Description | |--------|-------------| | getLogs() | Get all logged entries | | clearLogs() | Clear log buffer and history | | clearMetrics() | Reset all metrics | | getMetrics() | Get current metrics | | exportLogs(format) | Export logs in specified format | | forceFlush() | Force flush buffered logs |

Event System

| Method | Description | |--------|-------------| | on(event, listener) | Subscribe to logger events | | off(event, listener) | Unsubscribe from events | | destroy() | Clean up all resources |

Configuration Options

interface LoggerConfig {
  enabled: boolean;              // Global enable/disable
  level: LogLevel;              // Minimum log level
  categories: Record<string, {  // Category configurations
    enabled: boolean;
    level?: LogLevel;
  }>;
  output: {
    console: boolean;           // Output to console
    custom?: (entry: LogEntry) => void; // Custom output handler
  };
  maxLogs: number;              // Maximum logs in buffer
  batchSize: number;            // Batch size for flushing
  flushInterval: number;        // Auto-flush interval (ms)
  intercept: {
    enabled: boolean;           // Enable interception
    console: boolean;           // Intercept console
    preserveOriginal: boolean;  // Keep original console output
    includeTrace: boolean;      // Include stack traces
  };
}

Events

// Subscribe to events
logger.on('log-entry', (entry: LogEntry) => {
  console.log('New log:', entry);
});

logger.on('log-batch', (entries: LogEntry[]) => {
  console.log('Batch of logs:', entries.length);
});

logger.on('metrics-updated', (metrics: LogMetrics) => {
  console.log('Metrics:', metrics);
});

logger.on('config-updated', (config: LoggerConfig) => {
  console.log('Config changed:', config);
});

Available events:

  • log-entry - Single log entry added
  • log-batch - Batch of logs flushed
  • metrics-updated - Metrics updated (every second)
  • metrics-cleared - Metrics reset
  • logs-cleared - Logs cleared
  • config-updated - Configuration changed

Log Entry Structure

interface LogEntry {
  id: string;                    // Unique identifier
  timestamp: number;              // Unix timestamp
  level: LogLevel;               // Log level
  message: string;               // Log message
  data?: any;                    // Additional data
  context?: Record<string, any>; // Contextual information
  category?: string;             // Log category
  tags?: string[];               // Tags for filtering
  source?: {                     // Source location
    function?: string;
    file?: string;
    line?: number;
    column?: number;
  };
  stack?: string;                // Stack trace for errors
}

Export Formats

JSON Export

const jsonLogs = logger.exportLogs('json');
// Returns formatted JSON string with all log entries

CSV Export

const csvLogs = logger.exportLogs('csv');
// Returns CSV with columns: timestamp, level, category, message, data

Plain Text Export

const textLogs = logger.exportLogs('txt');
// Returns human-readable text format

Advanced Usage

Custom Output Handler

logger.updateConfig({
  output: {
    console: false, // Disable console output
    custom: (entry: LogEntry) => {
      // Send to remote logging service
      fetch('/api/logs', {
        method: 'POST',
        body: JSON.stringify(entry)
      });
    }
  }
});

Structured Logging

// Log with structured data
logger.info('User action', {
  action: 'login',
  userId: '123',
  timestamp: Date.now(),
  metadata: {
    ip: '192.168.1.1',
    userAgent: 'Mozilla/5.0...'
  }
}, {
  category: 'Auth',
  tags: ['security', 'audit']
});

Performance Monitoring

// Monitor log performance
logger.on('metrics-updated', (metrics) => {
  if (metrics.logsPerSecond > 100) {
    logger.warn('High log rate detected', {
      rate: metrics.logsPerSecond
    });
  }
  
  if (metrics.errorRate > 10) {
    logger.fatal('High error rate', {
      errorRate: `${metrics.errorRate}%`
    });
  }
});

Singleton Instance

import { Logger, logger } from '@sucoza/logger';

// Use the singleton instance
logger.info('Using singleton');

// Or create your own instance
const customLogger = Logger.getInstance();
customLogger.info('Same singleton instance');

TypeScript Support

The library is written in TypeScript and provides comprehensive type definitions:

import type {
  LogLevel,
  LogEntry,
  LoggerConfig,
  LogMetrics,
  LoggerOptions,
  ExportFormat
} from '@sucoza/logger';

Best Practices

  1. Use Categories - Organize logs by functional areas
  2. Add Context - Include relevant context in child loggers
  3. Set Appropriate Levels - Use trace/debug for development, info+ for production
  4. Monitor Metrics - Watch error rates and log volume
  5. Export Regularly - Export and archive logs periodically
  6. Clean Up - Call destroy() when shutting down

License

MIT © tyevco

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

For issues and feature requests, please use the GitHub issues page.