Skip to content

Error Logging

DodaTech 2 min read

title: "Error Logging — Structured Logging for API Debugging" description: "API error logging captures structured log data including timestamps, trace IDs, request details, error codes, and stack traces for debugging and monitoring." date: 2026-06-28 lastmod: 2026-06-28 weight: 22 tags: [apis, error-handling] }

API error logging captures structured information about errors including timestamps, trace IDs, request context, error codes, and stack traces for debugging and monitoring.

What You'll Learn

  • Structured logging patterns for API errors
  • Log levels and when to use each
  • Centralized log aggregation

Why It Matters

Good logging turns errors into actionable debugging data. Without structured logs, finding the root cause of production errors is guesswork.

Code Examples

# Structured error logging
import logging
import json

logger = logging.getLogger("api")

def log_error(request, error, trace_id):
    log_entry = {
        "level": "ERROR",
        "trace_id": trace_id,
        "timestamp": datetime.utcnow().isoformat(),
        "method": request.method,
        "path": request.path,
        "query": dict(request.args),
        "user_id": getattr(request, "user_id", None),
        "error_code": getattr(error, "code", type(error).__name__),
        "error_message": str(error),
        "status_code": getattr(error, "status_code", 500)
    }
    logger.error(json.dumps(log_entry))

# Usage in error middleware
@app.errorhandler(AppError)
def handle_error(error):
    trace_id = request.headers.get("X-Trace-ID", str(uuid.uuid4()))
    log_error(request, error, trace_id)
    return jsonify(error.to_dict(), trace_id=trace_id), error.status_code
// Structured error logging in Express
const logger = require('pino')();

function logError(err, req, traceId) {
  logger.error({
    traceId,
    method: req.method,
    url: req.url,
    ip: req.ip,
    userId: req.user?.id,
    errorCode: err.code || err.name,
    errorMessage: err.message,
    stack: err.stack
  });
}

Common Mistakes

1. Logging Without Context

A log without request context (URL, user, trace ID) is nearly useless.

2. Logging at Wrong Level

Use ERROR for failures, WARN for recoverable issues, INFO for normal operations.

3. Logging Sensitive Data

Never log passwords, tokens, API keys, or personal data.

4. Not Using Structured Format

Structured JSON logs are searchable; plain text logs are not.

5. No Log Rotation

Production logs grow quickly. Implement rotation and retention policies.

Practice Questions

  1. What context should every error log include?
  2. When should you use WARN vs ERROR level?
  3. Why should logs be structured (JSON)?
  4. What data should never be logged?
  5. Why are trace IDs important for logging?

Answers:

  1. Trace ID, timestamp, method, path, user ID, error code, error message.
  2. WARN for recoverable issues (retries, rate limit approaching); ERROR for failures.
  3. Structured logs can be parsed, searched, and analyzed by log aggregation tools.
  4. Passwords, tokens, API keys, credit card numbers, personal data.
  5. They connect error logs to specific requests for debugging.

Challenge: Set up structured error logging for an API with appropriate log levels, context capture, and a log aggregation plan.

FAQ

What is the best log aggregation tool?

: ELK Stack (Elasticsearch, Logstash, Kibana), Datadog, or AWS CloudWatch.

How long should logs be retained?

: 30 days for general logs, 90+ days for audit logs.

Should I log 400 errors?

: Yes, at WARN level. High rates of 400s may indicate client issues.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro