2.4 KiB
2.4 KiB
Structured Logging & Correlation Tracking
This backend implements structured logging with correlation IDs for end-to-end request tracing.
Features
Correlation IDs
- Every request gets a unique
correlationId(UUID v4) - Propagated through middleware, services, and logs
- Returned in response headers as
X-Correlation-ID - Supports client-provided IDs via
X-Correlation-IDorX-Request-IDheaders
Structured Logs
- JSON format in production
- Colorized console with correlation ID in development
- All logs include:
timestamp,level,context,correlationId,message - Database persistence with full request context
Log Levels
error: System errors, exceptionswarn: Slow requests (>1s), deprecated featuresinfo: Request/response cycles, business eventsdebug: Detailed troubleshooting info
Usage
In Middleware
const logger = require('./src/utils/logger');
app.use((req, res, next) => {
logger.logInfo('MyContext', 'Processing request', {
correlationId: req.correlationId,
req
});
next();
});
In Services
const logger = require('./src/utils/logger');
async function myService(req, data) {
try {
logger.logInfo('MyService', 'Starting operation', {
correlationId: req.correlationId,
metadata: { itemId: data.id }
});
// ... operation
} catch (error) {
logger.logError('MyService', error, {
correlationId: req.correlationId,
errorCode: 'SERVICE_ERROR'
});
throw error;
}
}
Client-Side Tracking
// Send correlation ID from frontend
axios.get('/api/endpoint', {
headers: {
'X-Correlation-ID': clientGeneratedId
}
});
// Read it from response
const correlationId = response.headers['x-correlation-id'];
Azure App Insights Ready
Logs are structured for easy integration with Azure Application Insights:
- Correlation IDs map to
operation_Id - Contexts map to
customDimensions - Performance tracking via response times
To enable:
const appInsights = require('applicationinsights');
appInsights.setup(process.env.APPINSIGHTS_INSTRUMENTATIONKEY);
appInsights.defaultClient.context.tags[appInsights.defaultClient.context.keys.cloudRole] = 'tilbudgivern-backend';
appInsights.start();
Performance
- Async logging doesn't block requests
- Connection pooling for database logs
- Automatic cleanup on process termination