@tklein1801/logger.js
v0.3.1
Published
   
Installation
npm install @tklein1801/logger.jsQuick Start
Basic Usage
import { LogLevel, LogClient } from '@tklein1801/logger.js';
const logger = LogClient.fromConfig({
label: 'MyApp',
level: LogLevel.INFO,
});
// or
const anotherLogger = LogClient.builder()
.withLabel('MyApp')
.withLevel(LogLevel.DEBUG)
.withDefaultMeta({service: 'UserService', version: '1.0.0'})
.build();
logger.info('Application started');
logger.warn('This is a warning');
logger.error('An error occurred');Child Loggers
Create scoped loggers that inherit parent configuration:
const childLogger = LogClient.fromParent(parentLogger,{
label: 'Database',
level: LogLevel.DEBUG,
});
childLogger.debug('Database connection established');Multiple Transports
Send logs to multiple destinations with different configurations:
import { LogLevel, createLogger, Transport, type LogEntry } from '@tklein1801/logger.js';
class FileTransport extends Transport {
protected sendBatch(logs: LogEntry[]): void {
logs.forEach((log) => console.log(`[FILE] ${log.message}`));
}
}
const logger = LogClient.fromConfig({
label: 'MultiTransportApp',
level: LogLevel.INFO,
transports: [
new FileTransport({
label: 'file',
batchSize: 10,
debounceMs: 1000,
level: LogLevel.WARN, // Only warnings and errors to file
}),
],
});Transport System
The transport system handles efficient log transmission with built-in optimizations:
- Batching: Groups logs to reduce transmission overhead
- Debouncing: Delays transmission to avoid overwhelming receivers
- Level Filtering: Processes only logs meeting minimum severity
- Error Recovery: Automatically re-queues failed logs for retry
Custom Transports
[!TIP] Inside the
examplesfolder, you can find some custom transport implementations.
Create custom transports by extending the Transport base class:
import { Transport, type LogEntry, type TransportOptions } from '@tklein1801/logger.js';
class DatabaseTransport extends Transport {
constructor(options: TransportOptions & { connectionString: string }) {
super(options);
}
protected async sendBatch(logs: LogEntry[]): Promise<void> {
// Send logs to your database
for (const log of logs) {
await this.saveLog(log);
}
}
private async saveLog(log: LogEntry): Promise<void> {
// Your database implementation
}
}
const logger = LogClient.fromConfig({
transports: [
new DatabaseTransport({
label: 'database',
connectionString: 'mongodb://localhost:27017/logs',
batchSize: 20,
debounceMs: 2000,
}),
],
});Transport Configuration
Configure transport behavior with these options:
batchSize: Number of logs to group before transmission (default: 10)debounceMs: Delay before sending logs in milliseconds (default: 1000)level: Minimum log level to process (default: LogLevel.INFO)enabled: Whether the transport is active (default: true)label: Transport identifier for debugging
API Reference
Log Levels
enum LogLevel {
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3,
}Logger Methods
logger.debug(message, ...args)- Debug level logginglogger.info(message, ...args)- Info level logginglogger.warn(message, ...args)- Warning level logginglogger.error(message, ...args)- Error level logginglogger.child(options)- Create child logger with inherited config
Transport Lifecycle
transport.enable()- Enable the transporttransport.disable()- Disable and flush remaining logstransport.flush()- Immediately send all queued logstransport.destroy()- Clean up resources
Development
# Install dependencies
npm install
# Run tests
npm test
# Build package
npm run build
# Lint and format
npm run checkCredits
lodash.debounce- Used for debouncing the transportation of logs in the Transport system to reduce load on receivers and improve batching efficiency. This ensures that during high-frequency logging periods, logs are accumulated and sent in batches rather than individually, optimizing performance and reducing network overhead.
