The logging bill starts with how many events an e-commerce agent emits, how large those events are, and how long they remain searchable; model execution cost is a separate quantity that those events should help explain. For a small Node.js SaaS, start with structured JSON summaries that preserve latency, attributed cost, release identity, and the outcome of the loop. Keep customer content out of the stream.
Short answer: log enough to compare a candidate release with the release you can restore, using consistent request IDs and safe tenant identifiers, then budget diagnostic detail separately. Rollback safety depends on retaining comparable evidence across both releases, not on retaining every prompt.
Consider a sizing exercise, not a production measurement: assume 10,000 loops, 40 events per loop, and 2,000 bytes per event. That produces 800,000,000 bytes before indexing or replication. Under those assumptions, verbose events dominate the raw byte budget. Reducing the assumed event count to four produces 80,000,000 bytes, but only if those four events still describe the decisions needed for investigation. This arithmetic predicts neither a vendor invoice nor measured savings. It exposes which design choice deserves scrutiny first.
Bytes need reasons.
What should structured JSON application logging retain for a small Node.js SaaS?
Structured application logging means writing events with consistent named fields rather than forcing operators to extract meaning from changing sentences. A useful baseline is timestamp, level, message, and request_id, plus user_id or tenant_id where justified; include trace_id and span_id when a tracing system supplies them. JSON makes those fields explicit. It doesn't decide which values are safe to keep.
For a commerce agent, propose an application schema that also records a release identifier, a loop identifier, elapsed milliseconds, outcome, and the cost attributed to the loop. These are application fields, not a claim about any ingestion API's request schema. Keep the correlation identifier stable across the loop; generating a fresh request ID on every log line destroys the link you intended to preserve. A retry needs its own attempt identity while retaining the parent loop identity, otherwise one retried action can masquerade as several independent purchases.
Use info for normal completion summaries, warn for recoverable events that merit investigation, and error for failed operations; reserve debug for detail with a specific diagnostic purpose. Those are proposed conventions. A recovered retry should not automatically become a failed-loop count, and an error line does not prove that a customer-visible action failed.
Cost has a similar accounting trap. A per-call amount and a loop total cannot both be summed into the same aggregate without double counting. Choose one aggregation level, document it, and preserve missing cost as unknown rather than substituting zero. Elapsed time belongs to a defined boundary too: total loop duration and the sum of call durations answer different questions when work overlaps. Consider a failed attempt followed by a successful retry: the loop outcome is successful, but the earlier attempt still consumed time and may carry attributed cost. Counting only the final success hides that work; adding every attempt amount to an already aggregated loop amount counts it twice. Retaining the aggregation boundary is therefore more valuable than retaining another paragraph of debug text, especially when the candidate and restored releases use different retry policies.
Zero isn't unknown.
The rollback comparison should use equivalent traffic windows and the same event definition for both releases. Compare failure outcomes, latency distributions, and attributed cost before making a release decision; the numerical thresholds belong to the application's operating requirements, since an acceptable delay for an optional recommendation may be unacceptable on a checkout path.
Logs provide evidence. They do not undo a completed external action.
Move the volume term before choosing the destination
The four-event assumption above is a budget to test, not a universal prescription. Keep a loop completion summary and add decision events where a tool action or retry changes the explanation of the outcome. If a workflow needs more events to distinguish a failed decision from a failed external action, spend the bytes. Dropping evidence merely to satisfy an arbitrary event quota defeats the purpose.
| Record choice | What it preserves | What it costs or loses |
|---|---|---|
| One completion summary per loop | Comparable release outcome, elapsed time, attributed cost | Cannot reconstruct every intermediate decision |
| Selected step and retry events | Attempt boundaries and action outcomes | More events, plus careful deduplication during analysis |
| Full prompt and tool payload capture | Detailed content for investigation | Larger records and a much harder privacy obligation |
| Short-lived debug detail | Temporary visibility into a specific question | Detail may be gone when a delayed report arrives |
Prefer allowlisting fields at write time. An email address disguised as user_id remains personal data, and an opaque identifier can still link to a person; use a tenant identifier only when its investigative value justifies that linkage. Exclude authorization headers, cookies, payment details, raw prompts, and unrestricted exception messages. OWASP's logging guidance is a useful basis for that decision.
Redaction after ingestion is a poor default because the sensitive value has already crossed the logging boundary. Retention expiry also doesn't establish a per-user erasure workflow. Before adopting a destination, require evidence for the deletion, export, and retention controls your data actually needs; if that evidence is absent, reduce the data collected or choose a destination with the necessary controls.
This is a storage decision disguised as a logging decision: an event that nobody can safely delete is expensive even when its serialized form is small.
Discard content first.
Compare destinations against the evidence you need
The useful comparison is how a destination supports the required investigation and lifecycle, rather than how many dashboard screenshots it can produce. Better Stack, Datadog, and Grafana Loki are real alternatives worth evaluating, but their documentation should be treated as acceptance-test inputs rather than proof that a particular deployment meets your needs.
| Option | Evaluation focus for this workload | Boundary to test before committing |
|---|---|---|
| Better Stack | Hosted log search and the operator workflow around a failed loop | Verify retention, export, and identifier handling for the selected service configuration |
| Datadog | Log management alongside tracing when a rollback needs cross-service context | Verify that the required correlation and lifecycle controls are configured for this application |
| Grafana Loki | Label-oriented log organization within a Grafana environment | Decide which fields belong in labels and which stay in event content; validate the resulting searches |
| Shared backend API | Credential and billing consolidation across the commerce application's backend services | Require separate evidence for trace-tree analysis, alert delivery, and privacy lifecycle requirements |
Infrai fits the last row when one API key and one bill for every backend service would remove separate credentials and invoice reconciliation from the team's work; its specified per-call cost and latency metadata also supports attributing backend calls to an agent loop. That metadata still needs an application-defined aggregation rule before it becomes a loop total.
Choose structured logs for event search and debugging. If rollback approval requires a distributed span tree, add a tracing system; copying trace_id and span_id into JSON provides correlation fields, not that tree. Likewise, validate alerting and scheduled-job monitoring independently: an absent completion event cannot report its own absence. Keep source-map processing, crash symbolication, and session replay out of the assumed logging contract unless separately established.
The trade-off is explicit. A compact event stream can be enough for a small service, while a workflow with strict erasure, export, or distributed investigation requirements needs more than a convenient ingestion interface.
Test the boundary.
A minimal event boundary, with deliberate omissions
The production service is Node.js; the Python below is a standalone reference emitter for the JSON contract, so the event-policy example stays independent of a JavaScript logging library or a vendor transport. Run it with Python 3. It writes one synthetic completion event to standard output, with illustrative latency and cost inputs rather than a measured agent run. The allowlist drops the synthetic email field before serialization.
import json
from datetime import datetime, timezone
from decimal import Decimal
ALLOWED = {
"request_id", "tenant_id", "loop_id", "release_id",
"duration_ms", "cost_usd", "outcome", "trace_id", "span_id",
}
def emit_completion(fields):
safe = {key: value for key, value in fields.items() if key in ALLOWED}
if safe.get("outcome") not in {"ok", "failed"}:
raise ValueError("outcome must be ok or failed")
for name in ("request_id", "loop_id", "release_id"):
if not isinstance(safe.get(name), str) or not safe[name]:
raise ValueError(f"{name} must be a nonempty string")
duration = safe.get("duration_ms")
if type(duration) is not int or duration < 0:
raise ValueError("duration_ms must be a nonnegative integer")
cost = safe.get("cost_usd")
if cost is not None:
amount = Decimal(str(cost))
if not amount.is_finite() or amount < 0:
raise ValueError("cost_usd must be finite and nonnegative")
safe["cost_usd"] = str(amount)
event = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"level": "info" if safe["outcome"] == "ok" else "error",
"message": "agent_loop_completed",
**safe,
}
print(json.dumps(event, allow_nan=False))
emit_completion({
"request_id": "synthetic-request-a",
"tenant_id": "synthetic-tenant-a",
"loop_id": "synthetic-loop-a",
"release_id": "candidate-a",
"duration_ms": 1250,
"cost_usd": "0.003",
"outcome": "ok",
"customer_email": "synthetic@example.invalid",
})
The cost is a decimal string here to preserve the supplied decimal representation; any downstream numeric aggregation must parse it deliberately. Unknown cost remains unknown. The field-name allowlist is only one boundary: application code must also ensure that approved string fields contain controlled identifiers rather than customer content. This example neither ingests records nor promises durable delivery, so the deployment still needs a tested transport and a policy for what happens when that transport cannot accept an event.
For a separate, minimal read of the log destination, this Python 3 client calls the verified search route without inventing filter parameters. Set INFRAI_ORIGIN to the service's HTTPS API origin and INFRAI_API_KEY to your credential in the environment before running it. It checks status, bounds retries, honors Retry-After when present, and prints only the response size rather than potentially sensitive log content. A successful response establishes that this read succeeded; it does not establish any retention or durability guarantee.
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["INFRAI_ORIGIN"].rstrip("/")
parts = urlsplit(origin)
if parts.scheme != "https" or not parts.netloc or parts.path:
raise ValueError("INFRAI_ORIGIN must be an HTTPS origin without a path")
key = os.environ["INFRAI_API_KEY"]
for attempt in range(5):
request = Request(
origin + "/v1/logs/search",
headers={"Authorization": f"Bearer {key}"},
method="GET",
)
try:
with urlopen(request, timeout=10) as response:
if response.status != 200:
raise RuntimeError(f"Unexpected HTTP status {response.status}")
print("Search response bytes:", len(response.read()))
break
except HTTPError as error:
if error.code != 429 or attempt == 4:
reason = error.read().decode("utf-8", errors="replace")
raise RuntimeError(f"HTTP {error.code}: {reason}") from error
retry_after = error.headers.get("Retry-After")
delay = float(2 ** attempt)
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
retry_at = parsedate_to_datetime(retry_after)
delay = max(
delay,
(retry_at - datetime.now(timezone.utc)).total_seconds(),
)
error.close()
time.sleep(delay)
Keep compact completion events for an explicitly chosen comparison window spanning the current release and its rollback target. Keep diagnostic detail only as long as its investigative purpose requires, and verify deletion behavior before relying on expiry. Do not assume a bulk export will be available later; if a governed archive is required, design that destination before emitting the data.
Deliberately stop keeping full prompts, customer addresses, and routine duplicate debug records in this stream. The cost is real: a later complaint may be impossible to reconstruct word for word, and a summary may identify the failing step without explaining the model's reasoning. Accept that limit only where operational summaries are sufficient. Where content is necessary evidence, give it a separately justified collection and deletion policy rather than quietly turning application logs into a permanent customer-content archive.
References
OWASP's Logging Cheat Sheet supports the sensitive-data boundary. The product documentation below provides starting points for validating the destination choices; none substitutes for testing the selected configuration against the application's retention and rollback requirements.
Further reading
- OWASP Logging Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html
- Better Stack log documentation: https://betterstack.com/docs/logs/
- Datadog log management documentation: https://docs.datadoghq.com/logs/
- Grafana Loki documentation: https://grafana.com/docs/loki/latest/
Top comments (0)