Docs/Tooling & production/Observability & audit

Observability & audit

Add OpenTelemetry tracing, Prometheus metrics, W3C and X-Ray trace propagation, PHI redaction, and append-only Postgres audit logs to Fletch apps.

github.com/fletchhq/fletch/obs

fletch/obspkg.go.devfletch/auditpkg.go.devfletch/audit/postgrespkg.go.dev

Updated 2026-12-06 fletch docs show observability 8 min read

On this page

github.com/fletchhq/fletch/obs adds OpenTelemetry tracing, Prometheus text-format metrics, and PHI-safe redaction to a Fletch app without pulling telemetry dependencies into core modules. Pair it with github.com/fletchhq/fletch/audit and github.com/fletchhq/fletch/audit/postgres when you need a tamper-resistant compliance trail of who accessed or modified regulated records.

Introduction

Core Fletch packages (router, live, quiver, and data) stay free of OpenTelemetry and Prometheus imports by exposing small standard-library observer hooks. obs plugs into every one of those hooks at the application boundary through fletch.WithObservability.

For regulated workloads (HIPAA, PCI, SOC 2), observability has a second requirement: keeping patient names, card numbers, and secrets out of logs, error spans, SQL traces, and Live dev snapshots while recording every sensitive access in an append-only audit table. obs and audit cover both sides cleanly.

Configuration

Create an *obs.Provider with obs.New, pass it to fletch.WithObservability, and wire an append-only Postgres audit recorder with fletch.WithAudit:

package bootstrap

import (
	"log/slog"
	"os"

	"github.com/fletchhq/fletch"
	auditpg "github.com/fletchhq/fletch/audit/postgres"
	"github.com/fletchhq/fletch/obs"
	"github.com/fletchhq/fletch/router"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

func buildApp(tp *sdktrace.TracerProvider, db *nockpg.DB) *fletch.App {
	telemetry := obs.New(
		obs.WithTracerProvider(tp),
		obs.WithMetricsPath("/metrics"),
		obs.WithXRay(),
		obs.WithDropQueryText(),
	)

	// Run auditpg.SchemaSQL() in a migration before serving requests.
	auditRec := auditpg.New(db.Pool())

	app := fletch.New(
		fletch.WithNock(db),
		fletch.WithObservability(telemetry),
		fletch.WithAudit(auditRec),
	)

	app.Use(
		router.TrustedProxies(router.PrivateRanges...),
		router.AccessLog(slog.New(slog.NewJSONHandler(os.Stdout, nil))),
	)
	return app
}

obs.New performs no I/O. If you omit obs.WithTracerProvider, it reads the global provider from go.opentelemetry.io/otel.GetTracerProvider().

router.AccessLog writes one structured slog line per completed request containing method, matched route pattern (such as /users/{id}, never the raw path or query string), status, duration, bytes, and request_id. Requests returning 5xx log at Error, 4xx at Warn, and others at Info.

OpenTelemetry tracing and trace propagation

Correlated spans across subsystems

When you pass an *obs.Provider to fletch.WithObservability, Fletch instruments HTTP routes, Live views, and Quiver jobs automatically under instrumentation scope obs.ScopeName ("github.com/fletchhq/fletch/obs"):

Subsystem Observer method Span name Attributes and parenting
HTTP router RouterObserver() <METHOD> <pattern> SpanKindServer; http.request.method, http.route, http.response.status_code. Child of incoming request trace.
Live views LiveObserver() live.mount <view>, live.event <view> live.view, live.event. Mounts are children of the page request span; actions start their own trace.
Quiver jobs QuiverObserver() quiver.enqueue <kind>, quiver.run <kind> SpanKindProducer / SpanKindConsumer; quiver.job.kind, quiver.job.id, quiver.job.queue, quiver.job.attempt, quiver.job.outcome. Injects W3C traceparent into RawJob.Trace so job execution links to the enqueue span.
SQL (data) DataObserver() sql.query, sql.exec SpanKindClient; db.operation.name and db.query.text (omitted when WithDropQueryText() is set).

To trace statements on a *sql.DB opened with database/sql, connect p.DataObserver() using data.OpenObserved or data.ObserveConnector:

db, err := data.OpenObserved("sqlite", dsn, telemetry.DataObserver())

Incoming W3C Trace Context and AWS X-Ray propagation

fletch.WithObservability installs (*obs.Provider).Middleware() in front of the router automatically. On every request, it extracts incoming W3C traceparent and tracestate headers into the request context so the router's server span continues the caller's distributed trace.

On AWS behind an Application Load Balancer or API Gateway that sends X-Amzn-Trace-Id without a W3C traceparent header, enable obs.WithXRay():

telemetry := obs.New(
	obs.WithTracerProvider(tp),
	obs.WithXRay(),
)

When traceparent is absent, Middleware() parses Root=1-<8 hex>-<24 hex>;Parent=<16 hex>;Sampled=<0|1> into a remote OpenTelemetry span context. If you use obs outside the root fletch package, wrap your HTTP handler with telemetry.Middleware() yourself.

Custom fletch.Observability providers

fletch.WithObservability accepts any type implementing fletch.Observability. Your provider returns the observer hooks (RouterObserver, LiveObserver, QuiverObserver), optional metrics handler and path (MetricsHandler, MetricsPath), and Describe() (string, map[string]string) for fletch ax inspect. If your provider also defines Middleware() func(http.Handler) http.Handler, Fletch mounts it ahead of the router.

Prometheus metrics

*obs.Provider records counters, gauges, and histograms in memory and serves them in Prometheus text exposition format (0.0.4) with no external Prometheus client dependency.

Pass obs.WithMetricsPath("/metrics") to mount the endpoint on your app router automatically. To expose metrics on a private internal port or behind admin middleware instead, omit WithMetricsPath and mount telemetry.MetricsHandler() directly:

internalMux := http.NewServeMux()
internalMux.Handle("/metrics", telemetry.MetricsHandler())

obs exports these metrics:

Metric Type Labels Description
fletch_http_requests_total Counter method, route, status HTTP requests served
fletch_http_request_duration_seconds Histogram method, route HTTP request duration
fletch_live_sessions_active Gauge view Live sessions attached or pending attach
fletch_live_sessions_detached Gauge view Live sessions waiting for client reconnect
fletch_live_events_total Counter view, status Live actions executed
fletch_live_event_duration_seconds Histogram view Live action duration
fletch_live_session_memory_bytes Histogram view Estimated memory of one Live session
fletch_live_memory_bytes_total Gauge view Estimated memory across all sessions of a view
fletch_live_session_evictions_total Counter view Live sessions evicted for limits or errors
fletch_quiver_jobs_enqueued_total Counter kind, status Jobs enqueued
fletch_quiver_jobs_total Counter kind, status Job deliveries (succeeded, retried, snoozed, failed)
fletch_quiver_job_duration_seconds Histogram kind Job handler duration
fletch_sql_queries_total Counter op, status SQL statements executed
fletch_sql_query_duration_seconds Histogram op SQL driver latency

PHI and sensitive-data redaction

Wrapping values with obs.Sensitive[T]

Wrap regulated fields such as SSNs, patient names, or payment identifiers in obs.Sensitive[T] via obs.NewSensitive(v). Formatting with fmt, logging with slog, or encoding to JSON or text always emits obs.RedactedText ("[redacted]"). Application code retrieves the underlying value explicitly with .Value().

type Patient struct {
	ID  string
	SSN obs.Sensitive[string]
}

p := Patient{
	ID:  "pat_104",
	SSN: obs.NewSensitive("123-45-6789"),
}

// Logs "[redacted]" instead of the SSN.
slog.Info("loaded patient", "id", p.ID, "ssn", p.SSN)

rawSSN := p.SSN.Value()

Allowlist log filtering with obs.NewRedactingHandler

obs.NewRedactingHandler(base, allowlist...) wraps any slog.Handler so every attribute value is replaced with "[redacted]" unless its key is explicitly allowlisted. Attributes inside slog groups match by leaf key or dotted path (for example "user.id").

base := slog.NewJSONHandler(os.Stdout, nil)
logger := slog.New(obs.NewRedactingHandler(
	base,
	"request_id",
	"method",
	"route",
	"status",
	"duration",
	"bytes",
))
slog.SetDefault(logger)

Log messages themselves are kept verbatim, so write constant messages and pass dynamic values as structured attributes. Default-deny redaction ensures a newly added attribute cannot leak PHI to your log aggregator by accident.

Redacting errors and SQL queries on spans

When exporting traces to a third-party APM, combine two obs.New options so regulated payloads never leave your network:

  • obs.WithErrorRedactor(fn func(error) string): records fn(err) on failed spans instead of err.Error(), preventing database constraint errors or validation messages from echoing sensitive inputs.
  • obs.WithDropQueryText(): omits the db.query.text attribute from SQL spans.
telemetry := obs.New(
	obs.WithTracerProvider(tp),
	obs.WithDropQueryText(),
	obs.WithErrorRedactor(func(err error) string {
		if errors.Is(err, context.Canceled) {
			return "canceled"
		}
		return "internal error"
	}),
)

Redacting Live component fields (fletch:"phi")

Tag Live component struct fields holding PHI or PII with fletch:"phi":

type IntakeView struct {
	Step        int
	PatientName string `fletch:"phi"`
	DateOfBirth string `fletch:"phi"`
}

When dev-mode inspection (/_fletch/ax/live_state) snapshots a mounted view, Fletch walks nested structs (up to 4 levels deep) and replaces every exported field tagged fletch:"phi" with "[redacted]". Fields wrapped in obs.Sensitive[T] also serialize as "[redacted]".

Append-only audit trails (audit and audit/postgres)

github.com/fletchhq/fletch/audit defines Fletch's standard-library audit contract: who acted (Actor), what they did (Action), what they touched (Resource), and whether it succeeded (Outcome: audit.Success, audit.Failure, or audit.Denied).

Wiring fletch.WithAudit

Pass an audit.Recorder to fletch.WithAudit(rec):

  • Every typed route that defines Authorize (excluding router.Public routes) is audited automatically. Fletch sets Action to "route.<name>" (or "route.<METHOD> <pattern>" when unnamed), Resource to r.URL.Path, Actor from auth.User(ctx) (falling back to app.Auth()), RequestID, IP, and Outcome (audit.Denied for 401/403, audit.Failure for 5xx or panics, audit.Success otherwise).
  • audit.Middleware(rec) attaches the recorder, client IP, and X-Request-Id to every request context so handlers can record finer-grained domain events with audit.Record.

Record custom domain events inside any handler or service:

err := audit.Record(ctx, audit.Event{
	Action:   "invoice.void",
	Resource: "invoice/" + invoiceID,
	Outcome:  audit.Success,
	Metadata: map[string]any{"reason": req.Reason},
})

audit.Record fills Actor, RequestID, and IP from context whenever the Event leaves them empty, defaults Outcome to audit.Success, and stamps Time in UTC. Never place raw PHI, tokens, or secrets inside Metadata.

Run router.TrustedProxies before audit.Middleware so Event.IP captures the real client address instead of your load balancer's IP.

Durable append-only storage (audit/postgres)

github.com/fletchhq/fletch/audit/postgres writes events to a Postgres fletch_audit_log table protected by database triggers that reject UPDATE, DELETE, and TRUNCATE with restrict_violation.

Run auditpg.SchemaSQL() in a migration, then construct the recorder over your *pgxpool.Pool (or a pgx.Conn / pgx.Tx):

// Apply auditpg.SchemaSQL() in a database migration first.
rec := auditpg.New(db.Pool())

app := fletch.New(
	fletch.WithAudit(rec),
)

Testing audited code with audit.MemoryRecorder

In tests, pass &audit.MemoryRecorder{} to fletch.WithAudit or audit.WithRecorder and inspect captured entries with rec.Events():

rec := &audit.MemoryRecorder{}
ctx := audit.WithRecorder(context.Background(), rec)
ctx = audit.WithActor(ctx, "usr_42")

if err := svc.VoidInvoice(ctx, "inv_9"); err != nil {
	t.Fatal(err)
}

events := rec.Events()

Reference

Observability (github.com/fletchhq/fletch/obs and fletch)

Symbol Package Role
WithObservability(o Observability) fletch Wires an observability provider into router, Live, Quiver, metrics, and trace middleware
New(opts ...Option) *Provider obs Builds an OpenTelemetry + Prometheus provider (no I/O)
WithTracerProvider(tp) obs Sets the OpenTelemetry trace.TracerProvider
WithMetricsPath(path) obs Mounts MetricsHandler() on the app router at path
WithErrorRedactor(fn) obs Replaces span error text with fn(err) before export
WithDropQueryText() obs Removes db.query.text from SQL spans
WithXRay() obs Extracts X-Amzn-Trace-Id when W3C traceparent is absent
(*Provider).MetricsHandler() obs http.Handler serving Prometheus text format 0.0.4
(*Provider).Middleware() obs Extracts W3C Trace Context (and X-Ray) into request context
(*Provider).DataObserver() obs data.Observer for data.OpenObserved / data.ObserveConnector
Sensitive[T], NewSensitive(v) obs Wrapper that prints, logs, and marshals as "[redacted]"
NewRedactingHandler(base, allow...) obs Allowlist slog.Handler redacting all other attribute values

Audit (github.com/fletchhq/fletch/audit, audit/postgres, and fletch)

Symbol Package Role
WithAudit(rec audit.Recorder) fletch Audits authorized typed routes and injects rec into request contexts
Event, Outcome audit Record struct and Success, Failure, Denied outcome constants
Recorder, MemoryRecorder audit Audit storage contract and in-memory test recorder
Record(ctx, event) audit Records an event using context Recorder, Actor, RequestID, and IP
Middleware(rec) audit HTTP middleware attaching recorder, client IP, and X-Request-Id to context
WithRecorder, WithActor, WithRequestID, WithIP audit Context helpers for manual or background-job audit recording
SchemaSQL(), New(db) audit/postgres Append-only fletch_audit_log DDL (with triggers) and pgx recorder