Request Logging — Comprehensive Request and Response Logging
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you'll learn about Request Logging. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Request logging captures comprehensive metadata about every API request for debugging, auditing, and performance analysis.
// Request logger middleware
function requestLogger(options = {}) {
const {
logBody = false,
maxBodySize = 4096,
excludePaths = ['/health', '/metrics'],
logHeaders = true,
sensitiveHeaders = ['authorization', 'cookie', 'x-api-key']
} = options;
return (req, res, next) => {
if (excludePaths.some(p => req.path.startsWith(p))) return next();
const startTime = Date.now();
const requestEntry = {
type: 'request',
timestamp: new Date().toISOString(),
method: req.method,
path: req.path,
query: req.query,
correlationId: req.correlationId,
userId: req.user?.id,
userAgent: req.headers['user-agent'],
ip: req.ip,
contentLength: parseInt(req.headers['content-length'] || '0'),
headers: logHeaders ? sanitizeHeaders(req.headers, sensitiveHeaders) : undefined
};
if (logBody && req.body) {
requestEntry.body = truncateBody(req.body, maxBodySize);
}
// Capture response
const originalEnd = res.end.bind(res);
const chunks = [];
res.end = function(chunk, encoding) {
if (chunk) chunks.push(Buffer.from(chunk));
const duration = Date.now() - startTime;
const responseEntry = {
type: 'response',
statusCode: res.statusCode,
duration,
correlationId: req.correlationId,
contentLength: res.getHeader('content-length') || chunks.reduce((s, c) => s + c.length, 0),
slow: duration > (options.slowThreshold || 1000)
};
const logLevel = res.statusCode >= 500 ? 'error'
: res.statusCode >= 400 ? 'warn'
: duration > 1000 ? 'warn'
: 'info';
logger[logLevel]({ ...requestEntry, ...responseEntry });
return originalEnd(chunk, encoding);
};
next();
};
}
Request logging provides end-to-end visibility into API traffic patterns, error rates, and performance characteristics.
← Previous
Structured Error Logging — Logging Errors with Rich Context
Next →
Database Query Logging — Logging and Monitoring Database Queries
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro