npm package: @roonaan/loggable
Description: Console logger with structured data, Loggable interface, and dev-friendly console output
Latest version: 0.1.0

# Loggable

Console logger with structured data, Loggable interface, and dev-friendly console output

## Installation

```bash
npm install @roonaan/loggable
```

## Basic Usage

```typescript
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:

```typescript
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 references
```

## Dynamic 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.

```typescript
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:**
1. Rules are checked in order - the first matching pattern is applied
2. Explicit palette options passed to the constructor override defaults
3. 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:

```typescript
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 complete
```

## Available Palettes

Choose from 9 pre-designed palettes:

- `defaultPalette` - Clean gray and blue theme
- `greenPalette` - Welcoming green theme for utilities and successful operations
- `redPalette` - Bold red theme for API and error tracking
- `bluePalette` - Calm blue theme for UI interactions
- `yellowPalette` - Vibrant yellow theme for warnings
- `purplePalette` - Rich purple theme for boot and initialization
- `orangePalette` - Warm orange theme for informational logs
- `grayPalette` - Neutral gray theme for utility operations
- `tealPalette` - Modern teal theme for user interactions

Each palette includes styled entries for `debug`, `log`, `info`, `warn`, and `error` levels.

## Creating Custom Palettes

```typescript
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 logger
- `options.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 format
- `Logger.TM_MILLIS` - HH:MM:SS:mmm format (with milliseconds)
- `Logger.TM_NONE` - Disable timestamps
- Custom function - `() => string` for any format
- No arguments - Reset to default

#### Instance methods
- `debug(...args): void` - Log at debug level
- `info(...args): void` - Log at info level
- `warn(...args): void` - Log at warn level
- `error(...args): void` - Log at error level

## License

MIT