A lightweight, drop-in logging solution for any JavaScript project with 5 configurable levels and automatic file logging.
- π₯οΈ 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.123instead of cryptic ISO format
- 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
- π 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
- 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
# Copy simple-logger.js to your project folder
cp simple-logger.js /path/to/your/project/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 toolsBrowser (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>- β
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.123instead of2025-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
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
- 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
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')
});π¨ 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"}// 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
});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" });logger.setLevel("HIGH"); // Change log level
logger.getLevel(); // Get current levellogger.getLogFilePath(); // Get current log file path
logger.isFileLoggingEnabled(); // Check if file logging is enabledlogger.enableConsoleReplacement(); // Capture console.log calls
logger.disableConsoleReplacement(); // Restore normal console
logger.isConsoleReplacementEnabled(); // Check statusπ΄ [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: 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"}
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
// 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: truenode test-simple-logger.jsThis 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)
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 filesThe 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
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
- Copy
simple-logger.jsto your project folder - Require it:
const SimpleLogger = require('./simple-logger.js') - Create instance:
const logger = new SimpleLogger({ appName: 'MyApp', level: 'HIGH' }) - Start logging:
logger.info('App started') - Done! Logs appear in console +
logs/folder
-
Copy
simple-logger.jsto your project -
Replace existing
console.logstatements:// Before console.log("User logged in:", userId); // After logger.info("User logged in", { userId });
-
Optional: Add
logs/to your.gitignoreif you don't want to commit log files
- 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)
- 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
- Zero setup time: Copy file β Start logging β Done
- Beautiful output: Colors make debugging faster
- Real-world ready: Handles production logging needs
- Human-readable: No cryptic timestamps or formats
- Flexible: 3 data formats, 2 layout modes, full customization
- Smart defaults: Works perfectly without any configuration
- File rotation: Daily files prevent giant log files
- Error handling: Logging never crashes your app
- Performance: Minimal memory footprint and fast execution
- Any project: Node.js, Electron, Browser, React, Vue, Express
- Any environment: Development, staging, production, CI/CD
- Any team: Junior developers to senior engineers
# 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).logThat's it an enterprise-grade logger π