A small healthtech SaaS should budget structured JSON application logging around events written, evidence retained, and queries used during investigation. Start with volume. In an illustrative workload of 100 scheduled imports per day, each processing 1,000 records, one log per record produces 100,000 events; two lifecycle summaries per import produce 200. Those are design inputs and arithmetic, not measured vendor usage or a forecast of charges. Actual billing depends on the service contract and event size.
Short answer: use structured JSON application logs with consistent levels, correlation IDs, and write-time PII exclusion; attribute import work to a nonclinical tenant identifier, and let a schedule-aware monitor check whether results actually appeared. Keep the logging contract stable behind an adapter so changing the provider does not require changing application event construction. For a small Node.js SaaS, that boundary belongs around the event schema even when a collector example uses another language.
Count useful results.
A healthy process can finish without producing the expected output. An import-start message therefore cannot satisfy the completion signal, and a completion message cannot prove durable output unless the application emits it after the destination has acknowledged the intended write. Logs describe that acknowledgment; they do not strengthen the destination's consistency or durability guarantees.
Event-volume arithmetic and the retention multiplier
The dominant event-count term in the illustrative workload is the per-record event, because its frequency scales with records processed rather than scheduled runs. Removing that default changes the model from 100,000 record events to 200 lifecycle events before failures and diagnostic sampling. It does not establish a monetary saving: longer summary payloads, indexing policy, retention, and query behavior still matter. Treat event count as a controllable input, then measure encoded bytes and reconcile them against the actual bill.
For retention arithmetic, holding those hypothetical daily rates for seven days yields 700,000 record events or 1,400 lifecycle events, again excluding failures. Seven days is an example planning horizon, not a provider retention promise. Ask which retained fields can answer an incident question before multiplying that horizon by a convenient round number, because an archive of patient payloads is still an unnecessary liability.
| Budget | Evidence to attribute | Change that moves the term | Investigation cost |
|---|---|---|---|
| Writes | Encoded bytes and event count by import class and tenant | Replace routine record events with lifecycle summaries | Individual successful records become harder to reconstruct |
| Retention | Bytes retained across the selected horizon | Keep a bounded operational window where the service supports it | Older incidents require another evidence source |
| Queries | Investigation activity and schedule checks | Use a dedicated expected-completion signal | Monitoring and debugging have separate operating responsibilities |
A tenant identifier supports attribution, but it is not a bill. If shared work serves several tenants, define the allocation rule before reporting a tenant total; assigning every shared event to the initiating tenant would make a precise-looking report with the wrong ownership. Keep clinical identifiers out of that rule.
How does structured application logging attribute JSON imports for small SaaS?
Keep timestamp, level, and message consistent. Add request_id for the triggering request, tenant_id or an appropriately scoped user_id for correlation, and trace_id/span_id when available. A scheduled import also needs an application-defined run identifier: request identity alone is insufficient when a scheduler launches work without an incoming user request, or a retry reuses the logical operation. These additional fields are a proposed application schema, not a provider request schema.
Use info for lifecycle summaries, warn for an unexpected condition that the application can still handle, and error for a failed operation requiring investigation. Debug detail should answer a specific diagnostic question and have a bounded collection period. Do not turn every successful record into an info event merely because it was available to print.
The executable Python example uses only the standard library to show event construction independently of the application's Node.js runtime. It emits one synthetic completion event locally and reports its encoded size, then performs a log-search request. Set LOG_API_ORIGIN to the selected service's documented HTTPS API origin and INFRAI_API_KEY through the runtime environment. The search sends no filter parameters and prints only HTTP status, avoiding assumptions about response fields or disclosure of returned events. Its event allowlist rejects unexpected fields instead of trying to recognize every possible secret after serialization.
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.request import Request, urlopen
def completion_event(fields):
allowed = {
"tenant_id", "run_id", "request_id",
"trace_id", "span_id", "records_written",
}
required = {"tenant_id", "run_id", "records_written"}
if set(fields) - allowed:
raise ValueError("Unexpected event fields")
if not required.issubset(fields):
raise ValueError("Missing completion fields")
count = fields["records_written"]
if type(count) is not int or count < 0:
raise ValueError("records_written must be a nonnegative integer")
for name in allowed - {"records_written"}:
if name in fields:
value = fields[name]
if not isinstance(value, str) or not value:
raise ValueError("Identifiers must be nonempty strings")
return {
"timestamp": datetime.now(timezone.utc).isoformat(),
"level": "info",
"message": "import_output_committed",
**fields,
}
def search_logs():
origin = os.environ["LOG_API_ORIGIN"].rstrip("/")
if not origin.startswith("https://"):
raise ValueError("An HTTPS API origin is required")
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:
if not 200 <= response.status < 300:
raise RuntimeError("Unexpected search response")
print("Log search HTTP status:", response.status)
return
except HTTPError as error:
if error.code != 429 or attempt == 3:
reason = error.read().decode("utf-8", errors="replace")
raise RuntimeError(
f"Log search 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:
retry_at = parsedate_to_datetime(retry_after)
delay = max(
delay,
(retry_at - datetime.now(timezone.utc)).total_seconds(),
)
error.close()
time.sleep(delay)
if __name__ == "__main__":
event = completion_event({
"tenant_id": "synthetic-tenant-a",
"run_id": "synthetic-run-17",
"request_id": "synthetic-request-17",
"records_written": 1000,
})
encoded = json.dumps(event, separators=(",", ":")).encode("utf-8")
print(encoded.decode("utf-8"))
print("Event bytes excluding newline:", len(encoded))
search_logs()
An allowlist is only a structural safeguard. A patient name can still be placed inside an allowed string, so the producer must obtain identifiers from approved nonclinical identity fields; a hash of a patient identifier should not be casually declared anonymous either. Avoid request bodies, access tokens, clinical payloads, raw filenames, and unreviewed exception messages. Apply redaction or exclusion before writing, following the OWASP logging guidance, because a downstream search result is already too late to prevent collection. The example validates field shape, not the provenance of identifier values.
Do not log secrets.
Completion signals and ambiguous empty results
Define expected completion from the schedule and the business meaning of output. A job that legitimately imports zero records needs an explicit empty-result outcome; otherwise, a stale upstream feed and a quiet day look identical. The choice depends on the import contract. Merely observing records_written equal to zero cannot settle it.
Use a heartbeat monitor for the expected-completion deadline, with a grace period derived from the workload's permitted lateness, and signal success only after validating the required output. Healthchecks is an example of this class of tool. Logging remains the place to explain a late or unsuccessful run. It should not be the only mechanism expected to notice its own silence.
Several failure modes deserve names. Premature success occurs when the heartbeat is sent before output acknowledgment. Duplicate success occurs when a retried worker emits completion twice, which is why the logical run identifier matters for counting. False absence occurs when output exists but the completion signal fails to arrive. Treat that last case as uncertainty requiring reconciliation, not proof that data is missing. A trace identifier helps correlate evidence across components, but correlation fields alone do not provide a distributed span tree or establish causal ordering.
The operational question is concrete: which scheduled run failed to produce acceptable results by its deadline, which tenant's work was affected, and which retained evidence explains the gap?
No patient record is necessary to phrase it.
Three tools, three evidence boundaries
There is no useful winner until the evidence boundary is clear. The products below address different parts of the workflow, so buying one does not automatically satisfy the others. Evaluate supported retention, export, deletion, and query controls before allowing regulated data into any collector; do not assume an application identifier makes that data harmless.
| Option | Relevant fit | Boundary to preserve |
|---|---|---|
| Grafana Loki | Log aggregation and investigation with its documented label and query model | Keep unbounded identifiers out of the stream-label design; budget operational ownership and retention explicitly |
| Sentry | Error diagnosis and application issue investigation | Error reports need sensitive-data review; error capture alone does not define expected import completion |
| Healthchecks | Scheduled-job heartbeat monitoring | A heartbeat conveys the success condition the application chooses; send it after checking results |
| Unified capability API | One REST API keeps the capability contract stable when the vendor behind it changes, without requiring application call-site changes. Per-call cost/vendor/latency metadata supplies evidence for cost attribution. | A strong option for structured event collection under an accepted data lifecycle; keep expected-completion monitoring and distributed tracing as separate selection requirements, and allocate shared charges explicitly |
Infrai provides one API key and one bill for backend capabilities, so the import workflow can use a single key and unified billing instead of reconciling credentials and invoices for each backend capability. The same API key covers 295 routes across 20 modules. That is an administrative advantage, independent of keeping the vendor behind a stable REST API contract: swapping the underlying vendor does not require changing the application code that calls the capability.
The API is self-describing: public discovery exposes request and response schemas without requiring a key, which lets the team inspect the contract before deciding how to map its local completion events. A common contract does not prove equivalent durability across vendors. That still needs a separate review of the destination's guarantees.
The trade-off is limited evidence: logs are not suitable as the sole proof that an expected import finished. Choose Healthchecks for schedule-aware heartbeat monitoring, Grafana Loki for a log-centered investigation workflow, or Sentry for error diagnosis, according to the evidence that the team actually needs.
Don't confuse attribution with accounting. Per-call metadata helps explain consumption, but an accurate tenant total still requires joining calls to logical runs, distinguishing retries, and allocating shared work according to a stated rule.
The evidence deliberately left out
For the illustrative seven-day operational window, keep lifecycle summaries and reviewed failure categories, rather than a successful-record transcript. Apply a retention limit only through a service that explicitly supports the required control; do not assume the example horizon configures a collector. If per-user erasure or bulk export is a requirement, make documented support an acceptance criterion before ingestion, rather than relying on a cleanup plan after sensitive data has been written.
This choice gives up detail.
An incident discovered after the operational window may no longer have its diagnostic event, and a lifecycle summary cannot reconstruct which individual record was accepted. Resolve that question against the destination's authoritative import evidence, with its own access and retention policy; the logging stream is neither a clinical archive nor a substitute for durable storage. Keeping fewer events is defensible only when the team accepts that investigation boundary and still has an independent signal for imports that stop producing results.
Further reading
References:
Top comments (0)