A standardized logging package for TypeScript microservices, built on top of Pino.
- 🚀 High-performance logging using Pino
- 🔍 Request ID tracking for service correlation
- 🌐 Express middleware for request/response logging
- 🛡️ Consistent error logging format
- 🧩 Contextual child loggers
npm install @unidev-hub/logger
import { createLogger } from '@unidev-hub/logger';
const logger = createLogger({
serviceName: 'user-service',
level: 'info',
prettyPrint: process.env.NODE_ENV === 'development'
});
logger.info('Server started', { port: 3000 });
logger.error('Failed to connect to database', new Error('Connection timeout'));
// Or with additional context
logger.error('Failed to connect to database', new Error('Connection timeout'), { host: 'db-server-1' });
import express from 'express';
import { createLogger, createRequestLogger, getRequestLogger } from '@unidev-hub/logger';
const app = express();
const logger = createLogger({ serviceName: 'api-gateway' });
// Apply middleware
app.use(createRequestLogger(logger, {
getUserId: (req) => req.user?.id,
skipPaths: ['/health', '/metrics']
}));
// Use in route handlers
app.get('/users', (req, res) => {
const requestLogger = getRequestLogger(req);
requestLogger.info('Fetching users');
// Your logic here
res.json({ users: [] });
});
app.listen(3000, () => {
logger.info('Server started', { port: 3000 });
});
// With Error object
logger.error('Failed to connect to database', new Error('Connection timeout'));
// With context object
logger.error('User validation failed', { userId: '123', reason: 'Invalid email' });
// With both Error and additional context
logger.error('Payment processing failed', new Error('Gateway timeout'), { orderId: 'ORD-123' });
function processOrder(orderId: string, userId: string) {
const orderLogger = logger.child({ orderId, userId });
orderLogger.info('Processing order');
// All logs from this logger will include orderId and userId
orderLogger.debug('Validating payment');
orderLogger.info('Order processed successfully');
}
The logger accepts the following configuration options:
Option | Type | Description | Default |
---|---|---|---|
serviceName | string | Name of the service | Required |
level | string | Minimum log level | 'info' or LOG_LEVEL env var |
prettyPrint | boolean | Format logs for human readability | true in development |
environment | string | Environment name | NODE_ENV or 'development' |
additionalFields | object | Extra fields to add to all logs | {} |
Option | Type | Description | Default |
---|---|---|---|
getUserId | Function | Extract user ID from request | undefined |
logRequestBody | boolean | Include request body in logs | false |
logResponseBody | boolean | Include response body in logs | false |
skipPaths | string[] | Paths to exclude from logging | [] |
- Use child loggers to add context to related log entries
- Include error objects in error logs for stack traces
-
Use appropriate log levels:
-
trace
: Very detailed debugging -
debug
: Debugging information -
info
: Normal operations -
warn
: Warning conditions -
error
: Error conditions -
fatal
: Critical failures
-
MIT