Observability with Experimental.Otlp
Experimental.
Experimental.Otlpis an experimental module. A release can change or remove it. It needs no opt-in intsconfig.jsonorvibe.config.json.
Experimental.Otlp sends a program's logs, metrics and traces to an OpenTelemetry collector over OTLP/HTTP. You keep writing logInfo, withSpan and Metric.counter, and you provide one layer (a value that supplies services to a program). The layer removes credentials from every export and caps the size of each request. Use it when a program logs prompts, tool results or other text that can hold a secret. The design is VIP-72.
The sample exports to a collector that a test owns. The collector is a fetch function in a .ts file, because a .vibe file does not read host globals such as Response.
// collector.ts
import * as HttpServerRequest from "effect/http/HttpServerRequest"
/** @throws {never} */
export function collectorFixture() {
const sent: Array<{ path: string; body: string }> = []
const collector: typeof globalThis.fetch = (input, init) => {
sent.push({ path: new URL(String(input)).pathname, body: new TextDecoder().decode(init?.body as Uint8Array) })
return Promise.resolve(new Response(null, { status: 200 }))
}
return { sent, collector }
}
/** @throws {never} */
export function browserExport(path: string, body: string) {
const headers = { "content-type": "application/json" }
return HttpServerRequest.fromWeb(new Request(`http://app.localhost${path}`, { method: "POST", headers, body }))
}import { collectorFixture } from "./collector.ts"
effect function triage() {
try logInfo("triage started with token=ghp_ABCDEFGHIJKLMNOPQRSTUVWX")
try annotateCurrentSpan({ api_key: "plain-value-123", "gen_ai.prompt": "summarize the notes" })
try Metric.update(Metric.counter("issues_labeled"), 1)
return "done"
}
export effect function main() {
const { sent, collector } = collectorFixture()
const telemetry = Experimental.Otlp.layer({ url: "http://localhost:4318", service: "triage" })
|> Layer.provide(%, FetchHttpClient.layer)
|> Layer.provide(%, Layer.succeed(FetchHttpClient.Fetch, collector))
|> Layer.provideMerge(%, Logger.layer([]))
provide telemetry {
try Console.log(try withSpan(triage(), "triage"))
}
const all = sent.map((request) => request.body).join("\n")
try Console.log(sent.map((request) => request.path).sort().join(" "))
try Console.log(all.includes("ghp_"), all.includes("token=[REDACTED]"))
try Console.log(all.includes("plain-value-123"), all.includes("gen_ai.prompt"))
try Console.log(all.includes("issues_labeled"), all.includes("service.name"))
}
// Run in an effect function: try main()done
/v1/logs /v1/metrics /v1/traces
false true
false false
true trueThe program runs unchanged, and the layer flushes all three signals when the provide block ends. The token in the log line, the api_key attribute value and the prompt never reach the collector. Logger.layer([]) removes the console logger so that the sample prints only its own lines. Without it, the console still prints the log line unscrubbed, because scrubbing applies to exports only.
Exports
The following table lists what the module exports.
| Export | What it is |
|---|---|
layer(options) | A layer that exports logs, metrics and traces as OTLP JSON, scrubbed and bounded |
relay(options) | An Effect that builds an HTTP handler, which forwards a browser's exports to a collector |
dropped | A Metric counter of discarded batches, named flows_observability_otlp_dropped |
redact(text) | The text with every recognized credential replaced |
scrubPayload(payload, { content? }) | An OTLP JSON payload scrubbed as layer scrubs it |
resource({ service, version?, attributes? }) | An Effect that validates a resource and fails with InvalidResourceConfiguration |
endpoint(url, headers?) | An Effect that validates a collector URL and fails with InvalidExporterEndpoint |
maxRequestBytes, maxInFlight | The request cap (1,048,576 bytes) and the concurrent request cap (4) |
maximumFieldLength, maximumResourceBytes | The resource limits: 1,024 UTF-16 code units a field, 131,072 bytes a resource |
Logger, Tracer, Metric and the unscrubbed Otlp, OtlpTracer, OtlpLogger and OtlpMetrics modules stay Effect's. Logging, Metrics and Tracing describe how to write the records. VIP-72 also specifies Experimental.Logger.journal, which copies a durable run's logs into its journal. It is not in this release.
Provide the layer
Experimental.Otlp.layer(options) requires Effect's HttpClient service. To use the platform's fetch, provide FetchHttpClient.layer to it, as the sample does. Provide the result once, around the whole program. The layer posts to /v1/logs, /v1/metrics and /v1/traces below url, and it flushes when its provide block ends.
The following table lists the options.
| Option | Type | Meaning |
|---|---|---|
url | string | The collector base URL: absolute http: or https:, with no credentials, query or fragment |
service | string | The service.name resource attribute |
version | string, optional | The service.version resource attribute |
attributes | record, optional | More resource attributes: strings, finite numbers, booleans, or arrays of one of those types |
headers | headers, optional | Headers for every export. A credential header needs an https: URL unless the host is localhost, 127.x.x.x or [::1] |
content | boolean, optional | To export prompts, completions, messages and tool content, set true. The default is false |
maxRequestBytes | number, optional | A lower request cap. Values above 1,048,576 are clamped to it |
exportInterval | duration, optional | The export cadence for all three signals. Effect's default applies when you omit it |
shutdownTimeout | duration, optional | The upper bound on the final flush |
The layer validates url, service, version and attributes when it is built, before the program starts. It ignores the OTEL_RESOURCE_ATTRIBUTES environment variable, so nothing enlarges a resource after validation. Removing the layer removes telemetry and changes nothing else: an export that fails does not fail or retry the code that logged.
Scrubbing
Every string in an export passes the redaction rules, and redact and scrubPayload expose the same rules as plain functions.
export effect function scrubbed() {
try Console.log(Experimental.Otlp.redact("Authorization: Bearer abc123def456 password=hunter2 tokens=12"))
const payload = Experimental.Otlp.scrubPayload({ attributes: [
{ key: "api_key", value: { stringValue: "v" } },
{ key: "gen_ai.prompt", value: { stringValue: "hello" } },
{ key: "gen_ai.usage.input_tokens", value: { intValue: 42 } }
] })
try Console.log(try Effect.try(() => JSON.stringify(payload)))
}
// Run in an effect function: try scrubbed()Authorization: [REDACTED] [REDACTED_TOKEN] password=[REDACTED] tokens=12
{"attributes":[{"key":"api_key","value":{"stringValue":"[REDACTED]"}},{"key":"gen_ai.usage.input_tokens","value":{"intValue":42}}]}The layer applies three kinds of rule:
- Text shapes. Private key blocks, credentials in URLs,
BearerandBasicvalues, JWTs,sk-andpk-keys, and GitHub, GitLab, AWS, Slack, Google and npm tokens become[REDACTED]or a named marker. So does the value in an assignment such aspassword=…orapi_key: …. - Attribute keys. An attribute whose key ends in a credential word, such as
api_key,authorization,passwordorsession, gets the value[REDACTED]. A numeric attribute whose key ends intokensis a count and stays. - Content. Attributes named
gen_ai.prompt,gen_ai.completion,gen_ai.input.messages,gen_ai.output.messages,gen_ai.system_instructions,gen_ai.tool.call.arguments,gen_ai.tool.call.result,gen_ai.request.messages,gen_ai.response.textorvibe.content, and names below them, are removed. To keep them, setcontent: true. Text rules still apply to kept content.
The rule set is finite. Keep a value that must never leave the process in a Redacted field, not in a log line.
Bounds
The transport discards a batch instead of queueing or retrying it. The following table lists the reasons.
| Reason | Condition |
|---|---|
oversized | The scrubbed request body is larger than maxRequestBytes |
stalled | The collector does not answer within 10 seconds |
saturated | Four export requests are already in flight |
Each discard adds one to Experimental.Otlp.dropped. At most once a minute, a discard also writes one warning log with the annotations code: "otlp_export_discarded", reason, bytes, limit and dropped. The warning goes to the loggers that existed before the layer, so it never enters the exporter. The transport refuses redirects and reads no response body.
Validate configuration
endpoint and resource run the checks that layer runs, so a program can reject bad configuration at startup.
export effect function validated() {
try Console.log(try Experimental.Otlp.endpoint("http://localhost:4318/"))
const url = try Effect.flip(Experimental.Otlp.endpoint("http://user:pw@collector.example"))
try Console.log(url._tag, url.reason)
const name = try Effect.flip(Experimental.Otlp.resource({ service: "" }))
try Console.log(name._tag, name.path, name.reason)
}
// Run in an effect function: try validated()
// Output: http://localhost:4318
// Output: InvalidExporterEndpoint the URL holds no credentials; use headers
// Output: InvalidResourceConfiguration service is not emptyEffect.flip swaps success and failure so that the sample can print the error. reason states the rule the value broke and never repeats the value. layer fails with the same two errors.
Relay a browser's exports
Experimental.Otlp.relay builds a handler for a route on your own server. A browser posts OTLP JSON to that route, and the handler scrubs the body and forwards it to the collector. Headers you configure, such as the collector's credential, stay on the server.
import { browserExport, collectorFixture } from "./collector.ts"
export effect function relayed() {
const { sent, collector } = collectorFixture()
const forward = try Experimental.Otlp.relay({ url: "http://localhost:4318" })
provide FetchHttpClient.layer, FetchHttpClient.Fetch = collector {
const ok = try forward(browserExport("/telemetry/v1/logs", `{"body":"password=hunter2"}`))
const other = try forward(browserExport("/telemetry/v1/profiles", "{}"))
try Console.log(ok.status, other.status, sent[0]?.path, sent[0]?.body)
}
}
// Run in an effect function: try relayed()
// Output: 200 404 /v1/logs {"body":"password=[REDACTED]"}The handler takes Effect's HttpServerRequest and returns an HttpServerResponse with no body. relay takes url, headers, content and maxBodyBytes, which defaults to 1,048,576 and cannot exceed it. The following table lists the statuses.
| Status | Condition |
|---|---|
| The collector's status | The request was forwarded |
405 | The method is not POST |
404 | The path does not end in /v1/logs, /v1/metrics or /v1/traces |
415 | The content type is not application/json |
413 | The body is larger than maxBodyBytes |
400 | The body is not JSON |
502 | The collector does not answer |
Rules and diagnostics
The module adds no compiler diagnostics of its own. The following table lists the failures and the one diagnostic a collector fixture meets.
| Code or error | Condition |
|---|---|
InvalidExporterEndpoint | The URL is not absolute http: or https:, or it holds credentials, a query, a fragment, a space, a backslash or a control character. A credential header with a non-local http: URL fails the same way |
InvalidResourceConfiguration | service is empty, a field or attribute key is longer than 1,024 code units or holds a control character, an attribute value has an unsupported type, an attribute is named service.name or service.version, or the resource is larger than 131,072 bytes |
EK4402 | A .vibe file reads a host global such as globalThis.Response. Move that code to a .ts file, as collector.ts does |
Related pages
- Logging, Metrics and Tracing cover the records this layer exports.
- Experimental platform APIs lists every
Experimentalmodule. - Durable workflows covers the journal that records a run.