Skip to content

100% Generic Multi-Environment Logger with Advanced Configuration - Smart detection, file-level overrides, and beautiful console formatting

License

Notifications You must be signed in to change notification settings

crimsonsunset/jsg-logger

Repository files navigation

JSG Logger

100% Generic Multi-Environment Logger with Advanced Configuration

A sophisticated, fully generic logging system that automatically detects its environment (browser, CLI, server) and provides optimal logging experience for any JavaScript project, with powerful file-level overrides and granular control.

✨ Features

  • 🎯 100% Generic - New in v1.2.0! Zero hardcoded assumptions, works with any project type
  • πŸš€ Zero-Boilerplate Integration - Eliminates 200+ lines of project setup code
  • πŸ”§ Auto-Discovery Components - Both camelCase and kebab-case component access
  • ⚑ Built-in Performance Logging - Static utilities with auto-getInstance
  • πŸ›‘οΈ Non-Destructive Error Handling - Missing components log but don't break apps
  • 🧠 Smart Environment Detection - Auto-adapts to browser, CLI, or server
  • 🎨 Beautiful Visual Output - Emoji, colors, and structured context display
  • πŸ“± Multi-Environment - Browser console, terminal, and production JSON
  • πŸͺ Log Store - In-memory storage for debugging and popup interfaces
  • βš™οΈ Runtime Controls - Dynamic log level adjustment and configuration
  • πŸ“Š Component Organization - Separate loggers for different system components
  • πŸ”§ External Configuration - JSON-based configuration system
  • πŸ“ File-Level Overrides - Per-file and pattern-based control
  • ⏰ Timestamp Modes - Absolute, readable, relative, or disabled
  • πŸŽ›οΈ Display Toggles - Control every aspect of log output
  • 🎯 Smart Level Resolution - Hierarchical level determination

πŸš€ Quick Start

v1.2.0: Fully Generic Design - Works with Any Project!

⚠️ Breaking Change: v1.2.0 requires defining components in your logger-config.json. The logger is now 100% generic with no hardcoded assumptions.

import JSGLogger from '@crimsonsunset/jsg-logger';

// Enhanced singleton with built-in configuration loading
const logger = await JSGLogger.getInstance({
  configPath: './logger-config.json'
});

// Use your project-specific components immediately
logger.api.info('Server started on port 3000');
logger.database.debug('Query executed', { query: 'SELECT * FROM users' });
logger.ui.info('Component mounted', { component: 'UserProfile' });

// Built-in static performance logging  
const startTime = performance.now();
// ... do work ...
JSGLogger.logPerformance('Page Generation', startTime, 'api');

// Non-destructive error handling - missing components auto-created
const dynamicLogger = logger.getComponent('new-feature');
dynamicLogger.info('Auto-created component!'); // Works immediately

Traditional Usage (Still Supported)

import logger from '@crimsonsunset/jsg-logger';

// Use component-specific loggers with smart level resolution
const log = logger.api;
log.info('API handler initialized', {
  endpoint: 'https://api.example.com',
  isReady: true
});

// Runtime controls
logger.controls.enableDebugMode(); // Enable debug for all components
logger.controls.setLevel('websocket', 'trace'); // Set specific component level
logger.controls.addFileOverride('src/popup.js', { level: 'trace' }); // File-specific control

🎯 Level Resolution Hierarchy

The logger uses intelligent level resolution with the following priority:

  1. File Override - fileOverrides["src/popup.js"].level
  2. Component Level - components["websocket"].level
  3. Global Level - globalLevel

This allows surgical debugging - you can turn on trace logging for just one problematic file while keeping everything else quiet.

βš™οΈ Advanced Configuration

Full Configuration Example

{
  "projectName": "My Advanced Project",
  "globalLevel": "info",
  "timestampMode": "absolute",
  "display": {
    "timestamp": true,
    "emoji": true,
    "component": true,
    "level": false,
    "message": true,
    "jsonPayload": true,
    "stackTrace": true
  },
  "components": {
    "api": { 
      "emoji": "🌐", 
      "color": "#4A90E2", 
      "name": "API",
      "level": "debug"
    },
    "database": { 
      "emoji": "πŸ’Ύ", 
      "color": "#00C896", 
      "name": "Database",
      "level": "warn"
    }
  },
  "fileOverrides": {
    "src/auth/login.js": { 
      "level": "trace",
      "emoji": "πŸ”",
      "display": {
        "level": true,
        "jsonPayload": true
      }
    },
    "src/managers/*.js": { 
      "level": "warn",
      "display": {
        "jsonPayload": false
      }
    },
    "src/popup.js": {
      "level": "debug",
      "timestampMode": "relative",
      "display": {
        "jsonPayload": false
      }
    }
  }
}

File Override Patterns

File overrides support powerful pattern matching:

  • Exact files: "src/popup.js"
  • Wildcards: "src/managers/*.js"
  • Patterns: "src/test-*.js"
  • Directories: "src/sites/*.js"

Each override can specify:

  • level - Log level for this file/pattern
  • emoji - Custom emoji override
  • timestampMode - File-specific timestamp mode
  • display - Individual display toggles

⏰ Timestamp Modes

Control how timestamps are displayed:

  • absolute - 22:15:30.123 (default)
  • readable - 10:15 PM
  • relative - 2s ago, 5m ago
  • disable - No timestamp
// Set globally
logger.controls.setTimestampMode('relative');

// Or per-file in config
"fileOverrides": {
  "src/popup.js": { "timestampMode": "relative" }
}

πŸŽ›οΈ Display Controls

Toggle individual parts of log output:

// Available display options
const displayConfig = {
  timestamp: true,    // Show/hide timestamp
  emoji: true,        // Show/hide level emoji
  component: true,    // Show/hide [COMPONENT-NAME]
  level: false,       // Show/hide level name (DEBUG, INFO, etc.)
  message: true,      // Show/hide log message
  jsonPayload: true,  // Show/hide context data trees
  stackTrace: true    // Show/hide error stack traces
};

// Runtime control
logger.controls.setDisplayOption('jsonPayload', false);
logger.controls.toggleDisplayOption('level');

πŸ—οΈ Architecture

logger/
β”œβ”€β”€ index.js                    # Main entry point with smart initialization
β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ config-manager.js       # Smart configuration system
β”‚   β”œβ”€β”€ default-config.json     # Default configuration
β”‚   └── component-schemes.js    # Component styling definitions
β”œβ”€β”€ formatters/
β”‚   β”œβ”€β”€ browser-formatter.js    # Advanced browser console output
β”‚   β”œβ”€β”€ cli-formatter.js        # Terminal output with pino-colada
β”‚   └── server-formatter.js     # Production JSON logging
β”œβ”€β”€ stores/
β”‚   └── log-store.js            # In-memory log storage with filtering
β”œβ”€β”€ utils/
β”‚   └── environment-detector.js # Environment detection
└── examples/
    └── advanced-config.json    # Full configuration example

🎯 Usage Examples

Per-Component Level Control

// Different components at different levels
logger.controls.setComponentLevel('websocket', 'warn');   // Quiet websocket
logger.controls.setComponentLevel('soundcloud', 'trace'); // Verbose SoundCloud
logger.controls.setComponentLevel('popup', 'debug');      // Debug popup

Surgical File Debugging

// Turn on trace logging for just one problematic file
logger.controls.addFileOverride('src/sites/soundcloud.js', {
  level: 'trace',
  display: { level: true, jsonPayload: true }
});

// Quiet all manager files
logger.controls.addFileOverride('src/managers/*.js', {
  level: 'warn',
  display: { jsonPayload: false }
});

Dynamic Display Control

// Hide JSON payloads but keep error stacks
logger.controls.setDisplayOption('jsonPayload', false);
logger.controls.setDisplayOption('stackTrace', true);

// Show level names for debugging
logger.controls.setDisplayOption('level', true);

// Use relative timestamps for popup
logger.controls.addFileOverride('src/popup.js', {
  timestampMode: 'relative'
});

Context Data

logger.api.error('Request failed', {
  url: window.location.href,
  selectors: {
    title: '.track-title',
    artist: '.track-artist'
  },
  retryCount: 3,
  lastError: error.message,
  userAgent: navigator.userAgent
});

// With file override for src/sites/soundcloud.js level: "trace":
// 22:15:30.123 🚨 [API] Request failed
//    β”œβ”€ url: https://soundcloud.com/track/example
//    β”œβ”€ selectors: {title: ".track-title", artist: ".track-artist"}
//    β”œβ”€ retryCount: 3
//    β”œβ”€ lastError: "Element not found"
//    β”œβ”€ userAgent: "Mozilla/5.0..."

πŸŽ›οΈ Runtime Controls API

Level Controls

logger.controls.setLevel(component, level)           // Set component level
logger.controls.getLevel(component)                  // Get effective level
logger.controls.setComponentLevel(component, level)  // Set in config
logger.controls.enableDebugMode()                    // All components β†’ debug
logger.controls.enableTraceMode()                    // All components β†’ trace

File Override Controls

logger.controls.addFileOverride(path, config)       // Add file override
logger.controls.removeFileOverride(path)             // Remove override
logger.controls.listFileOverrides()                  // List all overrides

Display Controls

logger.controls.setDisplayOption(option, enabled)   // Set display option
logger.controls.getDisplayConfig()                   // Get current config
logger.controls.toggleDisplayOption(option)          // Toggle option

Timestamp Controls

logger.controls.setTimestampMode(mode)               // Set timestamp mode
logger.controls.getTimestampMode()                   // Get current mode
logger.controls.getTimestampModes()                  // List available modes

System Controls

logger.controls.refresh()                            // Refresh all loggers
logger.controls.reset()                              // Reset to defaults
logger.controls.getConfigSummary()                   // Get config summary
logger.controls.getStats()                           // Get logging stats

πŸ“Š Log Store & Statistics

Advanced Log Filtering

// Get recent logs with file context
const recentLogs = logger.logStore.getRecent(20);
const websocketLogs = logger.logStore.getByComponent('websocket', 10);
const errorLogs = logger.logStore.getByLevel(50, 5); // Errors only

// Enhanced log entries include:
// - filePath: 'src/sites/soundcloud.js'
// - effectiveLevel: 'trace'
// - component: 'soundcloud'
// - displayConfig: { timestamp: true, ... }

Real-time Statistics

const stats = logger.controls.getStats();
// Returns:
// {
//   total: 156,
//   byLevel: { debug: 45, info: 89, warn: 15, error: 7 },
//   byComponent: { soundcloud: 67, websocket: 23, popup: 66 },
//   timeRange: { start: 1627846260000, end: 1627846320000 }
// }

🎨 Output Examples

πŸš€ BREAKTHROUGH: Perfect Browser Formatting

// Direct browser logger with 100% style control:
12:00 AM 🎯 [JSG-CORE] ✨ JSG Application v1.0.0 - Logger Ready!
12:00 AM 🎡 [SOUNDCLOUD] MediaSession track change detected
   β”œβ”€ title: Alt-J - Breezeblocks (Gkat Remix)
   β”œβ”€ artist: Gkat
   β”œβ”€ hasArtwork: true
12:00 AM 🎯 [JSG-CORE] πŸ§ͺ Testing JSON context display
   β”œβ”€ testData: {nested: {...}, simple: 'test string', boolean: true}
   β”œβ”€ location: {href: 'https://soundcloud.com/discover', hostname: 'soundcloud.com'}
   β”œβ”€ timestamp: 2025-07-29T06:00:53.837Z

File Override in Action

// src/sites/soundcloud.js with level: "trace" override:
12:00 AM 🎡 TRACE [SOUNDCLOUD] Detailed selector matching
   β”œβ”€ selector: ".playButton"
   β”œβ”€ found: true
   β”œβ”€ timing: 2.3ms

// src/managers/websocket-manager.js with level: "warn" (quiet):
(no debug/info logs shown)

// src/popup.js with timestampMode: "relative":
2s ago πŸŽ›οΈ [POPUP] User clicked debug button
   β”œβ”€ component: "soundcloud"

Display Toggles in Action

// With display: { level: true, jsonPayload: false }:
12:00 AM 🚨 ERROR [SOUNDCLOUD] Track extraction failed

// With display: { timestamp: false, level: true, jsonPayload: true }:
🚨 ERROR [SOUNDCLOUD] Track extraction failed
   β”œβ”€ url: https://soundcloud.com/track/example
   β”œβ”€ retryCount: 3

πŸ“¦ Installation

npm install @crimsonsunset/jsg-logger

Latest: v1.1.0 includes major project simplification enhancements!

🎯 Environment Detection

The logger automatically detects its environment and uses optimal implementations:

  • Browser: πŸš€ BREAKTHROUGH - Custom direct logger (bypasses Pino) for 100% console styling control
  • CLI: Uses pino-colada for beautiful terminal output
  • Server: Uses structured JSON for production logging

Why Browser is Different: Our testing revealed that Pino's browser detection was interfering with custom formatters, especially in Chrome extensions. By creating a custom direct browser logger that bypasses Pino entirely, we achieved:

  • Perfect emoji and color display
  • Readable timestamp formatting (12:00 AM)
  • Beautiful JSON tree expansion
  • Seamless Chrome extension integration
  • Zero compromises on functionality

πŸš€ Advanced Features

Automatic File Detection

The browser formatter automatically detects which file is logging by analyzing the call stack, enabling seamless file override functionality.

Smart Level Resolution

The three-tier hierarchy (file β†’ component β†’ global) provides maximum flexibility with sensible defaults.

Pattern Matching

File overrides support glob patterns with * and ? wildcards for powerful bulk configuration.

Runtime Reconfiguration

All settings can be changed at runtime without restarting, perfect for debugging complex issues.

🎯 Migration from Basic Logger

If you're upgrading from a basic logger:

// Before: Simple global level
logger.level = 'debug';

// After: Granular control
logger.controls.setComponentLevel('websocket', 'warn');     // Quiet websocket
logger.controls.addFileOverride('src/popup.js', {           // Debug popup
  level: 'debug',
  timestampMode: 'relative'
});

πŸ”§ Browser Developer Tools

In browser environments, runtime controls are available globally:

// Available as window.JSG_Logger
JSG_Logger.enableDebugMode();
JSG_Logger.setDisplayOption('level', true);
JSG_Logger.addFileOverride('src/popup.js', { level: 'trace' });
JSG_Logger.getStats();

⚠️ Disclaimer

This software is provided "AS IS" without warranty of any kind. Use at your own risk. The author is not responsible for any damages, data loss, or issues that may result from using this logger. See the LICENSE file for full legal terms.


License: ISC

This logger system provides the foundation for sophisticated debugging and monitoring across complex multi-file applications with surgical precision and beautiful output.