Observability
Structured JSON logging with redaction, request tracing and logs, Sentry reporting that runs on Workers, and health routes.
Usage
import { Hono } from "hono"
import { errorHandler } from "@dapplelight/signet-server/http"
import { requestId } from "@dapplelight/signet-server/middleware/request-id"
import { createLogger, type Logger } from "@dapplelight/signet-server/observability/logger"
import { requestLog } from "@dapplelight/signet-server/observability/request-log"
import { createSentry } from "@dapplelight/signet-server/observability/sentry"
import { traceMiddleware } from "@dapplelight/signet-server/observability/trace"
import { env } from "./env"
export const log = createLogger({ level: "info", base: { service: "api" } })
const sentry = createSentry({ dsn: env.SENTRY_DSN, enabled: env.APP_ENV === "production", environment: env.APP_ENV })
const app = new Hono<{ Variables: { reqId: string; logger: Logger } }>()
app.use("*", requestId({ childLogger: (id) => log.child({ reqId: id }) }))
app.use("*", traceMiddleware({ serviceName: "api", skipPaths: ["/health/live", "/health/ready"] }))
app.use("*", requestLog({ logger: log, skipPaths: ["/health/live", "/health/ready"], slowMs: 1000 }))
app.onError(errorHandler({
isProduction: () => env.APP_ENV === "production",
onError: (err, meta) => sentry.captureException(err, meta), // the promise goes to waitUntil
}))
app.get("/orders/:id", (c) => {
c.get("logger").info({ orderId: c.req.param("id") }, "order fetched")
return c.json({ ok: true })
}){"level":"info","time":"2026-09-25T07:15:49.201Z","msg":"order fetched","service":"api","reqId":"9f3c...","orderId":"ord_1042"}{"level":"info","time":"2026-09-25T07:15:49.230Z","msg":"request.completed","service":"api","method":"GET","route":"/orders/:id","reqId":"9f3c...","traceId":"4bf92f3577b34da6a3ce929d0e0e4736","status":200,"durationMs":29}Both take config and never read env. Without an OpenTelemetry SDK registered, every call is a no-op. @opentelemetry/api is an optional peer dependency.
API
observability/logger
| Export | What it does |
|---|---|
createLogger(options) | A logger: trace, debug, info, warn, error, fatal, child(bindings), level, isLevelEnabled. |
redactFields(fields, options?) | The same cleaning on its own, for context sent elsewhere (Sentry does not scrub context). |
LEVELS | trace 10 to fatal 60. |
LevelName, LevelSetting, LogFields, LoggerOptions, LogFn, Logger | Types. |
createLogger option | Type | Default | |
|---|---|---|---|
level | LevelSetting | string | "info" | A plain string is accepted; unknown throws. silent writes nothing. |
base | Record<string, unknown> | none | Fields on every line. |
redact | string[] | none | Extra key names (any depth) or dotted paths like user.phone, items.*.card. |
write | (line, level) => void | console.error, warn, log by level | Workers Logs reads severity from the console method. |
production | boolean | false | Drop stack from errors. |
messageKey | string | "msg" | |
mixin | () => Record<string, unknown> | off | Called on every line. Its fields come after base and before the call's fields, and are redacted like any other. |
Call shapes: log.info({ ...fields }, "msg"), log.info("msg"), log.info("msg", { ...fields }), log.error(err, "msg"). No %s interpolation.
Secrets are redacted by default at any depth: password, passwd, token, secret, authorization, cookie and apiKey, ignoring case, _ and -, and as a suffix (accessToken yes, maxTokens no). Strings are not scanned, so a secret inside msg goes out as written. Levels are live: log.level = env.LOG_LEVEL. A child follows its parent until given its own level. It never throws on data: cycles become "[Circular]", bigints strings.
observability/trace
| Export | What it does |
|---|---|
traceMiddleware(config) | Hono middleware. One server span per request with http.request.method, http.route and http.response.status_code. |
withSpan(name, attrs, fn) | Runs fn(span) in a child span of the current one. A throw is recorded on the span and rethrown. |
traceContext(c) | { traceId, spanId } for the request. Both are undefined when tracing is off and no valid traceparent came in. |
TraceConfig, TraceIds, SpanHandle | Types. |
traceMiddleware option | Type | Default | |
|---|---|---|---|
serviceName | string | required | Set on each span as service.name. |
tracerName | string | serviceName | |
skipPaths | string[] | none | Exact paths that get no span, such as /health/live. |
attributes | (c) => Record<string, string | number | boolean> | none | Extra attributes per request. Nothing here is scrubbed. |
The span is named GET /orders/:id. Status 5xx marks it as an error. Errors are recorded on the span and rethrown. An incoming W3C traceparent header continues the caller's trace. Spans and log lines carry method, route pattern and status. They never carry bodies, query strings or headers. @opentelemetry/api is an optional peer dependency, loaded on first use. Without an OpenTelemetry SDK registered, every call is a no-op. Signet adds no exporter. Needs hono 4.8 or later.
observability/request-log
| Export | What it does |
|---|---|
requestLog(config) | Hono middleware. Logs request.started, then request.completed or request.failed. |
RequestLogConfig | Type. |
requestLog option | Type | Default | |
|---|---|---|---|
logger | Logger | required | A Logger fits. Any object with a method per level name taking (msg, fields) works. |
skipPaths | string[] | none | Exact paths that are not logged. |
slowMs | number | off | A completed request at or over this gets slow: true. The message stays request.completed. |
level | (status) => LevelName | below 400 info, 4xx warn, 5xx error | Level of request.completed. request.started is info; request.failed is error. |
Fields are method, route (the pattern, never the raw path), status, durationMs (an integer), reqId and traceId. request.failed adds error, the message only. reqId comes from requestId, traceId from traceMiddleware or the incoming traceparent. Mount it after both. The slow flag is Signet's; the Hono middleware it was modelled on has no slow field.
observability/sentry
| Export | What it does |
|---|---|
createSentry(config) | captureException(err, context?, scope?) and isEnabled. Plain fetch to the envelope endpoint. |
redactSecrets(text) | Default scrub: bearer tokens, JWTs, password=-style secrets, emails, 9+ digit runs. |
parseStack(stack, scrub?) | Frames from a JS stack string, oldest call first. |
SentryConfig, SentryScope, SentryEvent, SentryRequest, SentryUser, StackFrame, Sentry | Types. |
createSentry option | Type | Default | |
|---|---|---|---|
dsn | string | none | Disabled when absent. |
enabled | boolean | required | false: errors go to console.error instead. |
release, environment | string | none | |
tags | Record<string, string> | none | On every event. |
clientName | string | "signet" | |
scrub | (text) => string | redactSecrets | Applied to message and stack. (t) => t turns it off. |
includeStack | boolean | true | |
beforeSend | (event) => event | null | none | Last look; null drops it. Allowlist context here. |
captureException resolves to whether Sentry accepted the event and never rejects. On Workers pass it to ctx.waitUntil, or return it from errorHandler's onError. scope carries tags, traceId (sent as the trace_id tag), request (url, method, query_string, headers; headers matching key|token|secret|auth|cookie|session|password are dropped) and user. Context values, tags and user values are not scrubbed: send only what you mean to.
observability/health
| Export | What it does |
|---|---|
healthRoutes(config) | A Hono app with GET /live and GET /ready. Mount it under a prefix of your choosing. |
HealthConfig | Type. |
healthRoutes option | Type | Default | |
|---|---|---|---|
checks | Record<string, () => Promise<boolean>> | required | One named check per dependency. Return true when it is usable. |
timeoutMs | number | 2000 | Longest a single check may take. |
| Route | Returns |
|---|---|
GET /live | 200 with { "ok": true }. |
GET /ready | 200 with { "ok": true, "checks": { "db": true } }, or 503 with "ok": false and the failed checks set to false. |
/live always returns 200 and runs nothing. /ready runs every check at once. A check that returns false, throws, or takes longer than timeoutMs counts as failed. Any failure returns 503. The body holds only true or false per check, never error text. Keys keep the order of checks. Responses carry Cache-Control: no-store. No other route answers. Takes config and never reads env.
import { healthRoutes } from "@dapplelight/signet-server/observability/health"
import { app } from "./app"
import { pingDb, pingKv } from "./checks"
app.route("/health", healthRoutes({ checks: { db: () => pingDb(), kv: () => pingKv() } }))Pass /health/live and /health/ready to skipPaths in traceMiddleware and requestLog so probes stay out of spans and logs.
http/observability
Read-only admin routes for AI cost over time, on signet-db's createAiSpend with an aiSpendLedger table (typed structurally, so this package does not import signet-db). Every route is denied unless authorize returns true.
| Export | What it does |
|---|---|
observabilityAdminRoutes({ spend, authorize, actor? }) | A Hono app of four GET routes. actor is accepted so one options object also serves aiSpendAdminRoutes; these routes only read. |
AiSpendLedgerStore, ObservabilityAdminOptions | Types. |
| Route | Returns |
|---|---|
GET /cost/series?days&scope&subject | { series }: spend per UTC day. scope is user, org or global (default global). subject is a raw id, hashed on the server, and needs scope user or org. |
GET /cost/by-model?days | { models }: spend per model, biggest first. Model names are never truncated. |
GET /cost/top?days&scope | { top }: biggest spenders by subject hash. scope is user (default) or org. |
GET /cost/cache-savings?days | { savings }: cacheSavedUnits, spentUnits and series per day. |
days is a whole number from 1 to 400 (default 30). An empty ledger is a 200 with an empty array or zero totals. Errors use the same envelope as aiSpendAdminRoutes: 403 FORBIDDEN, 400 VALIDATION_FAILED with details.fieldErrors, and any other store error goes to your errorHandler. Subjects appear only as their hash; no raw id and no prompt is ever in a response.
import { observabilityAdminRoutes } from "@dapplelight/signet-server/http/observability"
import { app } from "./app"
import { spend } from "./spend"
app.route("/api/admin/observability", observabilityAdminRoutes({
spend, // createAiSpend(db, { tables: { usageCounters, aiSpendCaps, aiSpendLedger } })
authorize: (c) => c.get("session")?.role === "admin",
}))Examples
Add your own redaction
import { createLogger } from "@dapplelight/signet-server/observability/logger"
const log = createLogger({ redact: ["email", "user.phone", "items.*.card"] })
log.info({ user: { phone: "+919876543210" }, token: "abc" }, "signed in") // phone and token become "[redacted]"Report with request context on Workers
import { redactFields } from "@dapplelight/signet-server/observability/logger"
import { app } from "./app"
import { sentry } from "./sentry"
app.onError((err, c) => {
c.executionCtx.waitUntil(
sentry.captureException(err, redactFields({ job: "sync" }), {
tags: { route: "/pay" },
request: { url: c.req.url, method: c.req.method },
user: { id: c.get("session")?.sub },
}),
)
return c.json({ error: "Internal error" }, 500)
})Tracing on Workers
Signet adds no exporter. The runtime or the app brings one, and the two options below differ only in who does.
With @microlabs/otel-cf-workers
The app installs @microlabs/otel-cf-workers on npm and @opentelemetry/api. The package registers the tracer provider and exports spans over OTLP; traceMiddleware and withSpan use it through @opentelemetry/api. Enable the nodejs_compat flag in wrangler.jsonc.
import { instrument, type ResolveConfigFn } from "@microlabs/otel-cf-workers"
import { Hono } from "hono"
import { traceMiddleware, withSpan } from "@dapplelight/signet-server/observability/trace"
const app = new Hono<{ Bindings: { OTLP_URL: string; OTLP_AUTH: string } }>()
app.use("*", traceMiddleware({ serviceName: "api" }))
app.get("/orders/:id", (c) =>
withSpan("orders.load", { "orders.source": "kv" }, async () => c.json({ id: c.req.param("id") })),
)
const config: ResolveConfigFn = (env: { OTLP_URL: string; OTLP_AUTH: string }) => ({
exporter: { url: env.OTLP_URL, headers: { authorization: env.OTLP_AUTH } },
service: { name: "api" },
})
export default instrument(app, config)With Cloudflare native tracing
Turn tracing on in wrangler.jsonc. Cloudflare records the Worker's own spans and sends them to the destination set in the dashboard. No package is needed.
{
"observability": { "enabled": true, "traces": { "enabled": true } }
}Signet's spans join those traces only when the runtime exposes an OpenTelemetry tracer provider to @opentelemetry/api. Otherwise traceMiddleware stays a no-op. requestLog still writes the traceId from the incoming traceparent header, so log lines match the trace.