Contextual Logging — Enriching Logs with Request and User Context
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you'll learn about Contextual Logging. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Contextual logging automatically enriches every log entry with request, user, and environment context without manual parameter passing.
// Async Local Storage context
const { AsyncLocalStorage } = require('async_hooks');
const logContext = new AsyncLocalStorage();
function contextMiddleware(req, res, next) {
const context = {
correlationId: req.correlationId || uuidv4(),
userId: req.user?.id,
sessionId: req.session?.id,
tenantId: req.tenant?.id,
ip: req.ip,
userAgent: req.headers['user-agent'],
requestId: uuidv4(),
startTime: Date.now()
};
logContext.run(context, () => next());
}
// Context-aware logger
const contextualLogger = {
info: (message, data = {}) => {
const ctx = logContext.getStore() || {};
logger.info({
...ctx,
message,
...data,
timestamp: new Date().toISOString(),
duration: ctx.startTime ? Date.now() - ctx.startTime : undefined
});
},
error: (message, error, data = {}) => {
const ctx = logContext.getStore() || {};
logger.error({
...ctx,
message,
error: {
name: error?.name,
message: error?.message,
stack: error?.stack?.split('\n').slice(0, 5)
},
...data,
timestamp: new Date().toISOString()
});
},
warn: (message, data = {}) => {
const ctx = logContext.getStore() || {};
logger.warn({ ...ctx, message, ...data, timestamp: new Date().toISOString() });
}
};
// Usage anywhere in request lifecycle
app.get('/api/scans', async (req, res) => {
contextualLogger.info('Fetching scans', { filter: req.query.filter });
const scans = await scanService.getAll();
contextualLogger.info(`Found ${scans.length} scans`);
res.json(scans);
});
Contextual logging eliminates the need to manually pass correlation IDs and user context to every log call.
← Previous
Log Shipping — Reliable Log Transport from Services to Central Storage
Next →
Log Format Standards — Defining Consistent Log Schemas Across Teams
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro