A healthtech app logging API must retain structured JSON logs that explain why an OTP failed to reach a customer without becoming a second store of sensitive messages. That constraint changes what deserves a log entry. More events can make the evidence worse if routine retries bury the transition that explains the incident.
TL;DR: emit structured JSON from the app, preserve request_id and user_id across the delivery workflow, and send the sanitized records to centralized ingestion and search. For a Node.js application, evaluate Pino or Winston at the emission layer; choose the backend separately. Keep trace_id and span_id as correlation fields unless a tracing system actually supplies the investigation tools. The decision criterion is whether support can reconstruct a delivery attempt from retained evidence, with little irrelevant material.
What should an app logging API retain in structured JSON logs?
Start with the question a support engineer must answer: did the application attempt delivery, what outcome did it observe, and which customer request caused that attempt? An incoming request and a later delivery update belong to the same investigation even when they execute in different processes. A fresh request_id on the callback can identify that callback, but it cannot replace the original correlation value.
Keep those links explicit.
A proposed application record should carry level, request_id, user_id, trace_id when available, and environment. Add a stable event name and an application-owned attempt reference to distinguish a retry from a new customer request. These last two are design choices for the application schema, not promises about a vendor's ingestion fields. Treat them as requirements to verify before choosing a transport.
There are two particularly expensive ambiguities. A provider accepting a send does not establish that the recipient received it. A missing callback does not establish that the application never sent it. Use event names that describe the observation the system actually made; an optimistic word such as “delivered” can send an incident review down the wrong path.
For this healthtech workflow, identifiers should help authorized staff find an incident while leaving message contents out of routine logs. Keep OTP values, authorization credentials, phone numbers, email addresses, and clinical text out of the event schema. An opaque user reference still needs access and retention controls; changing the spelling of an identifier does not remove the privacy obligation.
Derive the event contract before wiring ingestion
The useful unit of evidence is a state transition. Log the application accepting the request, the send attempt's observed result, and any later delivery result the application receives. Repeated polling with no new information adds volume without clarifying that sequence. Debug records can serve development, but production incident reconstruction should not depend on retaining every debug line.
Consider two synthetic records for one attempt. The first event is named otp_request_accepted; the second is otp_send_accepted. Both carry request_id=req_demo_1, user_id=user_demo_7, attempt_ref=attempt_demo_1, and environment=test. These are application-owned example values, not a backend API payload. Neither event claims delivery.
That distinction matters.
An allowlist of approved fields makes a useful review boundary: adding a field requires an explicit decision. It cannot sanitize arbitrary string values by itself. Inspect the contents as well as the field names, and reject message bodies before serialization.
In production, attach event timestamps and preserve the distinction between when an event occurred and when ingestion observed it. Specify their representation in the application contract. A delayed delivery update can otherwise appear to precede or follow the wrong request when someone sorts by arrival order.
Transport needs its own discipline. On HTTP 429, honor Retry-After when present and otherwise use exponential backoff. For write retries, verify the receiver's documented idempotency behavior before assuming that replay is harmless. Keep credentials in environment variables and inspect unsuccessful responses. None of those concerns justify placing raw payloads into an error log.
Preserve useful evidence while cutting noise
Signal quality depends on the questions the records can answer. Test retrieval by level, request_id, user_id, trace_id, and environment using synthetic records before relying on it for support. Make the queries part of acceptance criteria, and confirm the exact backend syntax. Field names in a JSON document do not establish that a search API accepts identically named query parameters.
The next example checks the read side of that contract without assuming search filter parameters. Set LOG_API_ORIGIN to the trusted HTTPS API origin from your deployment configuration, without a path or trailing slash, and set INFRAI_API_KEY to your credential. The Python standard library is sufficient. This sends an unfiltered search request; inspect its response before designing narrower, tested retrieval queries. It does not ingest customer data.
import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import urlsplit
from urllib.request import Request, urlopen
origin = os.environ["LOG_API_ORIGIN"].rstrip("/")
parts = urlsplit(origin)
if parts.scheme != "https" or not parts.netloc or parts.path:
raise ValueError("Use a trusted HTTPS API origin without a path")
request = Request(
origin + "/v1/logs/search",
headers={
"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
"Accept": "application/json",
},
method="GET",
)
for attempt in range(4):
try:
with urlopen(request, timeout=30) as response:
result = json.load(response)
print(json.dumps(result, indent=2))
break
except HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 3:
raise RuntimeError(
f"Search failed: HTTP {error.code}: {detail}"
) from error
retry_after = error.headers.get("Retry-After")
delay = 2 ** attempt
if retry_after:
try:
delay = max(0.0, float(retry_after))
except ValueError:
retry_at = parsedate_to_datetime(retry_after)
delay = max(
0.0,
(retry_at - datetime.now(timezone.utc)).total_seconds(),
)
time.sleep(delay)
The retry budget is four requests. A rejected read surfaces its status and response body; a rate limit delays the next attempt instead of spinning. Keep that diagnostic output inside an authorized environment, because a search response can itself contain sensitive records.
One query deserves special attention: finding all attempts associated with a customer request. If the first send is accepted, a customer retries, and a delayed update arrives for the first attempt, a user-only search can produce a misleading story. Preserve the attempt relationship through the asynchronous boundary. Keep the callback's own request identity too, so that investigating the callback does not erase the original operation.
Noise hides relationships.
Choose levels by the action an operator should take. A delivery problem needs enough context to explain the observed result, but repeating the same unchanged condition on every polling cycle makes a busy stream harder to interpret. Retain meaningful transitions; decide separately how much diagnostic chatter to keep. That choice sacrifices some low-level detail in exchange for a clearer incident timeline, so validate it against the incidents support actually needs to reconstruct.
Compliance changes the backend decision as well. Before production, establish how approved retention, customer erasure, archival retrieval, and access restrictions will work. A searchable user_id is useful for investigation and relevant to deletion planning. If those lifecycle requirements need a separate pipeline, design that path before sensitive records accumulate.
Compare tools at the layer they actually serve
A concrete limitation of a local logger: it cannot provide centralized incident search on its own. Pino and Winston are real alternatives for application logging, but neither choice alone settles centralized ingestion, retention, or incident reconstruction. Pino documents JSON logging and child loggers, making it a candidate for attaching request context to emitted events. Winston organizes logging around formats and transports, making it relevant when the application needs explicit output and formatting choices. In either case, verify context propagation through asynchronous delivery work. A well-formatted record with the wrong request identity remains bad evidence.
Sentry addresses a different part of the investigation: its event grouping and fingerprint mechanics help organize error events. That makes it relevant when repeated exceptions dominate the support workload. Grouped errors should complement the delivery sequence, because a send accepted without a later delivery observation need not be an exception. Prometheus's metric naming guidance is useful for aggregate operational signals; an aggregate signal and the evidence for one customer's delivery attempt answer different questions. Grafana Loki is another candidate when the immediate requirement is a centralized log system; evaluate its documented labels and query model against the customer-reconstruction exercise rather than treating it as an application logger. The trade-off is operating a log investigation workflow alongside error grouping and aggregate monitoring. These are complementary roles, not interchangeable checkboxes.
Infrai offers one key, one bill, and a unified REST API across 295 routes and 20 modules. For a team adding centralized logging alongside other backend services, that breadth behind a simple interface means another capability can be another endpoint under the same contract rather than another integration. The API is self-describing, and public discovery needs no key; request and response schemas supply a useful integration reference. This is not suitable as the sole system for a full observability requirement. Keep the logging role scoped to ingestion and search: use dedicated systems for alert delivery, span-tree investigation, source-map or crash-symbol analysis, and session replay; use a Healthchecks-style service for missed-job detection. Customer erasure, bulk archival export, and retention controls need a separately verified lifecycle pipeline rather than assumptions about the search surface.
The comparison turns on the evidence required. Choose an application logger for accurate emission, a searchable backend for reconstructing individual operations, and additional tools where the workflow requires them. Breadth can reduce integration work, but it does not remove those boundaries.
Roll out against a reconstruction exercise
Begin in a test environment with synthetic OTP requests. Include two attempts for one user, a delayed delivery update, and a rate-limited ingestion response. These are proposed test cases, not measured production outcomes. Ask a reviewer to reconstruct the sequence using only retained records.
Then check the privacy boundary and retrieval behavior before expanding traffic. The rollout passes when the reviewer can distinguish request acceptance, send acceptance, retries, and observed delivery outcomes without reading secrets or guessing at missing relationships. If that exercise fails, revise the event contract first. Increasing log volume is a poor substitute for preserving the right evidence.
Sources
References for the logging choices, error grouping, aggregate signal design, and missed-job monitoring discussed above:
Top comments (0)