/

Correlation IDs

Correlation IDs help you track requests as they flow through different services, components, and layers of your application.

Basic Usage

Use the correlationId property in the options object:

// Set correlation ID for a log entry
Log.info('Payment process started', {
    correlationId: 'operation-123'
});

// Use with different log levels
Log.debug('Processing user request', {
    correlationId: 'req-456'
});

Log.error('Request failed', {
    correlationId: 'req-456',
    context: { errorCode: 'TIMEOUT' }
}, error);

Generating Correlation IDs

// Generate unique correlation IDs
const correlationId = crypto.randomUUID().substring(0, 8);

// Or use a simple function
const generateId = () => Math.random().toString(36).substring(2, 10);

Log.info('Order processing started', {
    correlationId: generateId()
});

Express.js Integration

// Middleware to add correlation ID to all requests
app.use((req, res, next) => {
    req.correlationId = req.headers['x-correlation-id'] || crypto.randomUUID().substring(0, 8);
    res.setHeader('x-correlation-id', req.correlationId);
    next();
});

// Use in routes
app.post('/api/orders', async (req, res) => {
    Log.info('Order creation started', {
        correlationId: req.correlationId,
        context: { customerId: req.body.customerId }
    });
    
    try {
        const order = await orderService.create(req.body, req.correlationId);
        
        Log.info('Order created successfully', {
            correlationId: req.correlationId,
            context: { orderId: order.id }
        });
        
        res.json(order);
    } catch (error) {
        Log.error('Order creation failed', {
            correlationId: req.correlationId
        }, error);
        
        res.status(500).json({ error: 'Failed to create order' });
    }
});

Service Layer Usage

class OrderService {
    async createOrder(orderData, correlationId) {
        Log.info('Order validation started', {
            correlationId,
            context: { customerId: orderData.customerId }
        });
        
        try {
            const order = await this.processOrder(orderData);
            
            Log.info('Order processed successfully', {
                correlationId,
                context: { orderId: order.id }
            });
            
            return order;
        } catch (error) {
            Log.error('Order processing failed', {
                correlationId,
                context: { customerId: orderData.customerId }
            }, error);
            
            throw error;
        }
    }
}

Best Practices

Correlation ID Best Practices

  • Use short IDs: 8-12 characters are usually sufficient
  • Pass IDs between services: Include correlation IDs when calling other services
  • Generate unique IDs: Use crypto.randomUUID() or similar for unique identifiers
  • Log at boundaries: Always log when entering/exiting services or operations

Next Steps

Previous
User Identification