Skip to content

Latest commit

 

History

History
457 lines (346 loc) · 15.2 KB

File metadata and controls

457 lines (346 loc) · 15.2 KB

Simple Universal Logger

A lightweight, drop-in logging solution for any JavaScript project with 5 configurable levels and automatic file logging.

✨ Features

📝 Smart Logging Output

  • 🖥️ Color-Coded Console: Error=Red, Warn=Yellow, Info=Cyan, Debug=Green, Dev=Magenta
  • 📁 Clean File Logging: Plain text logs without color codes, perfect for parsing
  • 🔄 Dual Output: Every log appears in both console AND file simultaneously
  • ⏰ Human-Readable Timestamps: 2025-09-23 11:30:45.123 instead of cryptic ISO format

🎨 Flexible Formatting

  • Compact Mode: 11:30:45 ERROR MyApp Database timeout → host=server port=5432
  • Standard Mode: [2025-09-23 11:30:45] [ERROR] [MyApp:1234] Database timeout | {"host":"server","port":5432}
  • Data Formats: JSON, Key-Value (key=value), or Inline (key: value, key2: value2)
  • Optional Components: Hide process IDs for cleaner output, disable colors for CI/CD

🗂️ File Management

  • 📂 Auto Directory Creation: Creates logs/ folder automatically if missing
  • 🗓️ Daily Log Files: Separate files per day (MyApp-2025-09-23.log)
  • 📊 Intelligent Rotation: New day = new file, no manual cleanup needed
  • 🔒 Safe Writing: Handles file permissions and errors gracefully

⚙️ Universal Compatibility

  • Zero Dependencies: Pure JavaScript, no external packages
  • Multi-Environment: Node.js (full features), Electron (full features), Browser (console only)
  • Drop-in Ready: Copy one file, start logging immediately
  • 🎯 5 Log Levels: NONE, LOW, MED, HIGH, DEV with intelligent filtering

🚀 Quick Start

1. Drop the file into your project

# Copy simple-logger.js to your project folder
cp simple-logger.js /path/to/your/project/

2. Start logging immediately

Node.js/Electron (with automatic file logging):

const SimpleLogger = require("./simple-logger.js");

// Creates logger with beautiful formatting and file logging
const logger = new SimpleLogger({
	appName: "MyApp",
	level: "HIGH",
});

logger.error("Payment processing failed", {
	userId: 123,
	errorCode: "CARD_DECLINED",
	amount: 99.99,
});
logger.warn("API rate limit approaching", {
	remaining: 10,
	resetTime: "14:30:00",
});
logger.info("User logged in successfully", {
	userId: 123,
	method: "oauth",
	ip: "192.168.1.1",
});

// Console Output (with colors):
// [2025-09-23 11:30:45.123] [ERROR] [MyApp:1234] Payment processing failed | {"userId":123,"errorCode":"CARD_DECLINED","amount":99.99}
// [2025-09-23 11:30:45.124] [WARN] [MyApp:1234] API rate limit approaching | {"remaining":10,"resetTime":"14:30:00"}
// [2025-09-23 11:30:45.125] [INFO] [MyApp:1234] User logged in successfully | {"userId":123,"method":"oauth","ip":"192.168.1.1"}

// File Output (logs/MyApp-2025-09-23.log):
// Same format but without colors, perfect for log analysis tools

Browser (console only):

<script src="simple-logger.js"></script>
<script>
	const logger = new SimpleLogger({
		appName: "WebApp",
		level: "HIGH",
		compactMode: true, // Cleaner for browser console
		showProcessId: false, // Not relevant in browser
	});

	logger.error("API request failed", { endpoint: "/api/users", status: 404 });
	logger.info("Page loaded", { route: "/dashboard", loadTime: "1.2s" });

	// Browser Console Output:
	// 11:30:45.123 ERROR WebApp API request failed → {"endpoint":"/api/users","status":404}
	// 11:30:45.124 INFO  WebApp Page loaded → {"route":"/dashboard","loadTime":"1.2s"}
	// (File logging not available in browser environment)
</script>

3. What happens automatically when you start logging

  • logs/ directory is created in your project root (if it doesn't exist)
  • Daily log file is created: logs/MyApp-2025-09-23.log
  • Console gets beautiful colors - errors in red, warnings in yellow, info in cyan
  • Files get clean text - same content but without color codes for parsing tools
  • Human-readable timestamps - 2025-09-23 11:30:45.123 instead of 2025-09-23T11:30:45.123Z
  • Smart data formatting - structured JSON data alongside your messages
  • Error handling - if file writing fails, console logging continues without interruption

4. No configuration needed - but lots of options available

The logger works perfectly with zero configuration, but you can customize everything:

  • Change timestamp format (human-readable vs ISO)
  • Switch to compact mode for cleaner output
  • Use key-value data format instead of JSON
  • Hide process IDs for simpler logs
  • Disable colors for CI/CD environments
  • Custom log directory location

Log Levels

  • NONE: Shows nothing
  • LOW: Shows only ERROR messages
  • MED: Shows ERROR + WARN messages
  • HIGH: Shows ERROR + WARN + INFO + DEBUG messages
  • DEV: Shows everything including DEV messages + console.log replacement

📖 API Reference

Constructor Options

const logger = new SimpleLogger({
	// Basic Options
	appName: "MyApp", // App name in logs (default: 'App')
	level: "HIGH", // Log level (default: 'NONE')
	enableConsole: true, // Show in console (default: true)
	enableFileLogging: true, // Write to files (default: true)
	logDirectory: "logs", // Directory for log files (default: 'logs')

	// Formatting Options
	humanReadableTime: true, // Use readable timestamps vs ISO (default: true)
	showProcessId: true, // Include process ID in logs (default: true)
	compactMode: false, // Shorter, cleaner format (default: false)
	enableColors: true, // Colored console output (default: true)
	dataFormat: "json", // Data format: 'json', 'keyvalue', 'inline' (default: 'json')
});

Formatting Examples

🎨 Compact Mode (great for development):

const logger = new SimpleLogger({
	appName: "Dev",
	level: "HIGH",
	compactMode: true,
	showProcessId: false,
});
// Output: 11:30:45.123 ERROR Dev Database connection failed → host=localhost port=5432

📊 Key-Value Data Format (easy to parse):

const logger = new SimpleLogger({
	appName: "Analytics",
	level: "HIGH",
	dataFormat: "keyvalue",
});
// Output: [2025-09-23 11:30:45.123] [INFO] [Analytics:1234] User action | action=login userId=123 success=true

📝 Inline Data Format (human-readable):

const logger = new SimpleLogger({
	appName: "API",
	level: "HIGH",
	dataFormat: "inline",
});
// Output: [2025-09-23 11:30:45.123] [WARN] [API:1234] Rate limit warning | endpoint: /api/users, remaining: 10, resetTime: 14:30:00

🖥️ CI/CD Friendly (no colors, ISO timestamps):

const logger = new SimpleLogger({
	appName: "Deploy",
	level: "HIGH",
	enableColors: false,
	humanReadableTime: false,
});
// Output: [2025-09-23T11:30:45.123Z] [INFO] [Deploy:1234] Deployment completed | {"version":"1.2.3","duration":"45s"}

Environment-Specific Configurations

// Production Server
const prodLogger = new SimpleLogger({
	appName: "ProdAPI",
	level: "MED", // Only ERROR and WARN
	enableColors: false, // No colors in production logs
	logDirectory: "/var/log/app", // System log directory
});

// Development
const devLogger = new SimpleLogger({
	appName: "DevApp",
	level: "DEV", // Show everything
	compactMode: true, // Cleaner console output
	showProcessId: false, // Less clutter
});

// Browser Application
const browserLogger = new SimpleLogger({
	appName: "WebApp",
	level: "HIGH",
	compactMode: true, // Better for browser console
	showProcessId: false, // Not relevant in browser
	enableFileLogging: false, // File logging not available
});

Logging Methods

logger.error("Error message", { data: "optional" });
logger.warn("Warning message", { data: "optional" });
logger.info("Info message", { data: "optional" });
logger.debug("Debug message", { data: "optional" });
logger.dev("Development message", { data: "optional" });

Level Management

logger.setLevel("HIGH"); // Change log level
logger.getLevel(); // Get current level

File Logging Methods

logger.getLogFilePath(); // Get current log file path
logger.isFileLoggingEnabled(); // Check if file logging is enabled

Console Replacement

logger.enableConsoleReplacement(); // Capture console.log calls
logger.disableConsoleReplacement(); // Restore normal console
logger.isConsoleReplacementEnabled(); // Check status

📋 Output Examples

🎨 Console Output (with beautiful colors)

🔴 [2025-09-23 11:30:45.123] [ERROR] [PaymentAPI:1234] Credit card processing failed | {"userId":123,"errorCode":"CARD_DECLINED","amount":99.99}
🟡 [2025-09-23 11:30:45.124] [WARN] [PaymentAPI:1234] Rate limit approaching | {"endpoint":"/api/charge","remaining":5,"resetIn":"60s"}
🔵 [2025-09-23 11:30:45.125] [INFO] [PaymentAPI:1234] Transaction completed successfully | {"userId":123,"transactionId":"txn_abc123","amount":99.99}
🟢 [2025-09-23 11:30:45.126] [DEBUG] [PaymentAPI:1234] Database query executed | {"query":"SELECT * FROM transactions","duration":"12ms","rows":1}
🟣 [2025-09-23 11:30:45.127] [DEV] [PaymentAPI:1234] Memory usage check | {"heapUsed":"45MB","heapTotal":"67MB","external":"2MB"}

📁 File Output (clean text for parsing)

File: logs/PaymentAPI-2025-09-23.log

[2025-09-23 11:30:45.123] [ERROR] [PaymentAPI:1234] Credit card processing failed | {"userId":123,"errorCode":"CARD_DECLINED","amount":99.99}
[2025-09-23 11:30:45.124] [WARN] [PaymentAPI:1234] Rate limit approaching | {"endpoint":"/api/charge","remaining":5,"resetIn":"60s"}
[2025-09-23 11:30:45.125] [INFO] [PaymentAPI:1234] Transaction completed successfully | {"userId":123,"transactionId":"txn_abc123","amount":99.99}
[2025-09-23 11:30:45.126] [DEBUG] [PaymentAPI:1234] Database query executed | {"query":"SELECT * FROM transactions","duration":"12ms","rows":1}
[2025-09-23 11:30:45.127] [DEV] [PaymentAPI:1234] Memory usage check | {"heapUsed":"45MB","heapTotal":"67MB","external":"2MB"}

⚡ Compact Mode Output

11:30:45.123 ERROR PaymentAPI Credit card processing failed → userId=123 errorCode=CARD_DECLINED amount=99.99
11:30:45.124 WARN  PaymentAPI Rate limit approaching → endpoint=/api/charge remaining=5 resetIn=60s
11:30:45.125 INFO  PaymentAPI Transaction completed → userId=123 transactionId=txn_abc123 amount=99.99

📊 Different Data Formats

// JSON Format (default)
logger.info("User action", { action: "login", userId: 123, success: true });
// Output: [2025-09-23 11:30:45.123] [INFO] [App:1234] User action | {"action":"login","userId":123,"success":true}

// Key-Value Format
logger.info("User action", { action: "login", userId: 123, success: true });
// Output: [2025-09-23 11:30:45.123] [INFO] [App:1234] User action | action=login userId=123 success=true

// Inline Format
logger.info("User action", { action: "login", userId: 123, success: true });
// Output: [2025-09-23 11:30:45.123] [INFO] [App:1234] User action | action: login, userId: 123, success: true

🧪 Testing & Verification

Run the comprehensive test

node test-simple-logger.js

This test demonstrates:

  • ✅ All 5 log levels (ERROR, WARN, INFO, DEBUG, DEV)
  • ✅ Level filtering (NONE, LOW, MED, HIGH, DEV)
  • ✅ Beautiful console colors vs clean file output
  • ✅ Multiple formatting options (compact, key-value, clean modes)
  • ✅ Console replacement feature
  • ✅ Automatic file logging with directory creation
  • ✅ Real-world log examples (payment failures, API errors, user actions)

Verify everything works

After running the test:

# Check multiple log files were created
ls logs/
# Output: TestApp-2025-09-23.log, Compact-2025-09-23.log, etc.

# View clean file output (no colors)
cat logs/TestApp-2025-09-23.log

# See the test summary
# The test shows exactly what you'll see in console vs files

Expected Output

The test shows side-by-side examples of:

  • Console: Colorful, easy to read during development
  • Files: Clean text, perfect for log analysis tools
  • Different formats: JSON, key-value, compact modes
  • Real examples: Payment processing, API calls, user authentication

📁 What Gets Created

When you start using the logger in Node.js/Electron:

your-project/
├── simple-logger.js          # The logger file you dropped in
├── logs/                     # Auto-created directory
│   ├── MyApp-2025-09-23.log # Today's log file
│   ├── MyApp-2025-09-24.log # Tomorrow's log file (auto-created)
│   └── ...                  # One file per day
└── your-app.js              # Your application

⚡ Drop-in Instructions

For New Projects

  1. Copy simple-logger.js to your project folder
  2. Require it: const SimpleLogger = require('./simple-logger.js')
  3. Create instance: const logger = new SimpleLogger({ appName: 'MyApp', level: 'HIGH' })
  4. Start logging: logger.info('App started')
  5. Done! Logs appear in console + logs/ folder

For Existing Projects

  1. Copy simple-logger.js to your project

  2. Replace existing console.log statements:

    // Before
    console.log("User logged in:", userId);
    
    // After
    logger.info("User logged in", { userId });
  3. Optional: Add logs/ to your .gitignore if you don't want to commit log files

Environment Considerations

  • Node.js/Electron: Full functionality (console + file logging)
  • Browser: Console logging only (file system not accessible)
  • Docker: Ensure logs/ directory is properly mounted/accessible
  • Serverless: Consider using console-only mode (enableFileLogging: false)

📦 Technical Specifications

  • File size: ~6KB (comprehensive logging solution)
  • Dependencies: Zero external packages
  • Node.js modules: fs, path (built-in only)
  • Browser support: Full console functionality (file logging N/A)
  • Log file encoding: UTF-8 with proper line endings
  • File naming pattern: {appName}-{YYYY-MM-DD}.log
  • Colors: ANSI escape codes (work in most terminals)
  • Performance: Minimal overhead, async-safe file writing

🎯 Why Choose Simple Logger?

Instant Productivity

  • Zero setup time: Copy file → Start logging → Done
  • Beautiful output: Colors make debugging faster
  • Real-world ready: Handles production logging needs

Developer Experience

  • Human-readable: No cryptic timestamps or formats
  • Flexible: 3 data formats, 2 layout modes, full customization
  • Smart defaults: Works perfectly without any configuration

Production Ready

  • File rotation: Daily files prevent giant log files
  • Error handling: Logging never crashes your app
  • Performance: Minimal memory footprint and fast execution

Universal

  • Any project: Node.js, Electron, Browser, React, Vue, Express
  • Any environment: Development, staging, production, CI/CD
  • Any team: Junior developers to senior engineers

🚀 Start Logging Now!

# 1. Copy the file
cp simple-logger.js your-project/

# 2. Use it immediately
node -e "
const Logger = require('./simple-logger.js');
const log = new Logger({appName:'Test', level:'HIGH'});
log.info('Simple Logger is working!', {awesome: true});
"

# 3. Check your logs
cat logs/Test-$(date +%Y-%m-%d).log

That's it an enterprise-grade logger 🎉