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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@onurege3467/log

v1.0.1

Published

A customizable logging library with colored output and multiple log levels

Readme

@onurege3467/log

A customizable logging library with colored output and multiple log levels. Built with vanilla JavaScript (ES5 compatible) and @onurege3467/easycolor for beautiful console output, plus @onurege3467/light-fs for high-performance file logging.

Features

  • 🎨 Colored Output: Beautiful colored logs using @onurege3467/easycolor
  • 🔧 Customizable: Add, remove, and modify log levels
  • 📝 Metadata Support: Attach additional data to log messages
  • Timestamp Support: Optional timestamps for each log entry
  • 🏷️ Prefix Support: Add custom prefixes to all log messages
  • 🎯 ES5 Compatible: Works with older JavaScript environments
  • 📦 Optimized: Uses high-performance @onurege3467/easycolor library
  • 🌈 Rich Color Support: Full spectrum of colors and styles
  • 🎯 Color Validation: Automatic color validation with suggestions
  • 💡 Smart Suggestions: Context-based color recommendations
  • 🎨 Background Colors: Support for background colors (bgRed, bgBlue, etc.)
  • 📁 File Logging: High-performance file logging with @onurege3467/light-fs
  • 🔄 File Rotation: Automatic log file rotation and management
  • 📊 Multiple Formats: JSON, CSV, and text log formats
  • Buffered Writing: Optimized batch writing for performance
  • 🚀 Lazy Loading: Dependencies loaded only when needed
  • 📏 Small Bundle: Only 21.4KB gzipped

Installation

npm install @onurege3467/log

Quick Start

var CustomLogger = require('@onurege3467/log');

// Create a logger with default configuration
var logger = new CustomLogger();

// Use default log levels
logger.info('Application started');
logger.warn('This is a warning');
logger.error('An error occurred');
logger.fatal('Critical failure');
logger.debug('Debug information');

Default Log Levels

The library comes with 5 default log levels:

| Level | Color | Symbol | Priority | |-------|-------|--------|----------| | debug | brightBlack | 🔍 | 0 | | info | blue | ℹ️ | 1 | | warn | yellow | ⚠️ | 2 | | error | red | ❌ | 3 | | fatal | brightRed | 💀 | 4 |

Configuration

You can customize the logger behavior by passing a configuration object:

var logger = new CustomLogger({
  prefix: 'MyApp',
  timestamp: true,
  output: 'both', // 'console', 'file', or 'both'
  fileLogging: {
    enabled: true,
    path: './logs',
    filename: 'app.log'
  }
});

Configuration Options

  • prefix (string): Add a prefix to all log messages
  • timestamp (boolean): Enable/disable timestamps (default: true)
  • output (string): Output destination ('console', 'file', 'both')
  • levels (array): Custom log levels (see below)
  • fileLogging (object): File logging configuration (see below)

File Logging Configuration

The library provides comprehensive file logging capabilities using @onurege3467/light-fs:

Basic File Logging

var logger = new CustomLogger({
  output: 'both',
  fileLogging: {
    enabled: true,
    path: './logs',
    filename: 'app.log',
    format: 'json'
  }
});

Advanced File Logging Configuration

var logger = new CustomLogger({
  fileLogging: {
    enabled: true,
    path: './logs',                    // Log directory
    filename: 'app.log',               // Log filename
    maxFileSize: 10 * 1024 * 1024,    // 10MB max file size
    maxFiles: 5,                       // Keep 5 log files
    rotation: 'daily',                 // 'daily', 'size', 'none'
    compression: true,                 // Enable gzip compression
    format: 'json',                    // 'json', 'csv', 'text'
    includeMetadata: true,             // Include metadata in logs
    includeColors: false,              // Include color codes in file
    dateFormat: 'ISO',                 // 'ISO', 'local', 'custom'
    customDateFormat: 'YYYY-MM-DD HH:mm:ss',
    levels: ['info', 'warn', 'error', 'fatal'], // Which levels to log
    excludeLevels: [],                 // Which levels to exclude
    bufferSize: 100,                   // Buffer size for batch writing
    flushInterval: 5000,               // Flush interval in ms
    encoding: 'utf8'                   // File encoding
  }
});

File Logging Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | enabled | boolean | false | Enable file logging | | path | string | './logs' | Log directory path | | filename | string | 'app.log' | Log filename | | maxFileSize | number | 10MB | Maximum file size before rotation | | maxFiles | number | 5 | Maximum number of log files to keep | | rotation | string | 'daily' | Rotation strategy ('daily', 'size', 'none') | | compression | boolean | true | Enable gzip compression | | format | string | 'json' | Log format ('json', 'csv', 'text') | | includeMetadata | boolean | true | Include metadata in logs | | includeColors | boolean | false | Include color codes in file | | dateFormat | string | 'ISO' | Date format ('ISO', 'local', 'custom') | | levels | array | [] | Specific levels to log to file | | excludeLevels | array | [] | Levels to exclude from file | | bufferSize | number | 100 | Buffer size for batch writing | | flushInterval | number | 5000 | Flush interval in milliseconds |

File Logging Examples

JSON Format Logging

var logger = new CustomLogger({
  output: 'file',
  fileLogging: {
    enabled: true,
    format: 'json',
    includeMetadata: true
  }
});

logger.info('User login', { userId: 12345, ip: '192.168.1.1' });
// Output: {"timestamp":"2025-08-25T14:00:00.000Z","level":"INFO","message":"User login","metadata":{"userId":12345,"ip":"192.168.1.1"}}

CSV Format Logging

var logger = new CustomLogger({
  output: 'file',
  fileLogging: {
    enabled: true,
    format: 'csv',
    includeMetadata: true
  }
});

logger.info('User action', { action: 'login', userId: 12345 });
// Output: 2025-08-25T14:00:00.000Z,INFO,User action,"{"action":"login","userId":12345}"

Text Format Logging

var logger = new CustomLogger({
  output: 'file',
  fileLogging: {
    enabled: true,
    format: 'text',
    dateFormat: 'local'
  }
});

logger.info('Application started');
// Output: [8/25/2025, 2:00:00 PM] [INFO] Application started

Daily Rotation

var logger = new CustomLogger({
  fileLogging: {
    enabled: true,
    filename: 'app.log',
    rotation: 'daily',
    maxFiles: 7 // Keep 7 days of logs
  }
});
// Creates: app-2025-08-25.log, app-2025-08-26.log, etc.

Level Filtering

var logger = new CustomLogger({
  fileLogging: {
    enabled: true,
    levels: ['error', 'fatal'], // Only log errors and fatals to file
    excludeLevels: ['debug']    // Never log debug to file
  }
});

File Logging Methods

Enable/Disable File Logging

// Enable file logging dynamically
logger.enableFileLogging({
  path: './logs',
  filename: 'dynamic.log',
  format: 'json'
});

// Disable file logging
logger.disableFileLogging();

File Management

// Get list of log files
var logFiles = logger.getLogFiles();
console.log('Available log files:', logFiles);

// Get log statistics
var stats = logger.getLogStats();
console.log('Log stats:', stats);
// Output: { enabled: true, logFiles: 3, totalSize: 1024000, bufferSize: 0, lastFlush: 1692984000000 }

// Clear all log files
logger.clearLogs();

Cleanup

// Clean up resources when done
logger.destroy();

Custom Log Levels

Adding Custom Levels

var logger = new CustomLogger();

// Add a success level with background color
logger.addLevel({
  name: 'success',
  priority: 1,
  color: 'bgGreen',
  symbol: '✅'
});

// Add a trace level with background color
logger.addLevel({
  name: 'trace',
  priority: 0,
  color: 'bgMagenta',
  symbol: '🔍'
});

// Add a highlight level with bright background
logger.addLevel({
  name: 'highlight',
  priority: 2,
  color: 'bgBrightYellow',
  symbol: '✨'
});

// Use the new levels
logger.success('Operation completed successfully');
logger.trace('Function called', { param1: 'value1' });
logger.highlight('Important system event');

Modifying Existing Levels

// Change the color and symbol of the info level
logger.setLevel('info', {
  color: 'bgCyan',
  symbol: '📝'
});

logger.info('This will use the new styling');

Color Validation and Suggestions

The library provides smart color validation and suggestions:

// Get all available colors
var allColors = logger.getAvailableColors();
console.log('Available colors:', allColors);

// Get context-based color suggestions
var successColors = logger.suggestColors('success'); // ['green', 'brightGreen', 'bgGreen', 'bgBrightGreen']
var errorColors = logger.suggestColors('error');     // ['red', 'brightRed', 'bgRed', 'bgBrightRed']
var warningColors = logger.suggestColors('warning'); // ['yellow', 'brightYellow', 'bgYellow', 'bgBrightYellow']

// Preview how a color looks
logger.showColorPreview('brightGreen');
logger.showColorPreview('bgBrightRed');
logger.showBackgroundColorPreview('bgBlue');

// Invalid colors are automatically detected
logger.setLevel('info', { color: 'invalidColor' }); // Shows warning with available colors

Available Context Suggestions

  • success: green, brightGreen, bgGreen, bgBrightGreen
  • error: red, brightRed, bgRed, bgBrightRed
  • warning: yellow, brightYellow, bgYellow, bgBrightYellow
  • info: blue, brightBlue, cyan, brightCyan, bgBlue, bgBrightBlue, bgCyan, bgBrightCyan
  • debug: brightBlack, white, bgBrightBlack, bgWhite
  • critical: brightRed, red, bgBrightRed, bgRed
  • highlight: brightYellow, brightCyan, brightMagenta, bgBrightYellow, bgBrightCyan, bgBrightMagenta

Removing Levels

// Remove the debug level
logger.removeLevel('debug');

// Now logger.debug() will be undefined

Logging with Metadata

You can attach additional data to your log messages:

logger.info('User login attempt', {
  userId: 12345,
  ip: '192.168.1.1',
  userAgent: 'Mozilla/5.0...'
});

logger.error('Database connection failed', {
  error: 'Connection timeout',
  retryCount: 3,
  server: 'db.example.com'
});

Available Colors

The library supports all @onurege3467/easycolor colors:

Text Colors

  • black, red, green, yellow, blue, magenta, cyan, white
  • brightBlack, brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite

Background Colors

  • bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite
  • bgBrightBlack, bgBrightRed, bgBrightGreen, bgBrightYellow, bgBrightBlue, bgBrightMagenta, bgBrightCyan, bgBrightWhite

Text Styles

  • bold, dim, italic, underline, blink, inverse, hidden, strikethrough

Advanced Usage

Factory Function

var createLogger = require('@onurege3467/log').createLogger;

var logger = createLogger({
  prefix: 'MyApp',
  timestamp: false
});

Default Logger Instance

var defaultLogger = require('@onurege3467/log').defaultLogger;

defaultLogger.info('Using the default logger instance');

Getting and Updating Configuration

// Get current configuration
var config = logger.getConfig();
console.log(config);

// Update configuration
logger.updateConfig({
  prefix: 'NewPrefix',
  timestamp: false
});

Examples

Basic Application Logger

var CustomLogger = require('@onurege3467/log');

var logger = new CustomLogger({
  prefix: 'MyApp',
  timestamp: true,
  output: 'both',
  fileLogging: {
    enabled: true,
    path: './logs',
    filename: 'app.log',
    format: 'json',
    rotation: 'daily'
  }
});

logger.info('Application starting...');
logger.info('Database connected');
logger.warn('High memory usage detected');
logger.error('Failed to process request', { requestId: 'abc123' });
logger.info('Application shutting down');

Web Application Logger

var logger = new CustomLogger({
  prefix: 'WebApp',
  fileLogging: {
    enabled: true,
    format: 'json',
    levels: ['info', 'warn', 'error', 'fatal'],
    includeMetadata: true
  }
});

logger.addLevel({ name: 'request', priority: 1, color: 'cyan', symbol: '🌐' });
logger.addLevel({ name: 'response', priority: 1, color: 'green', symbol: '📡' });
logger.addLevel({ name: 'security', priority: 3, color: 'bgRed', symbol: '🔒' });

logger.request('GET /api/users', { 
  method: 'GET', 
  path: '/api/users', 
  ip: '192.168.1.100' 
});

logger.response('200 OK', { 
  statusCode: 200, 
  responseTime: 150 
});

logger.security('Failed login attempt', {
  ip: '192.168.1.200',
  username: 'admin',
  attempts: 5
});

Production Logger with File Rotation

var logger = new CustomLogger({
  prefix: 'Production',
  output: 'both',
  fileLogging: {
    enabled: true,
    path: '/var/log/myapp',
    filename: 'app.log',
    format: 'json',
    rotation: 'daily',
    maxFiles: 30, // Keep 30 days
    compression: true,
    bufferSize: 1000,
    flushInterval: 10000,
    levels: ['warn', 'error', 'fatal'],
    includeMetadata: true
  }
});

logger.warn('High CPU usage', { usage: 85, cores: 8 });
logger.error('Database connection failed', { 
  error: 'Connection timeout',
  retryCount: 3,
  server: 'db.example.com'
});

Performance

Thanks to @onurege3467/easycolor and @onurege3467/light-fs:

  • Fast execution: High-performance color processing and file operations
  • Memory efficient: Optimized memory usage with buffered writing
  • ES5 compatible: Works in older environments
  • File compression: Automatic gzip compression for log files
  • Batch writing: Buffered writes for optimal performance
  • Zero disk I/O blocking: Non-blocking file operations
  • Lazy loading: Dependencies loaded only when needed
  • Small bundle size: Only 21.4KB for the core library
  • Tree-shaking friendly: Modular design for better bundling

Performance Comparison

Benchmark Results (10,000 iterations each)

| Library | Simple String | With Metadata | Complex Metadata | Bundle Size | |---------|---------------|---------------|------------------|-------------| | @onurege3467/log | 117,040 ops/s | 152,581 ops/s | 169,451 ops/s | 21.4KB | | winston | 97,705 ops/s | 82,476 ops/s | 99,505 ops/s | ~500KB | | pino | 7,240,275 ops/s | 4,938,640 ops/s | 3,490,794 ops/s | ~200KB | | debug | 29,960,931 ops/s | 36,945,494 ops/s | 50,897,061 ops/s | ~50KB | | console.log | 6,840,773 ops/s | 12,930,104 ops/s | 37,060,234 ops/s | 0KB |

Performance Analysis

  • @onurege3467/log offers excellent performance with rich features
  • Smallest bundle size among feature-rich loggers
  • Balanced performance - fast enough for most use cases
  • Rich feature set with colored output and file logging
  • ES5 compatibility for broader environment support

Run Your Own Benchmark

npm run benchmark

Testing

Run the test suites to see all features in action:

# Run basic tests
npm test

# Run file logging tests
npm run test:file

# Run all tests
npm run test:all

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create your feature branch
  3. Commit your changes
  4. Push to the branch
  5. Create a Pull Request

Author

onurege3467

Related