Use withRuntimeOperation, runtimeLogger, and createRuntimeLogger to attach
application context to logs and completed operations. See the full
operation logging guide for initialization,
steps, outcomes, redaction, export lifecycle, and release requirements.
Requires ingester 1.5.0. One summary per request (always kept), request ids echoed to clients, one issue per error code:
import {
autterRequests, autterErrorResponse, defineRuntimeErrors, runtimeContext,
} from "@autter/runtime-node";
export const billingErrors = defineRuntimeErrors("billing", {
declined: { status: 402, message: "Payment declined", expected: true,
why: "The card issuer rejected the charge", fix: "Ask for another card" },
limit: ({ plan }: { plan: string }) => ({ status: 429, message: `Plan ${plan} limit reached` }),
});
app.use(autterRequests({ ignore: ["/healthz", "/metrics"] }));
app.post("/checkout", async (req, res) => {
runtimeContext.set({ cart: { items: req.body.items.length } });
runtimeContext.info("Applied coupon", { coupon: "SPRING" }); // folded into the summary
if (overLimit) throw billingErrors.limit({ plan: "free" }); // Express 5 (next(err) on 4)
res.json({ ok: true, requestId: runtimeContext.requestId });
});
app.use(autterErrorResponse()); // { error: { message, code, why?, fix?, link?, requestId } }Also: autterFastify, withRuntimeRequest (fetch-style handlers),
runtimeContext.fork / runInBackground / carrier() for background work and
queues, the per-operation AI usage rollup, waitUntil, initAutterLogging
(no NodeSDK — for apps with their own OTel), enrichers (enrichUserAgent,
enrichRequestSize, enrichEdgeGeo, enrichDeployment), sinks (otlpSink,
consoleSink, fileSink → .autter/runtime/*.jsonl in development) and test
helpers:
import { captureRuntime, expectOperation } from "@autter/runtime-node/testing";
const runtime = captureRuntime();
// … exercise the app …
expectOperation(runtime, "POST /checkout").toHaveOutcome("degraded").toHaveErrorCode("billing.declined");Full guide: Requests, coded errors and background work.
The steps before an error, scoped to the current request:
import { addBreadcrumb, runtimeLogger } from "@autter/runtime-node";
app.post("/checkout", async (req, res) => {
addBreadcrumb({ message: "Loaded cart", data: { items: 3 } }); // type "custom"
runtimeLogger.info("Charging card", { provider: "stripe" }); // recorded as a "log" breadcrumb
await charge(); // a throw here carries both
});- Scope: inside
autterRequests()/withRuntimeRequest()/withRuntimeOperation()the trail belongs to the request and is shared with its child operations and forks (AsyncLocalStorage). Inside a traced request without the middleware it belongs to the trace; outside both, to the process (so a crash outside any request carries what happened before it). - The last 30 are kept.
captureException,captureMessageand errors thrown out of operations attach them to the exception span event asautter.breadcrumbs(a JSON string, at most 16 KB, or less whenOTEL_ATTRIBUTE_VALUE_LENGTH_LIMITis lower). - Every
runtimeLogger/runtimeContext.debug|info|warn|errorentry is recorded as alogbreadcrumb with its level and up to 10 primitive attributes. - Messages (≤ 500 characters) and data (≤ 10 keys of strings, numbers,
booleans or null) are scrubbed with your
redactsettings. - The browser relay forwards browser breadcrumbs, re-validated and re-scrubbed.
- Needs ingester 1.6.0. Logger-only mode (
initAutterLogging) and@autter/runtime-edgedon't attach them yet.
The server tracker exports per-instance RSS, heap, memory limit, and GC
metrics by default. See memory pressure incidents
for ECS/Kubernetes OOM event forwarding and optional heap profiles. Set
memoryMetrics: false only if another exporter already emits equivalent
process metrics.
Autter Runtime for Node.js — two halves in one package:
- Same-origin browser relay for
@autter/runtime-browser - Curated OpenTelemetry server tracker exporting OTLP/HTTP JSON
npm install @autter/runtime-nodeThe browser tracker posts to your backend; this handler validates and whitelist-sanitises the payload, attaches your private ingest key server-side, forwards asynchronously, and returns 202 immediately.
Express / Node http:
import { createBrowserRelayHandler } from "@autter/runtime-node";
app.post(
"/api/autter-runtime",
createBrowserRelayHandler({ apiKey: process.env.AUTTER_RUNTIME_KEY! }),
);Next.js App Router / any fetch-style runtime:
import { createBrowserRelayFetchHandler } from "@autter/runtime-node";
export const POST = createBrowserRelayFetchHandler({
apiKey: process.env.AUTTER_RUNTIME_KEY!,
});Options: endpoint (default AUTTER_ENDPOINT, then AUTTER_RUNTIME_ENDPOINT,
then https://otlp.autter.dev), maxBodyBytes
(default 64 KB), perIpRateLimit (default 120 requests a minute per client;
false when a WAF already limits the route), trustProxy, redact,
compatCheck, onError, waitUntil.
Serverless: pass waitUntil. The relay answers 202 at once and forwards
to the ingester afterwards (with retries). A platform that freezes or ends the
function once the response is sent loses that forward, so hand it the
platform's waitUntil: waitUntil from @vercel/functions on Vercel,
(p) => ctx.waitUntil(p) on Cloudflare Workers. The promise it gets never
rejects. createAutterRelayRoute in @autter/runtime-next does this for you.
Rate-limit key and trustProxy. The relay route is public, so it limits
each visitor. Any caller can write anything into X-Forwarded-For, so by
default (trustProxy: "auto") the relay never takes that header's first entry.
Proxies append the address they saw to the right of the header, or overwrite
it, so the relay reads it right to left and takes the first public address,
skipping hops on your own network. That works behind load balancers, CDNs and
hosting platforms with no setup:
| Where the relay runs | What "auto" keys |
|---|---|
| Node, reached directly | The connection's own address; the header is ignored |
| Node behind a load balancer or ingress on your network | The address that proxy appended |
| Next.js route handlers, Vercel, Netlify, Deno Deploy and other fetch runtimes | The rightmost public entry, which the platform's edge wrote |
| Cloudflare Workers | CF-Connecting-IP |
Other settings:
trustProxy: 1(or any count) when exactly that many proxies you control sit in front, such as a Node origin behind Cloudflare with no load balancer.trustProxy: truewhen every proxy in front strips client values: the leftmost entry.trustProxy: falsenever reads the header: the socket address in Node, one shared bucket in fetch runtimes.clientIp: (request) => stringto supply the address yourself, for example Deno'sinfo.remoteAddror Bun'sserver.requestIP.
Strings from environment variables work too ("auto", "false", "2").
A fetch handler exposed straight to the internet with no proxy in front can
still be fooled by a forged header; set trustProxy: false or clientIp there.
// instrument.ts — must run before anything else creates connections
import { initAutterServer } from "@autter/runtime-node";
const autter = initAutterServer({
apiKey: process.env.AUTTER_RUNTIME_KEY!,
service: "payments-api",
// environment: NODE_ENV by default; release: AUTTER_RELEASE, else the
// running commit (GIT_SHA, VERCEL_GIT_COMMIT_SHA, ...). See Defaults below.
});
// handled errors — always recorded, never sampled out:
autter.captureException(err, { "order.id": "…" });
// fingerprint override — every error carrying the same fingerprint is one
// issue, whatever its message or stack (a string or up to 10 strings, each
// ≤200 chars; sent as `autter.fingerprint` on the exception event; needs
// ingester 1.6.0+, older ingesters ignore it):
autter.captureException(err, { fingerprint: ["checkout", "card-timeout"] });
// warnings/info without an exception — same grouping+aggregation as
// errors, just a lower severity ("fatal" | "error" | "warning" | "info"):
autter.captureMessage("Legacy /orders lookup used", "warning");
// named process spans — background jobs, queue consumers, cron ticks,
// DB-heavy calls. Always recorded (never head-sampled), so Autter's
// slow-process monitor sees accurate run counts and durations, and can
// flag the process when it is slow and repeating a lot:
await autter.withProcessSpan("invoice.rebuild", async () => {
await rebuildInvoices();
});
// graceful shutdown flushes exporters (never rejects):
await autter.shutdown();Run it first: node --require ./instrument.cjs server.js (CJS), or for
pure-ESM apps add OTel's loader hook
(node --import ./instrument.mjs --experimental-loader=@opentelemetry/instrumentation/hook.mjs server.js)
so http auto-instrumentation can patch ESM imports.
Defaults (cheap by construction):
| Signal | Default |
|---|---|
| Captured/unhandled exceptions | 100% (dedicated always-on tracer) |
| Traces containing an error | 100% (tail retention, retainTracesOnError) |
| Traces of slow requests (over 500 ms and the route's p95 baseline) | kept whole, up to 60 a minute per process (tail retention, retainTracesAboveMs, retainSlowTracesPerMinute) |
withProcessSpan spans |
100% (same always-on tracer) |
| LLM/GenAI call spans | 100% with model, tokens, cost, latency and status (llmTracing, on by default); prompt and completion content only for failed or slow calls (llmContent) |
| Healthy traces | 1% head sampling (traceSampleRate; also for requests whose incoming traceparent is unsampled, such as browser fetches from @autter/runtime-browser) |
Request metrics (http.server.duration histogram, every request) |
exported every 60 s |
| Logs | not collected |
| PII in custom attributes | redacted before export (redactAttributes) |
| Query strings in span URLs | parameter names only (keepQueryParams) |
| Client IP, raw user agent, host id, command line | dropped (keepIdentifyingAttributes, dropAttributes) |
Forgotten shutdown() |
exporters still flushed on exit (autoFlush) |
Release (release unset) |
AUTTER_RELEASE, else the running commit as the full SHA; release: false or AUTTER_DETECT_RELEASE=false reports none |
| Running commit | the first of AUTTER_COMMIT, GITHUB_SHA, VERCEL_GIT_COMMIT_SHA, CF_PAGES_COMMIT_SHA, GIT_SHA, GIT_COMMIT, COMMIT_SHA, SOURCE_COMMIT, RENDER_GIT_COMMIT, RAILWAY_GIT_COMMIT_SHA, HEROKU_SLUG_COMMIT, SOURCE_VERSION holding 7 to 40 hex characters, sent as deployment.commit (never runs git) |
Environment (environment unset) |
NODE_ENV, else test under Jest, Vitest or node --test (JEST_WORKER_ID, VITEST, NODE_TEST_CONTEXT), else production |
Error-linked trace retention. Errors export at 100% while traces are
head-sampled — on its own that strands a retained error without the trace
that explains it. So unsampled spans are kept briefly in an in-process
buffer, and the moment a trace shows an error — a 5xx response, a recorded
exception, captureException, or an error-severity captureMessage — the
whole trace is exported, sampling lottery notwithstanding. The buffer is
bounded (512 spans per trace, 10 000 spans and about 16 MB in all, dropped
as soon as the request ends healthy, forgotten after 60 s without a span)
and never blocks. Over its budget it drops the newest in-flight traces,
whole: the oldest requests are the likeliest to end slow, so their child
spans are still there when their root ends. A dropped trace (or one over
512 spans) is never exported in part; it falls back to plain head sampling.
Disable with retainTracesOnError: false.
Slow-trace retention. The same buffer keeps the whole local trace of a
slow request: one whose root server span took longer than both 500 ms and
its route's p95 baseline. The SDK keeps that baseline per method and route
template from every request the process served (sampled or not, older ones
counting half every 15 minutes), so "slow" means slow for that endpoint.
A regression does not become the new normal within minutes: while a fifth
of a route's requests in the last minute or so are above its baseline, the
baseline is frozen, so a route that becomes and stays slow keeps a steady
sample of slow traces (within the budget below) instead of only its first
few. After an hour regressed the baseline adopts the new latency. The
baseline lives in the process: a process that starts slow (a deploy that
regressed) has no healthy baseline, and keeps slow traces only above 500 ms
until it has 20 requests. Slow traces are
rate limited: retainSlowTracesPerMinute (default 60) a minute per process,
bursts of up to 20, a sixth of it per route; past that, slow requests fall
back to head sampling. A positive retainTracesAboveMs is a fixed threshold
instead of the estimate; retainTracesAboveMs: false (or 0) turns it off.
Up to 1.11 it was off unless retainTracesAboveMs was set.
Every request span the SDK exports says why, in autter.retention_reason:
head (the random sample), error or slow (tail retention; these also
carry autter.tail_retained). Latency percentiles and endpoint regression
detection never depend on what is kept: they read the histograms, which
count every request. See Endpoint regressions.
Crashes are observed via process.uncaughtExceptionMonitor, which does
not change your process's exit behaviour; the final flush is
best-effort. Framework instrumentations are opt-in:
import { ExpressInstrumentation } from "@opentelemetry/instrumentation-express";
initAutterServer({ ..., instrumentations: [new ExpressInstrumentation()] });Express (4 and 5): automatic. With initAutterServer alone, the error
behind a 5xx response is recorded on the request span with its type,
message and stack, plus the route and (with autterRequests) the request id.
That covers a handler that throws, an async handler that rejects (Express 5),
next(err), and routers that have their own error handler. (Express 4
ignores the promise an async handler returns, so its rejection is an
unhandled rejection: recorded with the request's route and id, see below.)
Express's own
behaviour is unchanged. An error that ends in a 4xx response is not
reported this way, and neither is an error that autterErrorHandler() or
captureException already reported, so adding the handler never reports an
error twice. captureExpressErrors: false turns the automatic capture off.
Everything else needs its hook. When a Fastify or Koa handler throws, the
framework answers 500, and on its own that 500 is all the tracker sees: a
stackless HttpServerError grouped by route. Add your framework's hook and
the thrown error is recorded, with its stack, on the request span; the
framework then carries on exactly as before. On Express,
autterErrorHandler() still has two uses: it also reports coded errors that
end in a 4xx (and every error with { capture: true }), and it works in
logger-only setups (initAutterLogging).
import { autterErrorHandler, autterFastifyErrors, autterKoa, captureRequestError } from "@autter/runtime-node";
// Express / Connect (optional on Express with initAutterServer): after your
// routes, before your own error handlers. Records the error, then calls
// next(err) unchanged. Once at app level covers nested routers too.
app.use(autterErrorHandler());
// Fastify 4/5: an onError hook (Fastify's error handler still answers).
// autterFastify (request summaries) already includes it.
app.register(autterFastifyErrors); // or autterFastifyErrors(app)
// Koa 2/3: mount first; records and rethrows, so app.on("error") still fires.
app.use(autterKoa());
// Anything else (NestJS exception filters, hapi onPreResponse, …):
captureRequestError(err, { "app.handler": "checkout" });All three report errors with status ≥ 500 (or none), RuntimeErrors and coded
errors — ctx.throw(404) and validation failures stay out of your issues.
Pass { capture: true } to report every error, or a predicate. An error is
reported once, even if your handler already called captureException, and it
lands on the request's HTTP server span even when an instrumentation's child
span is active (captureRequestError still adds its attributes to that span
when the error was already reported). Errors from another JavaScript realm
(a vm context, Next's edge sandbox under next start) keep their own type,
message and stack. autterErrorResponse() reports the same way and also
answers the request.
initAutterServer({
...,
sampleRate: 0.5, // half of captured errors
ignoreErrors: ["ECONNRESET", /^AbortError$/, /^billing\.declined/],
});sampleRate(0..1, default 1): the share of captured errors reported:captureException, error-levelcaptureMessageandreportOutcome. Never a fatal message, a crash (uncaught exception) or an unhandled rejection (which may be one); warnings and info are never sampled. NottraceSampleRate, which samples healthy traces.ignoreErrors: never reported. A string matches when the error's type (error.name) or message contains it (case-sensitive); a RegExp is tested against the type, the message and"<type>: <message>". Every capture path, crashes included.- A value filtered out is marked captured, so a later hook (error
middleware,
onRequestError) does not report it either. A request that failed still exports its failed span, which the ingester turns into a stacklessHttpServerErrorfor a 5xx; leave those out with a suppression rule. initAutterLoggingtakes the same two options;registerAutter(@autter/runtime-next) passes them through.
What the SDK filters never leaves the process and is counted nowhere. For volume control that is counted, applies to every SDK and service at once and is changed without a deploy, use suppression rules in Autter's Runtime settings (drop or sample by error type, message, service, environment, route, release or source; ingester 1.9.0). The ingester also collapses a looping error into one sample a minute with an exact count.
Errors you catch and log count on their own — no captureException needed.
An Error passed to console.error, pino, winston, bunyan or
runtimeLogger.error becomes an occurrence at error severity, with the log
line as context and the error's stack, marked
autter.handling: "caught". A log line with no error object is untouched, and
an error you also pass to captureException in the same tick is reported
once. A caught error never fails the request it happened in, and handled
occurrences stay out of your error rate — they are issues to see, not
failures. A burst limit per error kind keeps ten at once, then one every ten
seconds; the ones left out are counted.
initAutterServer({ ... }); // on by default
initAutterServer({ ..., captureLoggedErrors: false }); // off
initAutterServer({ ..., captureLoggedErrors: { console: false } }); // keep loggers, not consoleWhen you mean to ignore an error — a fallback you chose — say so in one line:
try {
prices = await pricingService.get();
} catch (err) {
runtimeContext.degraded(err, "pricing service down, using cached prices");
prices = cached;
}runtimeContext.degraded(err, reason) records the error at warning
severity, marked autter.handling: "deliberate" with the reason (grouped by
its code when the error is coded), and never pages anyone. The current
request or operation ends degraded unless it already failed or set its own
outcome — so a crash, a caught error and a deliberate fallback are told apart.
Recorded as errors (severity error, autter.unhandled_rejection: true, not
fatal) — without changing whether your process crashes. Any
unhandledRejection listener switches off Node's default crash, so the SDK
does what Node would have done when its listener is the only one:
--unhandled-rejections |
Your own listener? | What happens | Recorded as |
|---|---|---|---|
throw (default) |
no | rethrown on the next tick: exit code 1, as before | fatal crash (autter.unhandled) |
throw (default) |
yes | your listener decides | error |
strict |
either | Node crashes first, as before | fatal crash |
warn, none |
either | no crash, as before | error |
warn-with-error-code |
no | Node's warning and exit code 1, as before | error |
The one visible difference: after the rethrow, uncaughtException listeners
receive origin "uncaughtException" rather than "unhandledRejection".
captureUnhandledRejections: false (or captureGlobalErrors: false) restores
the 1.5.0 behaviour, where a rejection is seen only when it crashes the
process.
A rejection from a promise started during a request, such as a floating
void sendReceipt() that fails after the response, keeps that request's
route, method and request id (http.route, http.request.method,
autter.request.id on its error span). The same holds for a crash, and for
a captureException call made after the response.
Some features need a minimum ingester version: operation logging needs
1.4.0, memory metrics 1.3.3, endpoint latency 1.3.1. After
initAutterServer, the SDK checks the ingester once in the background
(GET /v1/compat, unref'd, 3 s timeout). For each feature in use that the
ingester can't store, it prints one warning:
[autter-runtime] Operation logging needs ingester >= 1.4.0; yours is 1.3.4. Upgrade the ingester: docker pull ghcr.io/autter-dev/otlp-ingester:latest and restart it (ClickHouse migrations run at boot). See …/docs/COMPATIBILITY.md
The check never throws, never delays startup or exit, and is silent when
versions match or are unknown. debug: true logs the result. Turn it off
with compatCheck: false or AUTTER_COMPAT_CHECK=0. The browser relay does
the same for browser features such as CSP violation capture. The SDK reports
itself through the OTLP resource attributes telemetry.distro.name and
telemetry.distro.version, so the Autter dashboard shows the SDK version
each service runs.
For a full report (for example in CI or after a deploy):
npx @autter/runtime-node doctor --endpoint https://ingest.example.com [--key "$AUTTER_RUNTIME_KEY"] [--json]Exit codes: 0 compatible, 1 mismatch or rejected key, 2 ingester unreachable. See docs/COMPATIBILITY.md.
Telemetry is batched (errors every ~2 s, healthy traces every ~5 s, metrics
every 60 s) — so exiting without flushing loses whatever is still buffered.
initAutterServer therefore installs an exit flush by default: on
beforeExit, SIGINT, and SIGTERM it force-flushes every exporter, then lets
your process die as it would have (conventional 130/143 codes). If your own
code also handles those signals, Autter only flushes alongside it and never
touches your exit path. Opt out with autoFlush: false.
Prefer explicit control? Do the same yourself and get a handle back:
import { installAutterAutoFlush } from "@autter/runtime-node";
const handle = installAutterAutoFlush(); // uses the active server's exporters
// …later: handle.flush("deploy-drain") or handle.dispose()If the process still exits with captures that were never confirmed
exported (e.g. a flush timed out), you get a one-line stderr warning — not
silent loss. While wiring things up, set debug: true (or AUTTER_DEBUG=1)
to see [autter] exported N span(s) lines on stderr as batches leave.
A wrong ingest key (every export answers 401), an ingester that is down or
answers 5xx, or a network error never throws or rejects into your code.
shutdown(), forceFlush(), flushRuntimeLogs(), emitLlmSelftestTrace()
and the background exports all resolve, so awaiting them in an Express 4
route (which does not catch a rejected async handler) is safe. Each failure
is instead:
-
printed once a minute per kind of failure, with what to fix:
[autter-runtime] traces export failed (401 Unauthorized) — check your ingest key: the ingester at http://localhost:4318 does not accept it. … -
passed to
onExportError, every time (errors it throws are ignored); -
returned by the flush that hit it as
{ ok: false, errors }.
const autter = initAutterServer({
...,
onExportError: (error) => metrics.increment("autter.export_failed", { kind: error.kind }),
});
const { ok, errors } = await autter.forceFlush();
// errors[0]: { kind: "unauthorized", status: 401, signal: "traces", operation: "export", message, error }kind is one of unauthorized (401: the key), forbidden (403: a client or
upload key used for server telemetry), not_found (404: the endpoint),
payload_too_large, rate_limited, server_error, client_error,
unreachable (connection refused, DNS), timeout, not_initialized or
other. The original error is on the non-enumerable error field, so a
result can be passed to res.json() as it is. initAutterLogging takes the
same option, and its flush() returns the same result.
Note on usage rollups: requests are counted from the http.server.duration
metric (100% accurate), under their route template: Express routes and,
from 1.7.0, Next.js routes (/blog/[slug], from the next.route Next puts
on its own spans). The SDK marks its resource autter.metrics_wired and
autter.metrics_routes, and each request span whose metric got a route
autter.metric_has_route; an up-to-date ingester then counts that request
from the metric alone, whatever traceSampleRate is. A request whose
metric has no route (Koa, Fastify or plain http without a router
instrumentation) is also counted from its sampled spans, which keep its
path. Ingesters up to 1.7.0 count every sampled server span on top of the
metric (at traceSampleRate: 1, about twice the requests), except
tail-retained error traces (autter.tail_retained). Since 1.7.0 the SDK
also applies the HTTP instrumentation to servers created before
initAutterServer (Next.js creates its server before instrumentation.ts
runs): until then a Next.js app got request spans and metrics only from
the first request that happened to load http again, if ever.
Error context is where secrets leak: connect ECONNREFUSED postgres://admin:hunter2@db… in an exception message, a provider error
echoing an API key, a ?token= in a request URL, a stray
captureException(err, { "user.email": … }). Everything the SDK exports is
therefore scrubbed by default — custom attributes, exception messages and
stack traces, span status messages, LLM call attributes and errors,
structured logs, and the browser events the relay forwards. A final pass at
export time scrubs every span regardless of who created it (HTTP
instrumentation URLs, third-party instrumentations, recordException in
your own code).
- secrets inside any string are masked in place, keeping the rest of the
message/stack readable: JWTs,
Bearer/Basiccredentials,Authorization:/Cookie:/Set-Cookie:header text,scheme://user:pass@hostconnection strings (postgres, mysql, mongodb+srv, redis, …), vendor keys (sk-…,sk_live_…,ghp_…,github_pat_…,xox?-…,AIza…,AKIA…, …), PEM private keys,password=/?token=/?api_key=-style assignments, emails, and Luhn-valid card numbers; - attributes whose key looks sensitive (
password,token,secret,api_key,authorization,cookie,session,ssn,card_number, …) are masked wholesale, at any nesting depth; - non-sensitive keys, numbers (including LLM token counts) and booleans pass through untouched, so grouping, dashboards and cost tracking keep working.
The same patterns run in the browser SDK, the relay, the Python adapter,
and again in the ingester before storage (shared test vectors in
test-vectors/redaction.json).
Extend it (applies to messages, stacks and URLs too) or disable it per service:
initAutterServer({
...,
// redactAttributes: false, // opt out entirely
redactAttributes: {
additionalKeyPatterns: ["employee_id"],
additionalValuePatterns: [/^ACC-\d+$/],
},
});Libraries that must never forward PII regardless of host configuration can wrap once:
import { makeSafeCapture } from "@autter/runtime-node";
const safe = makeSafeCapture();
safe.captureException(err, { "user.email": email }); // masked before exportThe raw primitives are exported too (redactAttributes(attrs, options),
redactText(text, options)). The browser relay takes the same options as
createBrowserRelayHandler({ ..., redact }).
This closes the server-side gap to match the browser relay's payload
whitelist; it is best-effort scrubbing of obvious PII shapes, not a DLP
engine — keep secrets out of attributes in the first place.
Query strings (1.6.1+). Query strings carry what a path never should: emails, one-time codes, API keys, session ids, search terms. So no span leaves the process with query values, whichever instrumentation made it (HTTP server and client spans, undici/fetch, Express, Fastify, Next.js's own spans):
http.target,http.url,url.fullandurl.originalare cut at the?(and#):/[email protected]&page=2becomes/search;url.querykeeps only the parameter names,email=[redacted]&page=[redacted]. It is added from the URL when the instrumentation did not set it, so you still see which parameters a request used. A parameter without=(/verify?<token>) may itself be the secret and is masked whole;- span names lose their query too (Next.js names a request span
GET /search?q=…until it knows the route).
List the parameters whose values are safe to keep, such as pagination or
sorting (exact names, after percent-decoding; kept values are still scrubbed
by redactAttributes):
initAutterServer({ ..., keepQueryParams: ["page", "sort"] });
// url.query: "email=[redacted]&page=2"This runs at export, like the scrubbing above, and also with
redactAttributes: false. Route templates (http.route) and request
summaries never contained a query.
Identifying attributes. OpenTelemetry puts attributes that identify a
person or a machine on every server span and on the resource. None of them
looks like a secret, so scrubbing keeps them, and nothing in Autter reads
them. They are dropped at export from span, event and link attributes and
from the resource (spans and metrics), whichever instrumentation set them,
also with redactAttributes: false:
| What | Keys |
|---|---|
| The client's address and port (the peer's, on outgoing calls), and the server's own IP | net.peer.ip, net.peer.port, net.sock.peer.addr, net.sock.peer.port, http.client_ip, client.address, client.port, network.peer.address, network.peer.port, net.host.ip, net.sock.host.addr, network.local.address |
| The raw user-agent string | http.user_agent, user_agent.original |
| The machine's id and addresses | host.id, host.ip, host.mac |
| The command line and the user running it | process.command_args, process.command, process.command_line, process.owner, process.executable.path |
Kept: service.instance.id (a random id; the ingester needs it to tell
processes apart), host.name, process.pid, process.runtime.*,
os.type, host.arch, server.address, and the coarse
user_agent.browser / .os / .device / .bot fields of request
summaries. host.name is kept because it is usually a container or pod
name; on a laptop or a VM it is the machine's name, which can be a person's.
Drop it, or any other key, with dropAttributes:
initAutterServer({ ..., dropAttributes: ["host.name"] });
// or AUTTER_DROP_ATTRIBUTES=host.nameTo keep identifying attributes, list them, or pass true for all of them:
initAutterServer({ ..., keepIdentifyingAttributes: ["http.user_agent"] });
// or AUTTER_KEEP_IDENTIFYING_ATTRIBUTES=http.user_agent (true for all)The ingester drops the same keys on arrival, so an attribute kept here is
stored only when the ingester keeps it too: set
AUTTER_KEEP_IDENTIFYING_ATTRIBUTES on the ingester as well
(otlp-ingester README).
IDENTIFYING_ATTRIBUTE_KEYS exports the list.
Hashed client IP (opt-in). To count distinct clients without storing
their addresses, turn on hashClientIp with a secret salt. The client's
address is normalised (port, brackets and zone id removed, IPv6 lower-cased
and compressed, ::ffff:1.2.3.4 read as 1.2.3.4) and exported only as
client.address_hash: HMAC-SHA256 under the salt, the first 32 hex
characters. The raw address is still dropped.
initAutterServer({ ..., hashClientIp: { salt: process.env.AUTTER_CLIENT_IP_SALT } });
// or AUTTER_HASH_CLIENT_IP=true and AUTTER_CLIENT_IP_SALT=<secret>- The address is the first valid one of
client.address,http.client_ip(both filled fromX-Forwarded-For/Forwardedbehind a proxy), then, on server spans only, the socket peernet.peer.ip/network.peer.address/net.sock.peer.addr. Behind a proxy that does not forward the client address, the peer is the proxy, so every request hashes to the proxy. On client spans the peer is the server being called and is never hashed. - The salt is a secret of the project: at least 16 characters (32 random ones recommended), the same in every service and instance of the project, so the same client gives the same hash everywhere. It is never logged, exported or written to a span. Without a usable salt nothing is hashed and one warning is printed: there is no unsalted fallback, since every IPv4 address can be hashed in a few minutes.
- The Python adapter and the ingester compute the same hash from the same
salt. A span that already has
client.address_hashkeeps it. - A hashed IP is still pseudonymous personal data in some readings of privacy law (GDPR, for one): whoever holds the salt can test a known address against it. That is why it is opt-in; keep the salt with your other secrets and rotate it to unlink old hashes.
Bundlers can load this package more than once: Next.js bundles one copy
into instrumentation.ts and another into each route (unless it is in
serverExternalPackages), and a process can load both the ESM and the CJS
build. Since 1.6.1 every copy shares one process-wide state
(globalThis[Symbol.for("@autter/runtime-node")]): the copy that ran
initAutterServer (or initAutterLogging) is the SDK for all of them, so
withRuntimeRequest, captureException, runtimeLogger and the rest export
through it from any copy, and an error one copy reported is never reported
again by another. Before any copy starts, and after shutdown(), every copy
behaves as before: records go to the console. The shared object is
versioned; a copy that finds a layout it does not know keeps its own state.
For the field contract, manual reporting patterns, and provider-agnostic OpenTelemetry setup, see the dedicated LLM instrumentation guide.
initAutterServer initialises LLM tracing automatically: any GenAI span —
gen_ai.* semconv attributes, the Vercel AI SDK's ai.* spans,
OpenInference LLM and embedding spans, OpenLLMetry's llm.request.type —
bypasses
head sampling, so every model call is recorded with model, tokens,
latency, and a USD cost. Opt out with llmTracing: false.
Prompt, completion and other model input/output content on those spans and
on the AI framework spans around them (Vercel AI SDK ai.prompt* /
ai.response.*; OTel GenAI messages, system instructions, tool definitions
and calls, retrieval query and documents, the GenAI message events;
OpenInference input.value / output.value, llm.*_messages.*, prompt
templates, llm.invocation_parameters, llm.tools.*, tool.parameters,
documents and embedding texts on LLM, chain, tool, retriever and embedding
spans; OpenLLMetry gen_ai.prompt.N.* / gen_ai.completion.N.*,
llm.request.functions.*, traceloop.entity.input / output) is exported
only for calls that failed or were slow, marked autter.llm.content = "error" / "slow". Slow means over 20 s until the model has about 50
recent calls, then over both 500 ms and the model's p95 baseline, so at low
volume an ordinary few-second call keeps no content. Other calls keep every
counter (tokens, cost, model, finish reasons, roles) and are marked
autter.llm.content = "omitted". llmContent: "always" keeps the content
of every call (the behaviour up to 1.11), llmContent: "never" of none; a
failed call's status message and exception messages, which can quote the
completion, become [omitted] (its exception type and stack frames stay).
Details in the
LLM instrumentation guide.
Easiest: wrap the client once — works with the OpenAI, Anthropic,
Google GenAI and Bedrock Runtime (ConverseCommand) SDKs, OpenRouter through
the OpenAI SDK (or anything with the same call shapes), streaming included;
every call through it is traced with no per-call code, prompt-cache reads
and writes and reasoning tokens included:
import { instrumentLlmClient } from "@autter/runtime-node";
const openai = instrumentLlmClient(new OpenAI());
// use it exactly as before — chat, embeddings, streams are all recorded
const out = await openai.chat.completions.create({ model: "gpt-5-mini", ... });Provider is detected from the client (override with
{ provider, userId, attributes } as the second argument). For streamed
responses the span closes when the stream is consumed; OpenAI streams only
report token usage when you pass
stream_options: { include_usage: true }.
Vercel AI SDK — just turn on its telemetry, nothing else:
const { text } = await generateText({
model: openai("gpt-5-mini"),
prompt,
experimental_telemetry: { isEnabled: true, metadata: { userId: user.id } },
});Manual control (raw fetch, unusual clients) — wrap the call:
import { withLlmCall } from "@autter/runtime-node";
const res = await withLlmCall(
{ provider: "openai", model: "gpt-5-mini", userId: user.id },
async (llm) => {
const out = await openai.chat.completions.create({ ... });
llm.setUsage({
inputTokens: out.usage?.prompt_tokens, // every prompt token, cached ones included
outputTokens: out.usage?.completion_tokens, // reasoning included
cacheReadTokens: out.usage?.prompt_tokens_details?.cached_tokens,
});
return out;
},
);Errors thrown inside are rethrown after marking the span failed — failing
model calls surface both as error issues and as status: "error" LLM calls.
Costs are estimated ingest-side from a built-in price table; report exact
figures with llm.setCost(usd) (the autter.llm.cost_usd attribute).
Where wrapping is awkward (queues, callbacks, batch results), report after
the fact with
trackLlmCall({ provider, model, inputTokens, outputTokens, durationMs }).
inputTokens is the total prompt including cache reads and writes; pass
cacheReadTokens, cacheWriteTokens, cacheWriteLongTtlTokens and
reasoningTokens so the cost accounts for prompt caching
(token usage and prompt caching).
To verify the pipe end-to-end without calling a real model:
import { emitLlmSelftestTrace } from "@autter/runtime-node";
const { traceId, ok, errors } = await emitLlmSelftestTrace();
// one fake "autter-selftest" call is flushed to the ingester; look it up by
// traceId in the dashboard's LLM tab (or runtime_llm_calls when self-hosting).
// Never rejects: ok is false and errors says why when the trace was not
// delivered (kind "unauthorized" / status 401 is a wrong ingest key).Non-HTTP work is only visible to the slow-process monitor where a span
exists — and regular traces are 1% sampled. withProcessSpan records a
span always:
import { withProcessSpan } from "@autter/runtime-node";
await withProcessSpan("invoice.rebuild", async () => {
await rebuildInvoices();
});Use stable, low-cardinality names; put ids in attributes
(withProcessSpan("email.digest", fn, { "user.id": id })).
Note on the slow-process monitor: Autter flags HTTP routes from the unsampled request metrics, so route detection works out of the box. Non-HTTP work is only visible where a span exists — relying on 1%-sampled regular traces there would undercount ~100×, which is why these spans skip head sampling.