Error Logging — Structured Error Logging for APIs
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Error Logging. We cover key concepts, practical examples, and best practices to help you master this topic.
Structured error logging captures error details in a consistent format with request context, enabling debugging, monitoring, and alerting for API errors.
Implementation
function logError(error, req) {
const logEntry = {
requestId: error.requestId || req.id,
timestamp: error.timestamp || new Date().toISOString(),
method: req.method,
path: req.path,
statusCode: error.statusCode || 500,
errorCode: error.error,
message: error.message,
userId: req.user?.id,
ip: req.ip,
userAgent: req.headers["user-agent"]
};
if (error.statusCode >= 500) {
console.error(JSON.stringify(logEntry));
alertingService.sendAlert(logEntry);
} else {
console.warn(JSON.stringify(logEntry));
}
}
Log Levels
Use appropriate log levels: ERROR for 5xx errors (server problems), WARN for 4xx errors (client problems), INFO for 429 rate limits (operational), DEBUG for detailed error context in development.
Common Mistakes
- No structured logging — Plain text logs are hard to search.
- Missing request context — Cannot identify which request caused the error.
- Logging sensitive data — Never log passwords, tokens, or PII.
- No log level differentiation — Treating all errors equally.
Practice Questions
- What information should an error log entry include?
- What log level should 5xx errors use?
- What data should never be logged?
What's Next
In the next lesson, you will learn error monitoring with Sentry.
← Previous
Error Middleware — Global Error Handlers in Express and FastAPI
Next →
Error Monitoring — Tracking Errors with Sentry
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro