@onurege3467/log
v1.0.1
Published
A customizable logging library with colored output and multiple log levels
Maintainers
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/logQuick 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 messagestimestamp(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 startedDaily 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 colorsAvailable Context Suggestions
success: green, brightGreen, bgGreen, bgBrightGreenerror: red, brightRed, bgRed, bgBrightRedwarning: yellow, brightYellow, bgYellow, bgBrightYellowinfo: blue, brightBlue, cyan, brightCyan, bgBlue, bgBrightBlue, bgCyan, bgBrightCyandebug: brightBlack, white, bgBrightBlack, bgWhitecritical: brightRed, red, bgBrightRed, bgRedhighlight: brightYellow, brightCyan, brightMagenta, bgBrightYellow, bgBrightCyan, bgBrightMagenta
Removing Levels
// Remove the debug level
logger.removeLevel('debug');
// Now logger.debug() will be undefinedLogging 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,whitebrightBlack,brightRed,brightGreen,brightYellow,brightBlue,brightMagenta,brightCyan,brightWhite
Background Colors
bgBlack,bgRed,bgGreen,bgYellow,bgBlue,bgMagenta,bgCyan,bgWhitebgBrightBlack,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 benchmarkTesting
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:allLicense
MIT License - see LICENSE file for details.
Contributing
- Fork the repository
- Create your feature branch
- Commit your changes
- Push to the branch
- Create a Pull Request
Author
onurege3467
Related
- @onurege3467/easycolor - The color library used by this logger
- @onurege3467/light-fs - The high-performance file system used for logging
