@megallm/logger
v1.0.2
Published
Enterprise-grade logging package with Loki, OpenTelemetry, file rotation, and beautiful console output
Maintainers
Readme
mega-logger
Enterprise-grade logging for Node.js with beautiful console output, Loki integration, OpenTelemetry support, and daily file rotation.
Features
- Beautiful Console Output - Colorful, emoji-rich logs in development; structured JSON in production
- Multiple Log Levels -
trace,debug,info,success,warn,error,fatal,silent - Daily File Rotation - Automatic log file rotation with size limits and compression
- Loki Integration - Send logs to Grafana Loki for aggregation and querying
- OpenTelemetry Support - Distributed tracing with automatic span correlation
- Child Loggers - Create contextual loggers with inherited metadata
- Performance Timing - Built-in utilities for measuring operation duration
- TypeScript-First - Full type safety with comprehensive type exports
- Zero Config - Works out of the box with sensible defaults
Installation
npm install mega-loggerFor OpenTelemetry support (optional):
npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-httpQuick Start
import { logger } from 'mega-logger';
// Simple logging
logger.info('Application started');
logger.debug('Debug information', { userId: 123 });
logger.error('Something went wrong', new Error('Failed to connect'));
// With timing
await logger.withTiming('database query', async () => {
// Your operation here
});Configuration
Basic Configuration
import { Logger } from 'mega-logger';
const logger = new Logger({
level: 'debug',
service: 'my-app',
environment: 'development',
defaultMetadata: {
version: '1.0.0',
},
});Environment Variables
LOG_LEVEL- Set minimum log level (trace,debug,info,warn,error,fatal,silent)NODE_ENV- Set environment (development,production,test)SERVICE_NAME- Set service name for logs
Console Output
Development mode shows beautiful, colorful logs:
[10:30:45.123] ℹ️ INFO [my-app] User logged in
userId: 123
email: "[email protected]"Production mode outputs structured JSON:
{
"timestamp": "2024-01-15T10:30:45.123Z",
"level": "info",
"message": "User logged in",
"service": "my-app",
"userId": 123,
"email": "[email protected]"
}File Rotation
import { Logger } from 'mega-logger';
const logger = new Logger({
file: {
directory: './logs',
filename: 'app',
maxSize: '10M', // Rotate when file exceeds 10MB
maxFiles: 7, // Keep 7 days of logs
interval: '1d', // Rotate daily
compress: true, // Gzip rotated files
},
});Loki Integration
import { Logger } from 'mega-logger';
const logger = new Logger({
loki: {
host: 'http://localhost:3100',
labels: {
app: 'my-app',
env: 'production',
},
batchSize: 100,
flushInterval: 5000,
},
});OpenTelemetry
import { Logger } from 'mega-logger';
const logger = new Logger({
openTelemetry: {
enabled: true,
serviceName: 'my-app',
endpoint: 'http://localhost:4318/v1/traces',
},
});
// Logs will automatically include trace_id and span_id
// when called within an active span
await logger.span('database-query', async () => {
logger.info('Executing query');
// ...
});API Reference
Log Levels
logger.trace('Most verbose level');
logger.debug('Debug information');
logger.info('General information');
logger.success('Operation succeeded');
logger.warn('Warning message');
logger.error('Error occurred');
logger.fatal('Critical error');Metadata
// Object metadata
logger.info('User action', { userId: 123, action: 'login' });
// Error objects
logger.error('Failed', new Error('Connection timeout'));Child Loggers
const requestLogger = logger.child({
requestId: 'abc-123',
userId: 456,
});
requestLogger.info('Processing request'); // Includes requestId and userIdTiming Utilities
// Automatic timing with withTiming
const result = await logger.withTiming('operation', async () => {
// Your async operation
return someResult;
});
// Manual timing with startTimer
const stopTimer = logger.startTimer('long-operation');
// ... do work ...
const { duration, durationFormatted } = stopTimer();Level Management
logger.setLevel('debug');
const currentLevel = logger.getLevel();Transport Management
import { ConsoleTransport, FileTransport } from 'mega-logger';
// Add transport
logger.addTransport(new ConsoleTransport());
// Remove transport
logger.removeTransport('console');
// List transports
const transports = logger.getTransports();Graceful Shutdown
// Flush all pending logs
await logger.flush();
// Close all transports
await logger.close();Formatters
Built-in Formatters
import {
PrettyFormatter,
CompactPrettyFormatter,
JsonFormatter,
NdjsonFormatter,
LogfmtFormatter,
} from 'mega-logger';
// Pretty (development)
new PrettyFormatter({ showIcons: true, colors: true });
// Compact pretty
new CompactPrettyFormatter();
// JSON (production)
new JsonFormatter({ pretty: false });
// NDJSON (newline-delimited JSON)
new NdjsonFormatter();
// Logfmt (key=value pairs)
new LogfmtFormatter();Custom Formatters
import type { Formatter, LogEntry } from 'mega-logger';
class MyFormatter implements Formatter {
format(entry: LogEntry): string {
return `[${entry.level}] ${entry.message}`;
}
}Transports
Built-in Transports
import {
ConsoleTransport,
FileTransport,
LokiTransport,
OpenTelemetryTransport,
} from 'mega-logger';Custom Transports
import type { Transport, LogEntry } from 'mega-logger';
class MyTransport implements Transport {
name = 'my-transport';
log(entry: LogEntry): void | Promise<void> {
// Send log somewhere
}
async flush(): Promise<void> {
// Flush pending logs
}
async close(): Promise<void> {
// Cleanup
}
}Utilities
import {
formatDuration,
maskSensitiveData,
generateTraceId,
detectEnvironment,
parseLogLevel,
} from 'mega-logger';
// Format milliseconds to human readable
formatDuration(1500); // "1.50s"
// Mask sensitive fields
maskSensitiveData({ password: 'secret123' }); // { password: 'se***23' }
// Generate trace IDs
generateTraceId(); // "a1b2c3d4e5f6..."Best Practices
1. Use Structured Metadata
// Good
logger.info('User logged in', { userId: 123, method: 'oauth' });
// Avoid
logger.info(`User ${userId} logged in via ${method}`);2. Use Appropriate Levels
trace- Extremely detailed tracingdebug- Debugging informationinfo- General operational messagessuccess- Successful operations (optional)warn- Warning conditionserror- Error conditionsfatal- Critical errors requiring immediate attention
3. Create Child Loggers for Context
app.use((req, res, next) => {
req.logger = logger.child({
requestId: req.id,
path: req.path,
});
next();
});4. Don't Log Sensitive Data
// Use maskSensitiveData utility
import { maskSensitiveData } from 'mega-logger';
logger.info('Request received', maskSensitiveData(requestBody));5. Always Flush Before Exit
process.on('SIGTERM', async () => {
await logger.flush();
process.exit(0);
});TypeScript Support
Full TypeScript support with exported types:
import type {
Logger,
LogLevel,
LogEntry,
LogMetadata,
Transport,
Formatter,
LoggerConfig,
} from 'mega-logger';License
MIT
