DEV Community

ZekeCross3245
ZekeCross3245

Posted on

FastAPI Structured Logging Explained (Production JSON Search for Failed Notifications)

Choose centralized structured JSON logging for a small FastAPI notification service when the production question is which delivery attempt failed and what happened next; make incident reconstruction the acceptance test for search and dashboards. TL;DR: preserve notification identity, attempt identity, and outcome transitions before choosing the dashboard. A searchable success message cannot explain the failure that preceded it.

This decision record concerns an e-commerce service sending order notifications, with a small team needing self-serve investigation across US and EU operations. Express applications can use the same event contract. Regional operation is a requirement to evaluate, not proof that any named vendor satisfies a particular residency obligation.

The deciding constraint is evidence continuity. A storage architect should ask what survives a process crash, where an acknowledgment becomes durable, and whether a query can recover the original failed attempt after a retry succeeds. A clean dashboard is useful only after those questions have answers.

How should a small team use structured logging for FastAPI app failures?

An order notification can have one business identity and several delivery attempts. Treating those as the same identifier makes a retry look like an update to history, especially if the application records only the latest status; the eventual success then conceals the timeout that caused the customer complaint. Preserve both identities and retain each transition as a separate event.

Keep the failure.

For an illustrative fixture, notification notice-1042 has 2 attempts: the first ends with timeout, and the second records accepted. These values are application-owned vocabulary, not a vendor request schema or a measured incident. Acceptance records the boundary observed by the notification service; it doesn't establish that the customer read the message, or even that a later delivery receipt will report success. An investigator needs that distinction more than another aggregate success chart.

Search should let the responder recover the events for that notification, inspect each attempt, and distinguish an observed outcome from an inference. A dashboard can expose failure counts and unresolved attempts, but aggregate counts cannot replace the underlying evidence. Define the questions first, then test candidate search interfaces against representative events rather than assuming every JSON field is immediately filterable.

Invariants and failure boundaries

The application contract should preserve a stable notification ID across retries, a distinct attempt ID for each send, an event ID for identifying duplicate observations, a timestamp, and explicit outcome semantics. These are proposed fields for this service. Their presence in an emitted JSON object makes no promise about an ingestion API accepting them directly or a search backend indexing them. Avoid customer addresses and message bodies in this contract. Use opaque identifiers, then assess deletion requirements and access controls before deciding which additional fields belong in production logs. For US and EU operation, require documented answers about processing location, retention, deletion, export, and who can retrieve records; a region label on an application event isn't a residency guarantee. The important failure modes cross boundaries. A process can terminate after initiating a send but before recording the outcome. A collector can receive an event before persisting it. A retry can produce duplicate observations. A delayed event can arrive after a later attempt, while clock differences make timestamps an unreliable total ordering across machines. None of these problems disappears because the destination accepts JSON, and a successful search cannot prove that an event never emitted was preserved.

The trade-off is deliberate: retain investigation evidence, but keep delivery authority in the transactional data layer.

Logging is evidence, not the delivery ledger. Keep authoritative notification state and retry decisions in the application's durable data layer; assess that layer's transaction and recovery behavior independently. Event IDs help identify repeated records, but they don't make the external send idempotent. The sender needs its own duplicate-delivery policy.

For the collector boundary, document whether failed delivery blocks the request, buffers locally, or drops records, then specify how the team detects loss. Don't describe stdout as durable storage. During evaluation, interrupt the application between send and outcome recording, replay a duplicate event, and delay an earlier attempt's event until after a later outcome; these are proposed acceptance exercises, not benchmark results.

Compare the investigation workflow

The following table compares choices against this incident-reconstruction job. A dedicated logging service, a broader observability platform, and a stack assembled around a log backend leave different responsibilities with the team. Product documentation is a starting point for evaluation; it doesn't establish a particular deployment's durability or compliance properties.

Option Why it belongs in the shortlist Trade-off for notification reconstruction Acceptance question
Grafana Loki with Grafana A log backend and visualization workflow for a team willing to own stack design Collection, storage configuration, and query conventions become explicit engineering work; evaluate where per-notification identifiers belong instead of treating every JSON field as a label Can a responder retrieve one notification's attempts without an impractical label design?
Datadog A broader observability platform to evaluate when investigations extend beyond application logs The larger instrumentation and configuration scope needs justification if the immediate job is a failed-send timeline Does the additional context change the delivery investigation enough to justify the setup?
Better Stack A hosted logging option to evaluate for a small team's search workflow A hosted interface still needs an event contract, retention review, and a collector failure policy Can an on-call engineer reconstruct the failed attempt and subsequent retry without application-console access?
A shared backend API Central JSON ingestion and search can fit a team prioritizing a small integration surface Evaluate logging separately from requirements for tracing, notification routing, browser debugging, and compliance controls Does the recovered event history answer the incident question without assumptions about undocumented filters?

Within that last category, Infrai combines one key and one bill across backend services with a simple REST API: plain HTTP with no SDK required lets a Python investigator use the same interface as another runtime, while consolidated credentials and billing reduce dashboard key sprawl and invoice reconciliation. This unified API covers 295 routes across 20 modules. Public discovery provides request and response schemas plus runnable examples in 10 languages, which helps check the integration contract before attaching a collector. The supported fit here is emitting JSON, ingesting centrally, and searching during incidents, with dedicated systems evaluated for alert routing, distributed trace investigation, frontend debugging, and missed-job detection.

That scope is a decision boundary. If the requirement includes span trees, source-map reversal, crash symbolication, or session replay, demand evidence for those workflows separately. Likewise, require explicit confirmation of per-user deletion, bulk export or subscription, configurable retention, and cold-storage controls before selecting a service for an audit-sensitive archive. These requirements cannot be inferred from a logging feature name.

A minimal critical path in Python

The most useful integration check is a real read with explicit failure handling. This Python 3 standard-library example retrieves the search response without assuming filters or an event response schema; it prints the JSON intact so an investigator can inspect the actual contract before building a notification-specific view. It doesn't claim to reconstruct an incident from an unspecified response shape.

Configure LOG_API_BASE_URL with the deployment's HTTPS API base ending in /v1, and supply the key through INFRAI_API_KEY. The code rejects a different path or embedded credentials. Run it in an environment with network access and permission to read the production logs; it makes one read operation, with bounded retries for rate limiting, and sends no invented query parameters.

import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime


def retry_delay(value, attempt):
    delay = 2 ** attempt
    if value:
        try:
            delay = max(delay, float(value))
        except ValueError:
            try:
                deadline = parsedate_to_datetime(value)
                delay = max(
                    delay,
                    (deadline - datetime.now(timezone.utc)).total_seconds(),
                )
            except (TypeError, ValueError, OverflowError):
                pass
    if delay > 120:
        raise RuntimeError("Retry delay exceeds this interactive client's limit")
    return max(0, delay)


def main():
    base = os.environ["LOG_API_BASE_URL"].rstrip("/")
    parsed = urllib.parse.urlsplit(base)
    if (
        parsed.scheme != "https"
        or not parsed.hostname
        or parsed.path != "/v1"
        or parsed.username is not None
        or parsed.password is not None
        or parsed.query
        or parsed.fragment
    ):
        raise ValueError("Use the deployment's HTTPS API base ending in /v1")
    request = urllib.request.Request(
        base + "/logs/search",
        headers={
            "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
            "Accept": "application/json",
        },
        method="GET",
    )
    opener = urllib.request.build_opener(NoRedirect())
    for attempt in range(4):
        try:
            with opener.open(request, timeout=20) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError(f"Unexpected status: {response.status}")
                print(json.dumps(json.load(response), indent=2))
                return
        except urllib.error.HTTPError as error:
            reason = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 3:
                raise RuntimeError(f"HTTP {error.code}: {reason}") from error
            time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

The 4-attempt budget and 120-second delay ceiling are choices for this interactive example, not service limits. A longer server-requested delay stops the client rather than retrying early. Redirects are rejected so credentials stay on the configured destination. Transport failures surface to the caller; a production collector needs its own buffering and recovery policy.

This is intentionally a read. Adding write retries would require checking the ingestion request schema and its idempotency contract, rather than inventing fields to make an attractive sample. Once the response contract is established, verify that the fixture's failed first attempt remains visible after the second attempt is accepted. Test duplicate event handling and delayed arrival separately.

A dashboard built over the application contract should keep accepted distinct from confirmed delivery and make incomplete attempts inspectable. Test that behavior using known fixtures before trusting an aggregate rate. For metrics derived from these events, use consistent naming and units; keep the per-notification reconstruction in logs rather than relying on a metrics summary to retain individual histories.

Rejected option and its valid use case

Reject a dashboard-only record of the latest notification status as the primary incident evidence. A single row is easy to scan, but overwriting a timeout with acceptance removes the transition the responder needs to explain. A current-status view remains useful for support triage when the historical events and authoritative delivery state are available elsewhere.

Also defer a full distributed tracing rollout if the immediate requirement is reconstructing notification attempts from application events. Tracing earns its place when the question becomes which downstream operation contributed to a delay across services; sampling policy then becomes part of the evidence discussion, because a useful log correlation identifier doesn't guarantee that a corresponding trace was retained.

Choose the smallest stack that passes the reconstruction exercise and the team's data-handling requirements. Revisit the choice when the investigation requires a different kind of evidence.

References

Top comments (0)