Skip to content

Structured Error Logging — Logging Errors with Rich Context

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Structured Error Logging. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Structured error logging captures rich context about failures including stack traces, request state, and error fingerprints for effective debugging.

// Structured error class
class AppError extends Error {
  constructor(code, message, options = {}) {
    super(message);
    this.code = code;
    this.statusCode = options.statusCode || 500;
    this.severity = options.severity || 'error';
    this.correlationId = options.correlationId;
    this.userId = options.userId;
    this.requestPath = options.requestPath;
    this.requestMethod = options.requestMethod;
    this.context = options.context || {};
    this.timestamp = new Date().toISOString();
    this.errorId = uuidv4();

    // Capture error fingerprint
    this.fingerprint = this.generateFingerprint();
  }

  generateFingerprint() {
    const relevant = `${this.code}:${this.message?.slice(0, 100)}`;
    return crypto.createHash('sha256').update(relevant).digest('hex').slice(0, 16);
  }

  toLogEntry() {
    return {
      type: 'error',
      errorId: this.errorId,
      code: this.code,
      message: this.message,
      severity: this.severity,
      statusCode: this.statusCode,
      correlationId: this.correlationId,
      userId: this.userId,
      request: {
        method: this.requestMethod,
        path: this.requestPath
      },
      context: this.context,
      stack: this.stack?.split('\n').slice(0, 10),
      fingerprint: this.fingerprint,
      timestamp: this.timestamp
    };
  }
}

// Error logging middleware
function errorLoggingMiddleware(err, req, res, next) {
  const error = err instanceof AppError ? err : new AppError('UNEXPECTED', err.message, {
    statusCode: err.status || 500,
    correlationId: req.correlationId,
    userId: req.user?.id,
    requestPath: req.path,
    requestMethod: req.method,
    context: { originalError: err.name, originalStack: err.stack }
  });

  logger.error(error.toLogEntry());

  // Track error rate
  metrics.increment('errors.total', { code: error.code, severity: error.severity });

  // Alert on critical errors
  if (error.severity === 'critical' || error.severity === 'fatal') {
    alertService.sendAlert({
      title: `Critical Error: ${error.code}`,
      description: error.message,
      errorId: error.errorId,
      correlationId: error.correlationId
    });
  }

  res.status(error.statusCode).json({
    error: error.code,
    errorId: error.errorId,
    message: error.statusCode === 500 ? 'Internal server error' : error.message
  });
}

Structured error logs enable error grouping, trending, and rapid root cause analysis in production systems.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro