Choose centralized structured JSON app logging when the question is which agent attempt consumed time or incurred cost. Choose a broader observability workflow when the investigation needs a trace tree, alert routing, or proof that an expected job ran. For a small developer tools SaaS, the deciding factor is signal quality: can the records explain one slow loop without burying the answer in successful request noise?
TL;DR: record attempts separately, time the whole loop, and publish one completion summary with a known-cost subtotal and an explicit count of missing cost observations. Evaluate search and the dashboard against that contract before picking a service. A basic logging API can fit this job; it cannot settle every operational requirement surrounding it.
Consider an agent that drafts a notification and requests email or SMS delivery. A successful model response is one milestone. Provider acceptance is another. Recipient delivery requires its own evidence. If the notification carries an OTP, collapsing those milestones into a single success counter produces a particularly unhelpful dashboard: the application can look healthy while the user's actual outcome remains unknown.
This architecture decision record makes three decisions: define the evidence boundary, choose the destination against that boundary, and instrument the critical path. The examples are synthetic Python programs using only the standard library. They illustrate an application event contract, including for a Node.js service; they don't prescribe changing the service's runtime or assert any vendor ingestion schema.
1. What should a centralized JSON app logging service record for small SaaS?
A loop needs a stable identifier. Each attempt needs a separate identifier, including retries, and every emitted summary needs an identity that a downstream consumer can use to recognize duplicates. These are application invariants. Centralizing records does not create them automatically.
Keep the evidence.
For this design, attempt records carry observed status, elapsed time, and cost when available. A completion record carries the elapsed time of the whole loop and a subtotal of known costs. Unknown cost remains unknown. The subtotal is useful for investigation, but it becomes misleading if a dashboard labels it as the complete total without showing coverage. Retry delays belong in the loop timer even if they don't appear in a provider's reported call latency; recording both measurements preserves the distinction between service time and time the user spent waiting.
Start with an allowlist at the serialization boundary. For notification work, prompts, recipient addresses, message bodies, and OTP values aren't necessary to answer this timing question. Logging an entire request object makes accidental collection far easier than logging a small, explicit event. Even a correlation identifier needs a documented purpose and retention policy; an allowlist is a collection control, not a GDPR compliance certificate.
Run this first program to check the proposed contract. It accepts the example record and rejects an added OTP field before serialization.
import json
ALLOWED = {
"event", "loop_id", "attempt_id", "operation", "status",
"duration_ms", "cost_usd",
}
def encode_event(event):
extra = set(event) - ALLOWED
if extra:
raise ValueError(f"Unexpected fields: {sorted(extra)}")
return json.dumps(event, allow_nan=False)
event = {
"event": "agent_attempt",
"loop_id": "synthetic-loop-1",
"attempt_id": "attempt-1",
"operation": "draft_notification",
"status": "completed",
"duration_ms": 240,
"cost_usd": None,
}
print(encode_event(event))
try:
encode_event({**event, "otp": "synthetic-secret"})
except ValueError:
print("Unexpected field rejected.")
else:
raise AssertionError("The allowlist accepted an unexpected field")
The acceptance criterion is deliberately small: the extra field must fail. A production exporter also needs value validation and a policy for recording rejected telemetry without blocking notification delivery. The example is an executable field-boundary check, not a complete exporter.
A missing completion record has a different meaning from a failed completion. The process might have stopped, the loop might still be running, or telemetry might not have arrived. Maintain an independent expectation of started work and use heartbeat monitoring for scheduled work whose absence matters. Search can retrieve an existing event; absence alone doesn't establish why an event is missing.
2. Choose the destination by the evidence it preserves
Use one comparison table, then test the same synthetic loop against every candidate. The entries below identify concrete evaluation paths rather than declare a benchmark winner. Search convenience matters, but a convenient interface cannot repair an event stream that merges retries or silently drops unknown costs.
| Option | Useful fit to evaluate | Trade-off and acceptance question |
|---|---|---|
| Grafana Loki | A log-oriented investigation using LogQL and a deliberate label model. | Decide which dimensions belong in labels and which stay in event content. Can the investigator find one loop without making every loop identifier a label? |
| Datadog | A workflow that considers logs alongside application performance monitoring. | Broader investigation requires corresponding instrumentation and configuration. Does the trial connect the actual agent operations, rather than merely display their log messages? |
| Better Stack | A centralized log workflow evaluated by the engineer investigating agent and notification events. | Run the exact lookup and aggregation needed for the incident. Verify the selected service configuration against notification and processing-location requirements separately. |
| Infrai | A plain REST API with a single key and unified billing for logs, model calls, and notification requests; any HTTP-capable runtime can call it without an SDK to install or update. Structured JSON ingestion, searchable fields, and a basic dashboard fit the loop investigation. Sharing one key and one bill across these backend capabilities reduces separate credential handling and invoice reconciliation. Public, self-describing discovery supplies request and response schemas for checking the exporter boundary. | A practical fit for centralized app logs and simple search. Treat alert routing, distributed trace investigation, heartbeat checks, per-user deletion, and bulk export requirements as separate acceptance boundaries before selecting this scope. |
The comparison is about investigative depth and integration work. If the requirement is finding an attempt and inspecting its fields, a narrow logging service deserves consideration. If the requirement is navigating dependencies across services, evaluate the tracing workflow explicitly. A trace_id or span_id in a log supports correlation; it doesn't by itself provide a span tree. The REST option also puts 295 routes across 20 modules under one key and one bill. For an agent that combines model calls, notification requests, and logging, that reduces the number of separate credentials and invoices the team must manage. This is an integration advantage; it does not establish the quality of the events being collected or replace a check of the required investigation workflow.
Test the distinction.
These boundaries also explain where a logging-only decision ends. Error symbolication, source-map processing, crash-dump analysis, and session replay need their own evaluation. Don't infer them from the presence of searchable application events. Feature-flag governance is another decision: audit history, evaluation statistics, dependency behavior, deletion recovery, and client refresh requirements belong in that review rather than in the agent latency dashboard.
For EU/US deployment, ask for evidence about processing location, retention, deletion, and export before sending production records. A regional-looking hostname is insufficient. If the workflow requires deleting one user's logs or subscribing a downstream archive to the entire stream, make those explicit selection criteria; basic ingestion and search do not establish either capability. Confirm retention and cold-storage controls with the destination before treating them as policy enforcement mechanisms.
Avoid guessing query parameters, too. The event fields in this article are application fields, not a promise about a service's HTTP filters. Inspect documented request schemas, then verify that the search response preserves the evidence required for the calculation.
Inspect the search boundary before building the dashboard
After configuring ingestion with the documented schema, use this read-only query to inspect the actual response. Set INFRAI_API_ORIGIN to the documented HTTPS API origin without a path, and set INFRAI_API_KEY in the environment. The program sends no speculative filters and assumes no response envelope. It retries rate limits with exponential backoff, honoring either form of Retry-After, and surfaces other HTTP errors. This is a transport check; the local simulations below establish what the returned records need to explain.
import email.utils
import os
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
from urllib.parse import urlsplit
origin = os.environ["INFRAI_API_ORIGIN"].rstrip("/")
parsed = urlsplit(origin)
if (parsed.scheme != "https" or not parsed.netloc or parsed.path
or parsed.query or parsed.fragment or parsed.username):
raise ValueError("Provide the documented HTTPS origin without a path")
request = urllib.request.Request(
origin + "/v1/logs/search",
headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
method="GET",
)
for attempt in range(4):
try:
with urllib.request.urlopen(request, timeout=30) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"Unexpected HTTP status: {response.status}")
print(response.read().decode("utf-8"))
break
except urllib.error.HTTPError as error:
if error.code != 429 or attempt == 3:
reason = error.read().decode("utf-8", errors="replace")
raise RuntimeError(f"HTTP {error.code}: {reason}") from error
delay = float(2 ** attempt)
retry_after = error.headers.get("Retry-After")
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
try:
deadline = email.utils.parsedate_to_datetime(retry_after)
if deadline.tzinfo is None:
deadline = deadline.replace(tzinfo=timezone.utc)
delay = max(
delay,
(deadline - datetime.now(timezone.utc)).total_seconds(),
)
except (TypeError, ValueError, OverflowError):
pass
error.close()
time.sleep(delay)
Inspect before aggregating.
3. Put the timer around the critical path
This second program simulates a retry followed by a successful draft and a delivery request. Its delays and cost inputs are invented test data, not measured service behavior or current prices. Save the block as a Python file and run it. It emits three attempt records and one completion summary, then checks the accounting invariants.
import json
import time
from decimal import Decimal
loop_id = "synthetic-loop-1"
scenario = [
("draft_notification", "retryable", 0.004, Decimal("0.001")),
("draft_notification", "completed", 0.006, Decimal("0.002")),
("request_delivery", "accepted", 0.003, None),
]
started = time.perf_counter()
known_cost = Decimal("0")
missing_cost = 0
attempts = []
for index, (operation, status, delay, cost) in enumerate(scenario, 1):
attempt_started = time.perf_counter()
time.sleep(delay)
duration_ms = (time.perf_counter() - attempt_started) * 1000
if cost is None:
missing_cost += 1
else:
known_cost += cost
event = {
"event": "agent_attempt",
"loop_id": loop_id,
"attempt_id": f"attempt-{index}",
"operation": operation,
"status": status,
"duration_ms": round(duration_ms, 3),
"cost_usd": None if cost is None else str(cost),
}
attempts.append(event)
print(json.dumps(event, allow_nan=False))
summary = {
"event": "agent_loop_completed",
"summary_id": f"{loop_id}:completed",
"loop_id": loop_id,
"status": "delivery_requested",
"duration_ms": round((time.perf_counter() - started) * 1000, 3),
"known_cost_usd": str(known_cost),
"missing_cost_attempts": missing_cost,
"attempt_count": len(attempts),
}
print(json.dumps(summary, allow_nan=False))
assert summary["attempt_count"] == 3
assert Decimal(summary["known_cost_usd"]) == Decimal("0.003")
assert summary["missing_cost_attempts"] == 1
assert len({event["attempt_id"] for event in attempts}) == 3
Expect a known-cost subtotal of 0.003 and one attempt with unknown cost. Elapsed times vary by execution. The result says delivery_requested because the program has no recipient delivery event. That distinction should survive ingestion, search, and the dashboard label.
Count costs once.
For the first dashboard, calculate loop latency from completion summaries and display attempt count beside it. Use attempt records to explain retries. Aggregate either the attempt costs or their corresponding summary subtotals for a given view; adding both counts the same work twice. Display missing-cost counts beside known-cost subtotals, and count unfinished loops separately so a completion-only latency chart doesn't become the entire health story.
The second program extends the first program's schema with completion-specific fields. Give each event type its own allowlist before combining them. In a real loop, record terminal errors when execution can still emit telemetry, persist attempt identities across retries, and deduplicate summaries by their stable identity before aggregation. A log collector receiving the same summary twice should not make the agent appear to have completed two loops.
Provider metadata and application timing answer related questions at different boundaries. Preserve both when available, with names that identify their origin. An agent loop can include orchestration, retry waiting, and delivery submission; replacing that timer with a model call's reported latency loses those components. More records won't recover a boundary that was never measured.
Rejected option: collecting every payload as diagnostic insurance
Reject full-payload logging as the default for this notification agent. The useful signal is the relationship between attempt identity, observed outcome, elapsed time, and cost coverage. Adding prompts and message bodies increases collection exposure while making the timing question harder to scan. OTP values are particularly poor diagnostic baggage.
There is a valid use case for richer diagnostic capture: a controlled reproduction where content is needed to explain model behavior. Use synthetic inputs, a separate access boundary, and a bounded retention policy. Keep that investigation out of the normal operational stream, then decide whether any additional field earns a permanent place in the event contract.
The resulting decision is intentionally limited. Select a destination that preserves these records and answers the loop lookup reliably; select additional operational tooling when the requirement crosses into tracing, alert delivery, scheduled-job assurance, or compliance lifecycle controls. Judge the signal by whether an engineer can distinguish a retry from a new loop and an accepted notification from a delivered one.
References
- OpenTelemetry, logs signal concepts: https://opentelemetry.io/docs/concepts/signals/logs/
- Grafana Loki, LogQL: https://grafana.com/docs/loki/latest/query/
- Grafana Loki, label guidance: https://grafana.com/docs/loki/latest/get-started/labels/
- Datadog, connecting logs and traces: https://docs.datadoghq.com/tracing/other_telemetry/connect_logs_and_traces/
- Better Stack, logging documentation: https://betterstack.com/docs/logs/
- Healthchecks, monitoring documentation: https://healthchecks.io/docs/
- Python, monotonic performance counter: https://docs.python.org/3/library/time.html#time.perf_counter
Top comments (0)