@m00nbyte/custom-logger
v1.0.0
Published
A versatile logger with customizable levels, colors, and formats for clear and flexible logging
Downloads
58
Maintainers
Readme
Custom Logger
Description
A highly customizable, feature-rich logging library with configurable levels, colors, icons, timestamps, and context-aware logging. Perfect for both development and production environments.
Features
- 🎨 Colorful output with ANSI colors (configurable)
- 📊 Custom log levels with numeric priorities
- ⏱️ Timestamps with millisecond precision
- 🏷️ Context-specific loggers for different modules
- 🎯 Level filtering to control verbosity
- 🔧 Fully configurable format, colors, and behavior
- 📝 Object/JSON support with pretty printing
- 🚀 Zero dependencies
- 📦 ESM & CJS support
Installation
npm install -D @m00nbyte/custom-logger
yarn add -D @m00nbyte/custom-loggerUsage
import logger from '@m00nbyte/custom-logger';
// Basic usage
logger.debug('Debug message');
logger.info('Info message');
logger.warn('Warning message');
logger.error('Error message');
logger.success('Success!');
logger.update('Config updated');
// Function style (legacy)
logger('info', 'Function style logging');
// With objects
logger.info({ user: 'john', action: 'login', timestamp: new Date() });Configuration
Global Configuration
import logger from '@m00nbyte/custom-logger';
// Configure logger
logger.configure({
level: 2, // Only show warn and above (0-4)
colored: true, // Enable colored output
icons: true, // Show emoji icons
timestamp: true, // Show timestamps
format: '❱ %timestamp% ❱ %icon%%event% ❱ %message%',
silentInit: false // Log configuration changes
});
// Individual settings
logger.setLevel(3); // Set log level (0=all, 3=errors only)
logger.colored(true); // Enable/disable colors
logger.icons(false); // Enable/disable icons
logger.timestamp(true); // Enable/disable timestampsAvailable Log Levels
| Level | Numeric Value | Default Color | Default Icon | Description | | ------- | ------------- | ------------- | ------------ | -------------------------- | | debug | 0 | grey | 🔧 | Detailed debug information | | update | 0 | cyan | 🔄 | Configuration updates | | info | 1 | blue | ℹ️ | General information | | success | 1 | green | ✅ | Success messages | | warn | 2 | yellow | ⚠️ | Warnings | | error | 3 | red | ❌ | Errors |
Advanced Usage
Custom Log Levels
// Add custom log level
logger.addLevel('critical', {
color: 'magenta',
level: 4,
icon: '💥'
});
// Use custom level
logger('critical', 'System critical!');
// Update existing level
logger.updateLevel('warn', {
newName: 'warning',
color: 'cyan',
level: 2
});
// Remove a level
logger.removeLevel('debug');
// List all available levels
logger.listLevels();Context-Specific Loggers
Create dedicated loggers for different parts of your application:
// Create module-specific loggers
const apiLogger = logger.create('API');
const dbLogger = logger.create('Database');
const authLogger = logger.create('Auth');
// Use them with automatic context prefix
apiLogger.info('Request started');
// Output: ❱ 14:30:25.123 ❱ API:info ❱ Request started
dbLogger.warn('Slow query detected');
// Output: ❱ 14:30:25.456 ❱ Database:warn ❱ Slow query detected
authLogger.error('Invalid credentials');
// Output: ❱ 14:30:25.789 ❱ Auth:error ❱ Invalid credentialsCustom Format Templates
Customize the output format with placeholders:
logger.configure({
format: '[%time%] %event% - %message%'
});
// Available placeholders:
// %timestamp% - Full timestamp (HH:MM:SS.mmm)
// %date% - Date only (YYYY-MM-DD)
// %time% - Time only (HH:MM:SS)
// %event% - Event/level name
// %icon% - Emoji icon (if enabled)
// %level% - Numeric level
// %message% - The log messageLevel Filtering Examples
// Show all messages (default)
logger.setLevel(0);
// Shows: debug, update, info, success, warn, error
// Show informational and above
logger.setLevel(1);
// Shows: info, success, warn, error, update
// Show warnings and above
logger.setLevel(2);
// Shows: warn, error, update
// Show errors only
logger.setLevel(3);
// Shows: error, update
// Show nothing (except updates)
logger.setLevel(4);
// Shows: update onlyAPI Reference
Core Methods
// Direct logging methods
logger.debug(message: string | object)
logger.info(message: string | object)
logger.warn(message: string | object)
logger.error(message: string | object)
logger.success(message: string | object)
logger.update(message: string | object)
// Function-style logging
logger(type: string, message: string | object)
// Configuration
logger.configure(options: LoggerOptions)
logger.setLevel(level: number)
logger.getLevel(): number
logger.colored(enabled: boolean)
logger.icons(enabled: boolean)
logger.timestamp(enabled: boolean)
// Level Management
logger.addLevel(name: string, config: LevelConfig)
logger.updateLevel(oldName: string, options: UpdateOptions)
logger.removeLevel(name: string)
logger.hasLevel(name: string): boolean
logger.listLevels(): void
// Context Loggers
logger.create(context: string): ContextLoggerAvailable Colors
- black
- red
- green
- yellow
- blue
- magenta
- cyan
- white
- grey
Examples
Production Configuration
import logger from '@m00nbyte/custom-logger';
// Production settings - minimal output
if (process.env.NODE_ENV === 'production') {
logger.configure({
level: 2, // Only warnings and errors
colored: false, // No colors in production
icons: false, // No emojis
timestamp: true, // Keep timestamps for debugging
silentInit: true // No init logs
});
}
// Development settings - verbose output
if (process.env.NODE_ENV === 'development') {
logger.configure({
level: 0, // Show everything
colored: true, // Colors for readability
icons: true, // Fun emojis
timestamp: true, // Helpful timestamps
format: '❱ %timestamp% ❱ %icon%%event% ❱ %message%'
});
}Error Tracking Integration
import logger from '@m00nbyte/custom-logger';
const errorLogger = logger.create('Errors');
// Integrate with error tracking service
const originalError = logger.error;
logger.error = function (message) {
// Send to error tracking service
if (typeof message === 'object' && message.error) {
sendToErrorService(message.error);
}
// Call original logger
originalError.call(this, message);
};
// Usage
try {
riskyOperation();
} catch (error) {
errorLogger.error({ error, context: 'riskyOperation' });
}Browser Support
The logger works in both Node.js and modern browsers. For browser usage, include it in your build process:
<script src="https://cdn.jsdelivr.net/gh/m00nbyte/custom-logger@latest/dist/index.iife.min.js"></script>
<script>
window.customLogger.info('Hello from browser!');
</script>Performance
The logger is designed to be performant:
- Conditional output based on log level
- Minimal overhead when logging is disabled
- Efficient string formatting
- Zero dependencies
Contribution
Feel free to submit issues or pull requests.
Like my work?
This project needs a :star: from you. Don't forget to leave a star.
