@devcode-sdk/logger
v0.3.2
Published
Logger Service
Readme
@devcode-sdk/logger
A logger service built on top of Pino Node.js logger with advanced features for modern applications. This package is production-ready and can be improved continuously.
Installation
$ npm install @devcode-sdk/loggerNode.js v24+ Required
Why? Because of my wish :)
Quick Start
import { AsyncLocalStorage } from 'node:async_hooks';
import { ILoggerConfig, LoggerService } from '@devcode-sdk/logger';
// Optional: Setup async context for distributed tracing
const localStorage = new AsyncLocalStorage<{ traceId: string }>();
const loggerConfig: ILoggerConfig = {
level: 'debug',
maskedKeys: ['password', 'token'],
lokiTransport: {
host: 'http://grafana.lab:3100',
timeout: 5000,
labels: {
app: 'my-some-service',
},
},
};
const logger = new LoggerService(loggerConfig, localStorage);
logger.error('error', new Error('test'));
logger.warn('warn');
logger.info('info', { password: '123456' });
logger.debug('debug');
logger.trace('trace');Key Features
1. Structured Logging
- Built on top of Pino for high-performance JSON logging
- Zero dependencies beyond Pino
- Fast and memory-efficient
2. Sensitive Data Protection
- Automatic masking of sensitive keys in log output
- Configurable mask patterns
- Prevents accidental exposure of credentials
3. Distributed Tracing Support
- Optional AsyncLocalStorage integration
- Adds traceId to log entries for correlation
- Enables end-to-end request tracking
4. Grafana Loki Integration
- Seamless logging to Grafana Loki
- Configurable host and timeout settings
- Customizable labels for better log organization
Configuration Options
ILoggerConfig Interface
interface ILoggerConfig {
level?: 'trace' | 'debug' | 'info' | 'warn' | 'error';
maskedKeys?: string[];
lokiTransport?: {
host: string;
timeout?: number;
labels?: Record<string, string>;
};
}Level Configuration
trace: Most verbose level (not typically used in production)debug: Development debugging informationinfo: General operational messageswarn: Warning conditions that might need attentionerror: Error conditions requiring immediate attention
Advanced Usage Examples
Basic Logger Setup
const logger = new LoggerService({
level: 'info',
maskedKeys: ['password', 'token', 'secret']
});With Loki Integration
const logger = new LoggerService({
level: 'debug',
lokiTransport: {
host: 'http://localhost:3100',
timeout: 3000,
labels: {
app: 'my-service',
environment: process.env.NODE_ENV
}
}
});With Async Context (Distributed Tracing)
import { AsyncLocalStorage } from 'node:async_hooks';
const localStorage = new AsyncLocalStorage<{ traceId: string }>();
const logger = new LoggerService(loggerConfig, localStorage);
// In your request handler
const span = createSpan();
localStorage.run({ traceId: span.id }, () => {
logger.info('Processing request');
});Performance Considerations
Log Level Filtering
The logger automatically filters messages based on configured log level, reducing unnecessary processing.
Asynchronous Operations
Loki transport operations are handled asynchronously to avoid blocking the main execution thread.
Environment Variables
# Example environment configuration
LOG_LEVEL=info
MASKED_KEYS=password,token,secret
LOKI_HOST=http://localhost:3100
LOKI_TIMEOUT=5000Troubleshooting
Common Issues
Loki Connection Failures
- Verify Loki host URL is accessible
- Check network connectivity
- Ensure proper timeout values are configured
Masked Keys Not Working
- Confirm keys are properly spelled in
maskedKeysarray - Check that sensitive data is passed as object properties, not strings
- Confirm keys are properly spelled in
Missing Trace IDs
- Ensure AsyncLocalStorage is properly initialized and used
- Verify context is set before logging operations
Best Practices
Configuration Management
// Use environment variables for configuration
const loggerConfig = {
level: process.env.LOG_LEVEL || 'info',
maskedKeys: process.env.MASKED_KEYS?.split(',') || [],
lokiTransport: process.env.LOKI_HOST ? {
host: process.env.LOKI_HOST,
timeout: parseInt(process.env.LOKI_TIMEOUT) || 5000
} : undefined
};License
Released under the ISC License.
