@loggerhub/core
v1.0.5
Published
Core logger interfaces and built-in adapters for LoggerHub
Maintainers
Readme
@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:
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:
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:
// 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:
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:
// 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
const factory = new LoggerFactory();
const logger = factory.createLogger({ LOGGER_ADAPTER: 'console', LOGGER_LEVEL: EnumLogLevel.Debug });NullLogger: No-op logger for testing/disabled logging
const factory = new LoggerFactory();
const logger = factory.createLogger({ LOGGER_ADAPTER: 'null' });Log Levels
enum EnumLogLevel {
Debug = 'debug',
Info = 'info',
Warning = 'warning',
Error = 'error',
Critical = 'critical'
}Log level hierarchy (lower levels include higher levels):
debug: All messagesinfo: Info, warning, error, criticalwarning: Warning, error, criticalerror: Error, criticalcritical: Critical only
Creating Custom Loggers
Extending AbstractLogger
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
import { LoggerFactoryInterface, TypeLoggerConfig } from '@loggerhub/core';
export class MyLoggerFactory implements LoggerFactoryInterface {
createLogger(config: TypeLoggerConfig): LoggerInterface {
return new MyLogger(config);
}
}Auto-Registration
import { LoggerFactoryRegistry } from '@loggerhub/core';
import { MyLoggerFactory } from './MyLoggerFactory';
// Register your factory
LoggerFactoryRegistry.registerLoggerFactory('mylogger', MyLoggerFactory);Configuration
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)
- Available values:
LOGGER_LEVEL- Log level (default:info)- Available values:
debug,info,warning,error,critical
- Available values:
Example .env file:
# Logger Configuration
LOGGER_ADAPTER=console
LOGGER_LEVEL=infoUsage with Environment Variables
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
npm install @loggerhub/coreLicense
MIT
