sparsh-node-logger
v1.0.6
Published
Centralized logging and error handling for Node.js microservices
Maintainers
Readme
Node.js Centralized Logging & Error Handling
A comprehensive logging and error handling module for Node.js microservices using Winston.
Features
- Standardized Error Handling: ApiError class with centralized error codes
- Multi-transport Logging: Console and file logging with Winston
- HTTP Request Tracking: Middleware for logging requests with performance metrics
- Environment-aware Formatting: Colorized for development, JSON for production
- Structured Logging: Consistent metadata across all log entries
Installation
npm installUsage
Basic Setup
const express = require('express');
const { logger, errorHandler, requestLogger } = require('./path-to-module');
const app = express();
// Apply request logger as early as possible
app.use(requestLogger);
// Your routes and other middleware here
// Apply error handler as the last middleware
app.use(errorHandler);
app.listen(3000, () => {
logger.info('Server started on port 3000');
});Logging
const { logger } = require('./path-to-module');
// Different log levels
logger.error('Critical application error', { details: err });
logger.warn('Warning condition', { source: 'database' });
logger.info('Informational message');
logger.http('HTTP-specific information');
logger.debug('Debugging information');
// With metadata
logger.info('User logged in', {
userId: user.id,
email: user.email,
timestamp: new Date()
});Error Handling
const { ApiError } = require('./path-to-module');
// Using error factory methods
app.get('/users/:id', (req, res, next) => {
const user = findUser(req.params.id);
if (!user) {
return next(ApiError.notFound('User not found'));
}
if (!canAccessUser(req.user, user)) {
return next(ApiError.forbidden('You cannot access this user'));
}
res.json(user);
});
// Handling validation errors
app.post('/users', (req, res, next) => {
const { name, email } = req.body;
const errors = {};
if (!name) errors.name = 'Name is required';
if (!email) errors.email = 'Email is required';
if (Object.keys(errors).length > 0) {
return next(ApiError.validationError('Validation failed', errors));
}
// Create user...
res.status(201).json(user);
});
// Catching and converting other errors
app.get('/data', async (req, res, next) => {
try {
const data = await fetchData();
res.json(data);
} catch (err) {
// Convert to API error
next(ApiError.internal('Failed to fetch data', {}, err));
}
});Example Server
Run the example server to see the logger in action:
npm startThen visit:
http://localhost:3000/- Basic routehttp://localhost:3000/log-levels- See different log levelshttp://localhost:3000/error- Triggers a generic errorhttp://localhost:3000/api-error- Triggers an API errorhttp://localhost:3000/not-found- 404 errorPOST http://localhost:3000/users- Test validation errors
Environment Variables
NODE_ENV: Set to 'production' for production-optimized loggingLOG_LEVEL: Override default log level (default: 'debug' in dev, 'info' in prod)SERVICE_NAME: Name of your service (included in logs)LOG_DIR: Directory for log files (default: 'logs')
