Documentation
¶
Overview ¶
Package telemetry wires OpenTelemetry: the OTLP exporters (traces, a bridge that ships the Prometheus registry as OTLP metrics, and a log provider for application and audit records), the HTTP server middleware, an instrumented client transport and a pgx tracer.
Everything is off unless Config.OTLP.Enabled is set, and each signal has its own switch under it. Without traces no tracer provider is installed, no middleware is added and the transport and pgx tracer reduce to an atomic load, so a build without tracing behaves as it did before.
Attributes never carry credentials or user data: spans are named after the route template (never the raw path), URLs are reduced to host and scheme (never the query string or userinfo), and SQL is reduced to the sqlc statement name (never the text or its arguments).
Index ¶
- Constants
- func Enabled() bool
- func HTTPMiddleware() func(http.Handler) http.Handler
- func Install(tp trace.TracerProvider) func()
- func LogCore() zapcore.Core
- func LogFields(ctx context.Context) []zap.Field
- func RoutePattern(ctx context.Context) string
- func Setup(ctx context.Context, cfg Config, build Build, gatherer prometheus.Gatherer, ...) (func(context.Context) error, error)
- func SpanName(method, route string) string
- func StartSpan(ctx context.Context, name string, attrs ...attribute.KeyValue) (context.Context, func(err error))
- func WrapClient(c *http.Client) *http.Client
- type Build
- type Config
- type DBTracer
- func (DBTracer) TraceBatchEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceBatchEndData)
- func (DBTracer) TraceBatchQuery(ctx context.Context, _ *pgx.Conn, data pgx.TraceBatchQueryData)
- func (DBTracer) TraceBatchStart(ctx context.Context, _ *pgx.Conn, _ pgx.TraceBatchStartData) context.Context
- func (DBTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData)
- func (DBTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context
- type FrontendConfig
- type Logger
- type OTLPConfig
Constants ¶
const ( ProtocolGRPC = "grpc" ProtocolHTTP = "http" )
Protocols accepted by Config.OTLP.Protocol.
const DefaultServiceName = "openartifact"
DefaultServiceName is the service.name reported when none is configured.
Variables ¶
This section is empty.
Functions ¶
func HTTPMiddleware ¶
HTTPMiddleware starts a server span per request, continuing the W3C traceparent/baggage of the caller. The span is renamed to the matched route template once the router has run (chi only knows it afterwards). It returns next untouched while telemetry is disabled.
It wraps the router from outside (api.HTTPServer.AddMiddleware), where chi's route context does not exist yet, so it seeds one: chi reuses it, and the matched pattern is readable here after next returns. Mount it before the logging middleware so log lines can carry the trace id. Probe endpoints (/health, /ready, /metrics) are not traced: polled every few seconds they would drown real traffic. Neither are the frontend telemetry relay's exports (every open UI posts every few seconds, and each would be a new root trace).
func Install ¶
func Install(tp trace.TracerProvider) func()
Install makes tp the process tracer provider and enables W3C trace context and baggage propagation. The returned function restores the disabled state. Setup uses it; tests use it with an in-memory provider.
func LogCore ¶ added in v0.14.0
LogCore returns the zap core that bridges application log records to the log provider Setup installs, under the application instrumentation scope. The provider maps the zap level to the record severity and adds the service.* resource attributes; a context field (see LogFields) sets the trace and span ids.
Records leave the process, so the core scrubs them first (see scrubCore): URLs lose userinfo and query string, request paths lose download tickets, query fields are replaced and error text is cleaned. The log output the core is teed with is not affected.
func LogFields ¶
LogFields returns the "trace_id" and "span_id" fields of the span in ctx, ready to pass to a zap logger call, or nil when ctx has no valid span (telemetry disabled, or a request outside any trace). The ids let a log line be joined to its trace in the backend.
The fields are followed by ctx itself, in a field no encoder writes: the log line is unchanged, and the OTLP bridge (LogCore) emits the record under ctx, so the record carries the span's trace and span ids as its own, not only as attributes.
func RoutePattern ¶
RoutePattern returns the chi route template of the request being served ("/repos/{name}/*" becomes "/repos/{name}"), or "" when no route matched. It is only complete once the router has dispatched the request.
func Setup ¶
func Setup( ctx context.Context, cfg Config, build Build, gatherer prometheus.Gatherer, logDropped *prometheus.CounterVec, log Logger, ) (func(context.Context) error, error)
Setup starts one provider per signal switched on in cfg and installs it as the process-wide provider: the tracer provider (with Install, so Enabled and HTTPMiddleware follow it) for traces, the meter provider for metrics, and a single log provider (otel.SetLoggerProvider) when logs or audit is on. With cfg.OTLP.Enabled false, or every signal off, it installs nothing and the returned shutdown is a no-op. gatherer feeds the metrics bridge (nil disables it). logDropped counts, by instrumentation scope, the log records the log provider drops because its export queue is full (nil counts nothing). The shutdown flushes every provider and restores the no-op ones.
func SpanName ¶
SpanName is the server span name for a request: "<METHOD> <route template>", or just the method when no route matched. The raw path never appears, so the number of distinct names is bounded by the route table.
func StartSpan ¶ added in v0.9.0
func StartSpan(ctx context.Context, name string, attrs ...attribute.KeyValue) (context.Context, func(err error))
StartSpan opens an internal span named name under a sampled request span and returns the context carrying it plus the function that ends it (pass the operation's error, or nil). It exists to break a request into steps that are not database queries (object store calls, for instance), so name and attrs must come from a fixed set: never identifiers, paths or URLs. A failed span records the Go type of the error, never its message.
While telemetry is disabled or the request is not sampled it returns ctx and a no-op, so it is safe on hot paths.
func WrapClient ¶
WrapClient instruments c in place: every request through it becomes a client span ("HTTP <METHOD>") and carries the traceparent/tracestate headers (never baggage) of the calling context. Attributes are limited to method, scheme, host and port (never the path or query, which may hold tokens or presigned signatures) and the status code. It is a no-op at request time while telemetry is disabled. The client's redirect policy and timeout are untouched.
Types ¶
type Config ¶
type Config struct {
OTLP OTLPConfig `yaml:"otlp"`
Frontend FrontendConfig `yaml:"frontend"`
}
Config is the telemetry section of the server configuration.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns the defaults: disabled, grpc, traces only, every trace sampled.
func (Config) FrontendActive ¶ added in v0.15.0
FrontendActive reports whether the frontend telemetry relay is on: the feature toggle and the OTLP master switch.
func (Config) FrontendURL ¶ added in v0.15.0
FrontendURL is the collector URL the relay forwards signal ("traces" or "logs") to. It assumes a configuration Validate accepted with the frontend active.
type DBTracer ¶
type DBTracer struct{}
DBTracer is a pgx tracer (query and batch) that emits one client span per statement, named after the sqlc statement ("GetUser") or, for hand-written SQL, its leading verb ("SELECT"). The SQL text and its arguments are never recorded, so neither values nor identifiers from user input reach a span.
Spans are created only under a sampled request span: background workers polling the database do not mint a trace per query. It is safe to install unconditionally: while telemetry is disabled every hook returns at once.
func (DBTracer) TraceBatchEnd ¶
TraceBatchEnd implements pgx.BatchTracer.
func (DBTracer) TraceBatchQuery ¶
TraceBatchQuery implements pgx.BatchTracer: each statement of the batch is an event on the batch span.
func (DBTracer) TraceBatchStart ¶
func (DBTracer) TraceBatchStart(ctx context.Context, _ *pgx.Conn, _ pgx.TraceBatchStartData) context.Context
TraceBatchStart implements pgx.BatchTracer.
func (DBTracer) TraceQueryEnd ¶
TraceQueryEnd implements pgx.QueryTracer.
type FrontendConfig ¶ added in v0.15.0
type FrontendConfig struct {
// Enabled turns the whole feature on. Off by default: the UI then loads no
// telemetry code and the relay and its config endpoint answer 404.
Enabled bool `yaml:"enabled"`
// Endpoint is the OTLP/HTTP base URL the relay forwards to ("/v1/traces"
// and "/v1/logs" are appended). Empty uses telemetry.otlp.endpoint, which
// then has to be an OTLP/HTTP one (protocol http).
Endpoint string `yaml:"endpoint"`
}
FrontendConfig configures the experimental browser telemetry: the web UI loads the OpenTelemetry browser SDK and sends its errors, web vitals and API client spans to a same-origin relay, which forwards them unchanged as OTLP/HTTP to the collector. It needs telemetry.otlp.enabled (the shared headers and TLS) and has no compatibility promise.
type OTLPConfig ¶
type OTLPConfig struct {
// Enabled is the master switch: nothing is exported without it, whatever
// the per-signal switches say. Off by default; OTEL_SDK_DISABLED=true
// forces it off.
Enabled bool `yaml:"enabled"`
// Endpoint is host:port or an http(s) URL of the collector. Empty uses the
// SDK default (localhost:4317 for grpc, localhost:4318 for http).
Endpoint string `yaml:"endpoint"`
// Protocol is "grpc" (default) or "http" (OTLP/HTTP protobuf).
Protocol string `yaml:"protocol"`
// Headers are sent with every export request (collector credentials).
// Never logged. The environment form is comma-separated key=value pairs
// with percent-encoded values.
Headers map[string]string `yaml:"headers"`
// Insecure disables TLS towards the collector. An http:// endpoint implies it.
Insecure bool `yaml:"insecure"`
// ServiceName is the service.name resource attribute.
ServiceName string `yaml:"serviceName"`
// SampleRatio is the fraction of new traces recorded, in [0,1]. Requests
// carrying a sampled traceparent are always recorded (parent based).
SampleRatio float64 `yaml:"sampleRatio"`
// Traces exports distributed traces and installs the HTTP server
// middleware. On by default, so enabled alone keeps tracing. The
// environment form is OTEL_TRACES_EXPORTER: otlp turns it on, none turns
// it off.
Traces bool `yaml:"traces"`
// Metrics exports the Prometheus registry (Go runtime and openartifact_*
// families) over OTLP to the same endpoint. /metrics is unaffected. The
// environment form is OTEL_METRICS_EXPORTER: otlp turns it on, none turns
// it off.
Metrics bool `yaml:"metrics"`
// Logs sends the application log records over OTLP as well, next to the
// configured log output; with it (or audit) on, an OTLP log provider is
// started on the same endpoint. The environment form is
// OTEL_LOGS_EXPORTER: otlp turns it on, none turns it off.
Logs bool `yaml:"logs"`
// Audit streams every audit event as an OTLP log event (scope and event
// name openartifact.audit), independent of traces. It shares the log
// provider with logs. The stream is best effort: the audit_logs table
// stays the source of truth.
Audit bool `yaml:"audit"`
}
OTLPConfig configures the OTLP exporters. The endpoint, protocol, headers and TLS settings are shared by every signal. The standard OTEL_* environment variables override the file; the signal specific OTEL_EXPORTER_OTLP_TRACES_*, OTEL_EXPORTER_OTLP_METRICS_* and OTEL_EXPORTER_OTLP_LOGS_* variables only apply while endpoint is empty.
func (OTLPConfig) NormalizedProtocol ¶
func (c OTLPConfig) NormalizedProtocol() (string, bool)
NormalizedProtocol maps the accepted spellings to ProtocolGRPC/ProtocolHTTP. ok is false for anything else.