Skip to content

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

  1. No structured logging — Plain text logs are hard to search.
  2. Missing request context — Cannot identify which request caused the error.
  3. Logging sensitive data — Never log passwords, tokens, or PII.
  4. No log level differentiation — Treating all errors equally.

Practice Questions

  1. What information should an error log entry include?
  2. What log level should 5xx errors use?
  3. What data should never be logged?

What's Next

In the next lesson, you will learn error monitoring with Sentry.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro