@roonaan/loggable
v0.1.0
Published
Console logger with structured data, Loggable interface, and dev-friendly console output
Readme
Loggable
Console logger with structured data, Loggable interface, and dev-friendly console output
Installation
npm install @roonaan/loggableBasic Usage
import { Logger, greenPalette } from '@roonaan/loggable';
// Create a logger with a tag and optional palette
const logger = new Logger('MyApp', { palette: greenPalette });
// Log with different levels
logger.info('App started', { version: '1.0.0' });
logger.warn('Deprecated API usage');
logger.error('Failed to connect', { error: 'ECONNREFUSED' });
logger.debug('Debug info', { data: 'details' });Structured Logging with Loggable Interface
Implement the Loggable interface to control how your objects are logged:
import { Logger, Loggable, bluePalette } from '@roonaan/loggable';
class User implements Loggable {
constructor(private id: number, private name: string) {}
toLogData() {
return { userId: this.id, displayName: this.name };
}
}
const logger = new Logger('Auth', { palette: bluePalette });
logger.info('User logged in', new User(123, 'Alice'));
// Output: User object is cleanly serialized without circular referencesDynamic Defaults with Pattern-Based Configuration
Use Logger.setDefaults() to automatically assign palettes based on logger tag patterns. This is useful for ensuring consistent theming across your application without passing palette options to every logger.
import { Logger, greenPalette, redPalette, tealPalette, purplePalette } from '@roonaan/loggable';
// Configure pattern-based defaults
Logger.setDefaults([
{ pattern: /^API/i, options: { palette: redPalette } },
{ pattern: /^UI/i, options: { palette: tealPalette } },
{ pattern: /^Utils/i, options: { palette: greenPalette } },
{ pattern: /^Boot/i, options: { palette: purplePalette } },
]);
// Loggers now automatically get the matching palette based on their tag
const apiLogger = new Logger('API:Service'); // auto-gets redPalette
const uiLogger = new Logger('UI:Events'); // auto-gets tealPalette
const utilsLogger = new Logger('Utils'); // auto-gets greenPalette
const bootLogger = new Logger('Boot'); // auto-gets purplePalette
// Override defaults with explicit options if needed
const customLogger = new Logger('UI:Custom', { palette: customPalette });How it works:
- Rules are checked in order - the first matching pattern is applied
- Explicit palette options passed to the constructor override defaults
- If no pattern matches, the default palette is used
Timestamps and Custom Time Functions
By default, all logs include a timestamp in HH:MM:SS format. You can customize or disable this behavior using predefined time format constants or custom functions:
import { Logger } from 'loggable';
// Use predefined time formats
Logger.setTimeFunction(Logger.TM_HMS); // HH:MM:SS (default)
Logger.setTimeFunction(Logger.TM_ISO); // ISO 8601 format: 2026-04-09T14:23:45.123Z
Logger.setTimeFunction(Logger.TM_MILLIS); // With milliseconds: 14:23:45:123
Logger.setTimeFunction(Logger.TM_NONE); // No timestamp
// Use a custom time format
Logger.setTimeFunction(() => new Date().toLocaleTimeString());
Logger.setTimeFunction(() => `[${new Date().getHours()}h]`);
// Reset to default HH:MM:SS format
Logger.setTimeFunction();Example output with different time formats:
// TM_HMS (default)
14:23:45 INFO [Boot] Site startup complete
// TM_ISO
2026-04-09T14:23:45.123Z INFO [API] Request completed
// TM_MILLIS
14:23:45:123 DEBUG [UI] User click detected
// TM_NONE (no timestamp)
INFO [Boot] Site startup completeAvailable Palettes
Choose from 9 pre-designed palettes:
defaultPalette- Clean gray and blue themegreenPalette- Welcoming green theme for utilities and successful operationsredPalette- Bold red theme for API and error trackingbluePalette- Calm blue theme for UI interactionsyellowPalette- Vibrant yellow theme for warningspurplePalette- Rich purple theme for boot and initializationorangePalette- Warm orange theme for informational logsgrayPalette- Neutral gray theme for utility operationstealPalette- Modern teal theme for user interactions
Each palette includes styled entries for debug, log, info, warn, and error levels.
Creating Custom Palettes
import { Logger, Palette } from '@roonaan/loggable';
const customPalette: Palette = {
debug: { color: '#888', background: '#f0f0f0' },
log: { color: '#888', background: '#f0f0f0' },
info: { color: '#0066cc', background: '#e6f2ff', fontWeight: 'bold' },
warn: { color: '#ff8800', fontWeight: 'bold' },
error: { color: '#cc0000', background: '#ffe6e6', fontWeight: 'bold' },
};
const logger = new Logger('Custom', { palette: customPalette });API Reference
Logger class
constructor(tag: string, options?: LoggerOptions)
Create a new logger instance.
tag: Unique identifier for the loggeroptions.palette: Optional palette to override defaults
static setDefaults(rules: LoggerDefaultRule[]): void
Configure pattern-based default options for loggers.
rules: Array of pattern-to-options mappings, checked in order
static setTimeFunction(fn?: TimeFunction | false): void
Set a custom time function for log timestamps, or use predefined formats.
Logger.TM_HMS- HH:MM:SS format (default)Logger.TM_ISO- ISO 8601 formatLogger.TM_MILLIS- HH:MM:SS:mmm format (with milliseconds)Logger.TM_NONE- Disable timestamps- Custom function -
() => stringfor any format - No arguments - Reset to default
Instance methods
debug(...args): void- Log at debug levelinfo(...args): void- Log at info levelwarn(...args): void- Log at warn levelerror(...args): void- Log at error level
License
MIT
