npm package: @loggerhub/core
Description: Core logger interfaces and built-in adapters for LoggerHub
Author: OneTeamSoftware
Latest version: 1.0.5

# @loggerhub/core

Core logging interfaces and abstract implementations for the LoggerHub TypeScript logging library.

## Overview

This package provides the fundamental building blocks for creating consistent, extensible logging solutions:

- **LoggerInterface**: Standard logging interface with async methods for all log levels
- **AbstractLogger**: Sophisticated base class with argument parsing and printf-style interpolation
- **Factory Pattern**: Pluggable logger factory system with auto-registration
- **Type Safety**: Full TypeScript support with proper interfaces and enums

## Key Components

### LoggerInterface

Standard interface defining async logging methods:

```typescript
interface LoggerInterface {
    debug(...args: unknown[]): Promise<void>;
    info(...args: unknown[]): Promise<void>;
    warning(...args: unknown[]): Promise<void>;
    error(...args: unknown[]): Promise<void>;
    critical(...args: unknown[]): Promise<void>;
    log(level: string, ...args: unknown[]): Promise<void>;
}
```

### AbstractLogger

Base class providing sophisticated argument parsing and features:

```typescript
export abstract class AbstractLogger implements LoggerInterface {
    // Implement only this method in concrete classes
    protected abstract logInternal(level: string, message: string, meta?: any): Promise<void>;
}
```

**Features:**
- **Log Level Filtering**: Automatic filtering based on configured level
- **5 Argument Patterns**: Flexible logging argument parsing
- **Printf Interpolation**: Support for %s, %d, %j, %o, %% placeholders
- **Structured Logging**: Object-based metadata support
- **Type Safety**: Full TypeScript support

### Argument Patterns

The AbstractLogger supports 5 flexible argument patterns:

```typescript
// Pattern 1: Single string message
logger.debug('Simple message');

// Pattern 2: Object-only structured logging
logger.debug({ userId: 123, action: 'login' });

// Pattern 3: Object + message
logger.debug({ userId: 123 }, 'Login failed');

// Pattern 4: Message + object metadata
logger.debug('Login failed', { userId: 123 });

// Pattern 5: Message + interpolation values
logger.debug('User %s failed login %d times', 'john', 3);
```

### Printf-Style Interpolation

Support for common printf placeholders:

```typescript
logger.info('User %s has %d items', 'john', 5);        // %s = string
logger.info('Processing %d/%d items', 1, 10);          // %d = number  
logger.info('Config: %j', { debug: true });            // %j = JSON
logger.info('Object: %o', someObject);                 // %o = object
logger.info('Literal %% symbol');                      // %% = literal %
```

### Factory System

Pluggable factory pattern with auto-registration:

```typescript
// Register a factory
LoggerFactoryRegistry.registerLoggerFactory('mylogger', MyLoggerFactory);

// Create logger instances
const factory = new LoggerFactory();
const logger = factory.createLogger({
    LOGGER_ADAPTER: 'mylogger',
    LOGGER_LEVEL: EnumLogLevel.Info
});
```

### Built-in Implementations

**ConsoleLogger**: Basic console output
```typescript
const factory = new LoggerFactory();
const logger = factory.createLogger({ LOGGER_ADAPTER: 'console', LOGGER_LEVEL: EnumLogLevel.Debug });
```

**NullLogger**: No-op logger for testing/disabled logging
```typescript
const factory = new LoggerFactory();
const logger = factory.createLogger({ LOGGER_ADAPTER: 'null' });
```

## Log Levels

```typescript
enum EnumLogLevel {
    Debug = 'debug',
    Info = 'info', 
    Warning = 'warning',
    Error = 'error',
    Critical = 'critical'
}
```

Log level hierarchy (lower levels include higher levels):
- `debug`: All messages
- `info`: Info, warning, error, critical
- `warning`: Warning, error, critical  
- `error`: Error, critical
- `critical`: Critical only

## Creating Custom Loggers

### Extending AbstractLogger

```typescript
import { AbstractLogger } from '@loggerhub/core';

export class MyLogger extends AbstractLogger {
    protected async logInternal(level: string, message: string, meta?: any): Promise<void> {
        // Your logging implementation
        console.log(`[${level.toUpperCase()}] ${message}`, meta || '');
    }
}
```

### Creating a Factory

```typescript
import { LoggerFactoryInterface, TypeLoggerConfig } from '@loggerhub/core';

export class MyLoggerFactory implements LoggerFactoryInterface {
    createLogger(config: TypeLoggerConfig): LoggerInterface {
        return new MyLogger(config);
    }
}
```

### Auto-Registration

```typescript
import { LoggerFactoryRegistry } from '@loggerhub/core';
import { MyLoggerFactory } from './MyLoggerFactory';

// Register your factory
LoggerFactoryRegistry.registerLoggerFactory('mylogger', MyLoggerFactory);
```

## Configuration

```typescript
interface TypeLoggerConfig {
    LOGGER_ADAPTER?: string;    // Logger adapter type (default: 'console')
    LOGGER_LEVEL?: EnumLogLevel; // Log level (default: 'info') 
    [key: string]: unknown;     // Additional adapter-specific config
}
```

### Environment Variables

The logger can be configured using environment variables:

- `LOGGER_ADAPTER` - Logger adapter type (default: `console`)
  - Available values: `console`, `null`, `winston` (if winston adapter is installed)
- `LOGGER_LEVEL` - Log level (default: `info`)
  - Available values: `debug`, `info`, `warning`, `error`, `critical`

Example `.env` file:
```env
# Logger Configuration
LOGGER_ADAPTER=console
LOGGER_LEVEL=info
```

### Usage with Environment Variables

```typescript
import { LoggerFactory } from '@loggerhub/core';

// Create logger using environment configuration
const factory = new LoggerFactory();
const logger = factory.createLogger();

// Override environment configuration if needed
const customLogger = factory.createLogger({
  LOGGER_ADAPTER: 'console',  // Overrides env LOGGER_ADAPTER
  LOGGER_LEVEL: EnumLogLevel.Debug  // Overrides env LOGGER_LEVEL
});
```

## Architecture Benefits

- **Consistency**: All loggers follow the same interface
- **Flexibility**: Multiple argument patterns for different use cases
- **Performance**: Log level filtering prevents unnecessary processing
- **Extensibility**: Easy to add new logger implementations
- **Type Safety**: Full TypeScript support with proper types
- **Testing**: Built-in null logger and registry reset for tests

## Installation

```bash
npm install @loggerhub/core
```

## License

MIT