← All posts

From Silent Crashes to Insight: Logging 101 for Backend Services

Turn silent 500 errors into clear, actionable insights by treating logs as breadcrumbs, structuring them, and feeding them into metrics and tracing.

When a user hits a page that returns an “Error 500”, the server has already failed, but the logs that were written before the crash are often the only clue left.
If those logs are missing or unstructured, the incident becomes a silent crash that a team has to hunt for in a sea of text.
This article shows how to turn those silent crashes into actionable insights by treating logs as breadcrumbs, structuring them, and feeding them into metrics and tracing systems.

TL;DR

  • Use structured JSON logs with context fields (user_id, request_id, component).
  • Log at appropriate levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.
  • Capture request, error, and latency data in a minimal Flask app.
  • Aggregate logs to create metrics and alerts; visualize them on dashboards.
  • Add distributed tracing spans to see request flow across services.
  • Avoid over‑logging; keep logs readable and searchable.

1. Why Logging Matters in Backends

When a backend service is running in production, developers can no longer step through code with a debugger.
Logs are the primary source of evidence that tells what happened, when it happened, and why it happened.
They are the historical record that lets a team:

  1. Diagnose an error after the fact.
  2. Reproduce the issue in a controlled environment by replaying the logged context.
  3. Respond faster to incidents by having a clear trail of events.

In practice, a well‑structured log line can be the difference between a 30‑minute investigation and a 5‑minute fix.

2. The “Error 500” Breadcrumb Analogy

Imagine walking through a dense forest during a rainstorm.
You drop a breadcrumb every time you step, so that if you get lost you can follow the trail back to the clearing.
In software, each log line is a breadcrumb.
When a “tree falls” (i.e., an HTTP 500 error), the trail of breadcrumbs lets you trace back to the root cause—perhaps a missing configuration, a null pointer, or a database timeout.

Without breadcrumbs, you wander blind, guessing which branch caused the fall.
With a breadcrumb trail, you can see the exact path of the error and fix the tree that caused it.

3. Log Levels & Structured Logging

Log Levels

Level Typical Use
DEBUG Fine‑grained diagnostic information.
INFO General operational events.
WARNING Unexpected but non‑critical conditions.
ERROR Failures that prevent a request from succeeding.
CRITICAL Severe failures that may crash the service.

Choosing the right level keeps the log volume manageable and lets operators focus on what matters.

Structured Logs

Plain‑text logs are hard to search and aggregate.
Structured logs are JSON objects that can be queried by key.
A structured log might look like this:

{
  "timestamp": "2024-10-13T12:34:56.789Z",
  "level": "ERROR",
  "message": "Database connection failed",
  "user_id": "42",
  "request_id": "abcd1234",
  "component": "auth-service",
  "error": "OperationalError: timeout"
}

Because each field is a key/value pair, you can filter all logs where level="ERROR" and component="auth-service" in seconds, rather than scrolling through pages of text.

Adding Context

Context fields such as user_id, request_id, and component tie a log entry back to a specific request, user, or subsystem.
They enable correlation across services, turning a single line of text into a navigable link in a monitoring dashboard.

4. Metrics & Alerts from Logs

Logs can be turned into actionable metrics:

Metric How to Compute Why It Matters
error_rate count(ERROR) / count(ALL) per minute Detects sudden spikes in failures
latency_avg Average of response_time_ms Measures performance degradation
critical_incidents Count of CRITICAL logs Triggers emergency alerts

By aggregating logs in a log‑store (e.g., Loki, Elasticsearch) and feeding them into a metrics engine (Prometheus, Grafana), you can set alert thresholds.
For example, if error_rate exceeds 5% for 5 consecutive minutes, send an email or Slack message.

Dashboards transform raw logs into visual patterns: heat maps of error spikes, line charts of latency, and funnel views of request success rates.

5. Tracing: Following a Request Across Services

What is Distributed Tracing?

Distributed tracing records the path a request takes through multiple services.
Each service creates a span—a named operation with a start and end timestamp.
Spans are linked by a unique trace_id and a parent span_id.

How It Helps

  • Latency hotspots: Identify which service or operation takes the longest.
  • Failure points: Spot where a request fails (e.g., a span with an error status).
  • Correlation: Match logs to the same trace using trace_id.

Example

A user requests /profile.

  • Service A starts a span get_user_profile.
  • Service A calls Service B; Service B starts a span fetch_user_data.
  • Service B calls Service C; Service C starts a span query_db.
    If Service C times out, the trace shows the exact span that failed, and the logs from that span contain the error details.

6. Common Mistakes & Trade‑offs

Mistake Consequence Mitigation
Logging too much data Storage costs rise; log ingestion slows Log only necessary fields; use log rotation
Using plain‑text logs Hard to search; no key/value filtering Switch to JSON structured logs
Mixing levels DEBUG logs pollute production Separate environments; use log level filters
Not adding context Hard to correlate logs across services Add request_id, trace_id, component

Balancing Verbosity and Performance

Logging is I/O‑bound. Too many logs can slow down your service.
A good practice is to log at INFO or WARNING in production, and enable DEBUG only when investigating.
Also, batch writes to the log file or use an asynchronous logger to avoid blocking request handling.

Choosing a Log Format Early

If you start with plain text and later switch to JSON, you’ll need to rewrite log consumers and dashboards.
Decide on a format (JSON is recommended) and stick with it.
If you need to support multiple consumers, emit the JSON and also keep a human‑readable line for local debugging.

Real‑World Example: Minimal Flask App

Below is a tiny Flask application that demonstrates:

  1. Logging every request with a unique request_id.
  2. Structured JSON logs.
  3. Error handling that logs stack traces.
  4. Simple latency measurement.
# app.py
import json
import logging
import time
import uuid
from flask import Flask, request, jsonify, g

app = Flask(__name__)

# Configure the root logger to write JSON to stdout
logging.basicConfig(
    level=logging.INFO,
    format='%(message)s',          # raw message; we’ll emit JSON ourselves
    handlers=[logging.StreamHandler()]
)
logger = logging.getLogger(__name__)

def log_json(**kwargs):
    """Emit a single JSON log line."""
    logger.info(json.dumps(kwargs))

@app.before_request
def start_timer():
    """Add a request_id and start time to the request context."""
    g.request_id = str(uuid.uuid4())
    g.start_time = time.time()

@app.after_request
def log_request(response):
    """Log the request after it has been processed."""
    latency_ms = int((time.time() - g.start_time) * 1000)
    log_json(
        timestamp=time.strftime("%Y-%m-%dT%H:%M:%S.%fZ", time.gmtime()),
        level="INFO",
        message="request handled",
        method=request.method,
        path=request.path,
        status=response.status_code,
        latency_ms=latency_ms,
        request_id=g.request_id,
        component="web-server"
    )
    return response

@app.errorhandler(Exception)
def handle_exception(e):
    """Catch all unhandled exceptions and log them."""
    latency_ms = int((time.time() - g.start_time) * 1000)
    log_json(
        timestamp=time.strftime("%Y-%m-%dT%H:%M:%S.%fZ", time.gmtime()),
        level="ERROR",
        message=str(e),
        exception_type=type(e).__name__,
        traceback=str(e.__traceback__),
        latency_ms=latency_ms,
        request_id=g.request_id,
        component="web-server"
    )
    return jsonify({"error": "Internal Server Error"}), 500

@app.route("/hello")
def hello():
    return jsonify({"message": "Hello, world!"})

@app.route("/boom")
def boom():
    # Intentional error to trigger the exception handler
    1 / 0

if __name__ == "__main__":
    app.run(debug=False)

How It Works

  1. before_request: Generates a unique request_id and records the start time.
  2. after_request: Calculates latency and logs an INFO level JSON line with all relevant fields.
  3. errorhandler: Catches any unhandled exception, logs an ERROR level JSON line including the stack trace, and returns a 500 response.
  4. log_json helper: Serializes a Python dictionary to a JSON string and writes it to the logger.

Because each log line contains request_id, you can later query all logs for a particular request, even across multiple services if you propagate the same request_id downstream.

Key Takeaways

  • Logs are the breadcrumbs that guide you from a silent crash to the root cause.
  • Use structured JSON logs with context fields (user_id, request_id, component) for easy correlation.
  • Log at the right level (DEBUG, INFO, WARNING, ERROR, CRITICAL) to balance detail and volume.
  • Turn logs into metrics and alerts to react proactively.
  • Add distributed tracing spans to see the full request path and locate latency hotspots.
  • Avoid over‑logging; keep logs readable, searchable, and cost‑effective.

FAQ

What is the benefit of using structured JSON logs?

Structured JSON logs enable key/value filtering, making it faster to locate errors and correlate events across services.

How do log levels help in production?

Using DEBUG in dev and INFO/WARNING in prod keeps log volume manageable and prevents noise, ensuring operators focus on critical events.

What metrics can be derived from logs?

You can compute error_rate, latency_avg, and critical_incidents from logs to detect spikes, performance degradation, and emergency failures.