DEV Community

tanmay kuamr chaurasia
tanmay kuamr chaurasia

Posted on

Stop Logging Free Text: Production Logging Best Practices

Getting paged at 3 AM is painful on its own. It is ten times worse when you open your log aggregator and see unhelpful lines like this:

2026-03-30 03:14:02 ERROR Failed to process order for user

Which user? Which request initiated this order? Which downstream microservice timed out?

Without context, debugging production outages turns into an agonizing guessing game where you manually grep through unstructured text strings across dozens of server instances.

The root cause of poor observability is rarely a lack of logging tools. It is usually a lack of intentional logging standards. Here is how to fix your logging strategy so you can diagnose production bugs in minutes instead of hours.

Enforce Structured JSON Logs

Stop printing raw sentences formatted with string interpolation. Human-readable logs work well in local development, but log management platforms need machine-readable structures to index, filter, and query data efficiently at scale.

Establish a strict schema across all your services. If your authorization service logs user_id while your payment service logs userId, you will never be able to run a unified query across your system.

Here is an example of implementing a consistent JSON logger in Python using standard libraries:

import logging
import json
from datetime import datetime, timezone

class JSONFormatter(logging.Formatter):
    def format(self, record):
        log_object = {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "level": record.levelname,
            "service": "payment-service",
            "message": record.getMessage(),
            "requestId": getattr(record, "request_id", None),
            "userId": getattr(record, "user_id", None),
        }

        if record.exc_info:
            log_object["exception"] = self.formatException(record.exc_info)

        return json.dumps(log_object)

# Logger setup
logger = logging.getLogger("app_logger")
handler = logging.StreamHandler()
handler.setFormatter(JSONFormatter())
logger.addHandler(handler)
logger.setLevel(logging.INFO)
Enter fullscreen mode Exit fullscreen mode

Propagate Request and Trace IDs

A single user transaction often spans an API gateway, a backend service, a database call, and an external payment provider. When an error occurs halfway through, you must be able to trace that exact execution path.

Generate a unique request ID at your network boundary (such as the API Gateway) and forward it through every internal HTTP header and background task payload.

import requests
import extra_context # hypothetical context container

def call_inventory_service(item_id: str, request_id: str):
    headers = {"X-Request-ID": request_id}

    # Pass context to internal logger call
    logger.info(
        f"Checking inventory for item {item_id}",
        extra={"request_id": request_id}
    )

    response = requests.get(
        f"http://inventory-service/items/{item_id}",
        headers=headers
    )
    return response.json()
Enter fullscreen mode Exit fullscreen mode

By passing the X-Request-ID header across every boundary, one single ID tells the entire end-to-end story across your distributed architecture.

Standardize Severity Levels as a Team

A major cause of log noise is arbitrary severity selection. Half of your "noisy log" problems exist because your engineering team hasn't agreed on what levels actually mean.

Define clear boundaries for your codebase:

  • ERROR: Actionable failures requiring immediate human attention or alerting (e.g., unhandled exceptions, database connection failures).
  • WARN: Unexpected conditions that were handled gracefully but might indicate a growing issue (e.g., degraded third-party API response times, fallback paths triggered).
  • INFO: Major state changes during normal execution (e.g., application startup, successful checkout completion).

Keep Production at INFO Level by Default

Running production environments on DEBUG level quietly creates a massive ingestion bill for data you will rarely read. DEBUG logs should be reserved for local development or temporary, targeted dynamic verbosity toggles during active incident investigations.

If you genuinely need fine-grained execution metrics at scale, sample your logs rather than ingesting 100% of debug events.

The most resilient engineering teams do not log more data. They log with intention, ensuring every log line earns its place when an outage happens.

About me

Tanmay builds AI agents and automation for businesses and is open to freelance projects. Connect with Tanmay on LinkedIn to discuss backend engineering, DevOps, or workflow automation.

Top comments (0)