Documentation
¶
Overview ¶
Package o11y is the top-level entry point for the SDK. It exposes Init for constructing a configured *SDK that bundles trace, metric, log, and optional profiling providers together with the W3C TraceContext+Baggage propagator and a dual-output slog logger.
The SDK never mutates global OpenTelemetry state; callers wire the returned providers into their application explicitly (e.g. otel.SetTracerProvider).
See ADR 0001 (log format strategy), ADR 0002 (metrics strategy), and ADR 0007 (OTLP authentication) for the design rationale.
Index ¶
- Constants
- func DefaultLatencyBuckets() []float64
- type Config
- type FeatureToggles
- type Option
- func WithDisableDefaultViews() Option
- func WithEnvironment(env string) Option
- func WithExtraHTTPServerAttributeKeys(keys ...string) Option
- func WithHistogramBuckets(buckets []float64) Option
- func WithLogEnabled(enabled bool) Option
- func WithLogLevel(level slog.Level) Option
- func WithMaxUniqueRoutes(n int) Option
- func WithMetricsAddr(addr string) Option
- func WithMetricsEnabled(enabled bool) Option
- func WithMetricsOTLPEndpoint(endpoint string) Option
- func WithOTLPEndpoint(endpoint string) Option
- func WithOTLPHeaders(headers map[string]string) Option
- func WithProfilingAuthHeaders(headers map[string]string) Option
- func WithProfilingEnabled(enabled bool) Option
- func WithProfilingEndpoint(endpoint string) Option
- func WithRuntimeMetrics(enabled bool) Option
- func WithServiceName(name string) Option
- func WithServiceNamespace(namespace string) Option
- func WithServiceVersion(version string) Option
- func WithTraceEnabled(enabled bool) Option
- type SDK
Constants ¶
const DefaultMaxUniqueRoutes = 1000
DefaultMaxUniqueRoutes is the default export-boundary cap for distinct http.route values. Additional SDK cardinality limits protect in-process aggregation memory before export.
const DefaultMetricsAddr = ":2112"
DefaultMetricsAddr is the default listen address for the built-in Prometheus /metrics HTTP server.
Variables ¶
This section is empty.
Functions ¶
func DefaultLatencyBuckets ¶
func DefaultLatencyBuckets() []float64
DefaultLatencyBuckets returns a fresh copy of the SDK's default histogram boundaries. It returns a copy so that callers who keep a reference cannot accidentally mutate the package-level defaults.
Types ¶
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config defines the configuration for the o11y SDK.
type FeatureToggles ¶
FeatureToggles reports which observability pillars were enabled at Init time. Use sdk.Toggles to inspect active state at runtime, e.g. for health-check endpoints or to conditionally log a startup warning when a pillar is off.
Profiling reflects the combined state of WithProfilingEnabled and whether a non-empty Pyroscope endpoint was configured: it is true only when the SDK actually started a profiler.
type Option ¶
type Option func(*Config)
Option is a functional option for configuring the o11y SDK.
func WithDisableDefaultViews ¶
func WithDisableDefaultViews() Option
WithDisableDefaultViews disables SDK-managed HTTP metric views.
func WithEnvironment ¶
WithEnvironment sets the deployment environment (e.g., "production", "staging").
func WithExtraHTTPServerAttributeKeys ¶
WithExtraHTTPServerAttributeKeys extends the SDK-managed allow-list on the http.server.request.duration metric view. By default that view keeps only http.request.method, http.route, and http.response.status_code to bound cardinality; any other attributes attached to the record (for example via o11ygin.WithMetricAttributesFn or otelhttp's WithMetricAttributesFn) are dropped from the exported series and end up as exemplar labels, where the OpenMetrics 128-rune cap quickly trips. Use this option to promote a small set of caller-controlled keys (e.g. "app_name", "bot_name") onto the series itself so they participate in PromQL aggregations.
Cardinality is the caller's responsibility: every distinct value combination multiplies the existing route×method×status series count. Prefer keys whose value space is enumerable and small (tens, not thousands).
Keys are checked against the otelprom Prometheus label-name normalization (non-alphanumeric → '_', runs collapsed, leading digits prefixed with "key_"). The SDK drops — with a startup WARN log — any key that, after normalization:
- matches a built-in label the SDK already exports (the view-allowed HTTP semconv keys, the four resource constants, and the three otelprom scope labels otel_scope_name / _version / _schema_url), or
- matches another caller-supplied key from this or a prior WithExtraHTTPServerAttributeKeys call (e.g. "app.name" and "app_name" both normalize to "app_name"), or
- normalizes to the empty string.
Accepting either form of collision would silently merge two attribute values into a single Prometheus label, corrupting PromQL grouping for that dimension.
Calls accumulate. Has no effect when WithDisableDefaultViews is set, because no SDK-managed view exists to extend.
func WithHistogramBuckets ¶
WithHistogramBuckets overrides the histogram boundaries applied to HTTP server and client latency histograms. Defaults to DefaultLatencyBuckets; override only when your service has a genuinely different latency profile. Changing these from the package default makes cross-service P99 comparisons inconsistent.
func WithLogEnabled ¶
WithLogEnabled controls whether the SDK exports logs via OTLP to the OTel Collector. When false, slog records are written to stdout only; no OTLP log provider is started and no collector connection is attempted. Default: true (env var O11Y_LOG_ENABLED overrides the built-in default).
func WithLogLevel ¶
WithLogLevel returns an Option that sets the minimum logging level for the SDK.
func WithMaxUniqueRoutes ¶
WithMaxUniqueRoutes sets the distinct http.route export cap. Values <= 0 use DefaultMaxUniqueRoutes. The SDK also derives an in-process aggregation cardinality budget from this value to guard against unbounded attribute sets.
func WithMetricsAddr ¶
WithMetricsAddr returns an Option that sets the metrics HTTP server listen address to the provided addr. If not set, the metrics server defaults to DefaultMetricsAddr (":2112").
func WithMetricsEnabled ¶
WithMetricsEnabled controls whether the SDK initialises a real MeterProvider. When false, no Prometheus HTTP server is started and no OTLP metrics are exported. All instrumentation that accepts a MeterProvider receives a no-op provider, preserving compile-time compatibility with zero runtime cost. Default: true (env var O11Y_METRICS_ENABLED overrides the built-in default).
func WithMetricsOTLPEndpoint ¶
WithMetricsOTLPEndpoint switches the metrics exporter from Prometheus pull to OTLP push. When set, the /metrics HTTP server is not started and metrics are exported via OTLP/HTTP to the given endpoint. Use this for serverless environments (Lambda, Cloud Run) where exposing a scrape port is not possible. When unset, the default Prometheus pull model is used.
Example: o11y.WithMetricsOTLPEndpoint("http://collector:4318")
func WithOTLPEndpoint ¶
WithOTLPEndpoint sets the OTLP/HTTP collector endpoint used for traces and logs. The endpoint must be reachable by the SDK's process (no proxy is configured by this package).
Production note: prefer https:// in production deployments. The default http://localhost:4318 is intended for local development against an OTel Collector running on the same host. When sending telemetry across a network boundary, use TLS — observability traffic carries trace IDs, hostnames, error messages and stack traces that should not be exposed in plaintext.
If the endpoint requires authentication (Grafana Cloud, Honeycomb, NewRelic, Datadog, ...), pair this option with WithOTLPHeaders to attach the API token / Bearer header to every OTLP request.
func WithOTLPHeaders ¶
WithOTLPHeaders attaches custom HTTP headers to every OTLP/HTTP request emitted by the SDK (traces, logs, and OTLP metrics push). Typical use cases:
- Authentication against managed observability backends, e.g. {"Authorization": "Bearer <token>"} or {"X-Honeycomb-Team": "<api-key>"}.
- Multi-tenant routing on a shared Collector, e.g. {"X-Scope-OrgID": "<tenant>"}.
Calling WithOTLPHeaders multiple times merges into the same map; later calls overwrite earlier values for the same header key. Header values are not logged.
func WithProfilingAuthHeaders ¶
WithProfilingAuthHeaders attaches custom HTTP headers to every Pyroscope profile push. Use this for Grafana Cloud Profiles, Basic auth via an Authorization header, or multi-tenant routing such as X-Scope-OrgID.
Calling WithProfilingAuthHeaders multiple times merges into the same map; later calls overwrite earlier values for the same header key. Header values are not logged.
func WithProfilingEnabled ¶
WithProfilingEnabled controls whether the SDK starts the Pyroscope profiler and wraps the TracerProvider with the trace-to-profile bridge. Profiling is opt-in: it requires both this toggle to be on AND a non-empty endpoint set via WithProfilingEndpoint. Either condition alone is insufficient. This lets operators stage a profiling rollout (or roll it back) without removing the endpoint from deployment manifests.
Default: false (env var O11Y_PROFILING_ENABLED overrides the built-in default). Unlike trace/metrics/log, profiling defaults off because it is an additional fourth signal that must be explicitly enabled.
func WithProfilingEndpoint ¶
WithProfilingEndpoint sets the Pyroscope-compatible ingest endpoint. Examples:
- "http://alloy.infra.svc.cluster.local:4040" for Grafana Alloy
- "http://pyroscope.infra.svc.cluster.local:4040" for direct Pyroscope ingest
When empty, profiling is fully disabled: no profiler goroutines are started, no pprof globals are touched, and trace spans are not annotated with pyroscope.profile.id. Default: empty.
func WithRuntimeMetrics ¶
WithRuntimeMetrics toggles collection of Go runtime metrics (goroutines, GC, memory, etc.) via OTel runtime instrumentation. Defaults to true.
func WithServiceName ¶
WithServiceName sets the service name for trace resource attributes.
func WithServiceNamespace ¶
WithServiceNamespace sets the service.namespace resource attribute (OTel semconv). It is required: Init returns an error when empty. The value identifies the owning team or product unit and maps naturally to the Kubernetes namespace when services are namespaced by product. It becomes a constant Prometheus label (service_namespace="...") on every series and appears on all three observability signals (traces, logs, metrics).
func WithServiceVersion ¶
WithServiceVersion sets the service version (e.g. "1.4.2") for trace resource attributes. Used in OTel as service.version and is especially useful for canary deployments and version-based trace filtering.
func WithTraceEnabled ¶
WithTraceEnabled controls whether the SDK initialises a real TracerProvider and exports spans via OTLP. When false, Init returns a no-op TracerProvider; the W3C TraceContext propagator still parses and forwards trace headers so downstream services are unaffected. Default: true (env var O11Y_TRACE_ENABLED overrides the built-in default).
type SDK ¶
type SDK struct {
// Logger writes structured log records to two destinations:
// • stdout – JSON with service.name, traceId, and spanId fields
// (for local development and container log collection via Fluentd)
// • OTel Collector – OTLP/HTTP → Loki (full OTel Log Data Model; service
// identity comes from the shared Resource, not per-record attrs)
// When a span is active in the context, traceId and spanId are included
// automatically in both destinations.
// When WithLogEnabled(false) is set, only the stdout destination is active.
Logger *slog.Logger
// Propagator is the W3C TraceContext + Baggage composite propagator.
// Pass it to nats.Inject / nats.Extract for distributed tracing over NATS.
// The propagator is always set (even when trace is disabled) so that
// incoming trace headers are still parsed and forwarded to downstream services.
Propagator propagation.TextMapPropagator
// Toggles reports which observability pillars were enabled at Init time.
Toggles FeatureToggles
// contains filtered or unexported fields
}
SDK holds the initialized observability providers. It does not mutate any global state; callers wire it however they like, e.g. slog.SetDefault(obs.Logger) or otel.SetTracerProvider(obs.TracerProvider()).
func Init ¶
Init initializes and returns a configured *SDK for the calling service.
The following options are required; Init returns an error if any are missing or invalid:
- WithServiceName — identifies the service
- WithServiceVersion — used for canary / rollback tracking
- WithEnvironment — must be one of: production, staging, development, testing (common aliases such as "prod" and "stg" are normalized automatically)
- WithServiceNamespace — identifies the owning team / k8s namespace
On success the SDK contains a tracer provider, meter provider (Prometheus scrape or OTLP push), logger provider (stdout JSON + OTLP/HTTP → Loki), and an ordered shutdown list. Init does not set global OpenTelemetry state.
func (*SDK) Meter ¶
Meter returns a named meter from the SDK's MeterProvider for custom instrumentation. HTTP server and client instrumentation are provided by the http.NewServerHandler and http.NewTransport facades, which accept the SDK's MeterProvider directly.
func (*SDK) MeterProvider ¶
func (s *SDK) MeterProvider() metric.MeterProvider
MeterProvider returns the SDK's meter provider interface. Use this when wiring SDK-produced metrics into instrumentation libraries that accept an OTel MeterProvider directly.
func (*SDK) Shutdown ¶
Shutdown gracefully flushes and shuts down all registered SDK components. Each component is attempted even if a previous one fails; all errors are logged and returned joined. Always call with a context that has a timeout to cap the flush wait.
Shutdown is idempotent: subsequent calls return the same joined error without rerunning any closer. Callers may safely register Shutdown in multiple defer chains (for example, both in main and in a signal handler) without risking double-shutdown of underlying exporters.
func (*SDK) TracerProvider ¶
func (s *SDK) TracerProvider() oteltrace.TracerProvider
TracerProvider returns the SDK's tracer provider interface. Use this to wire the SDK's provider as the global OTel tracer provider if needed, e.g. otel.SetTracerProvider(sdk.TracerProvider()).
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
|
|
|
gin
command
Package main demonstrates gin instrumentation with the o11y SDK using OTLP metrics push.
|
Package main demonstrates gin instrumentation with the o11y SDK using OTLP metrics push. |
|
jetstream/publisher
command
Package main demonstrates a JetStream publisher instrumented with the o11y SDK.
|
Package main demonstrates a JetStream publisher instrumented with the o11y SDK. |
|
jetstream/subscriber
command
Package main demonstrates a JetStream pull consumer instrumented with the o11y SDK.
|
Package main demonstrates a JetStream pull consumer instrumented with the o11y SDK. |
|
metrics
command
Package main demonstrates metrics with the o11y SDK using OTLP push.
|
Package main demonstrates metrics with the o11y SDK using OTLP push. |
|
mongodb
command
Package main demonstrates MongoDB tracing through the o11y MongoDB wrapper.
|
Package main demonstrates MongoDB tracing through the o11y MongoDB wrapper. |
|
nats-core/publisher
command
Package main demonstrates a NATS Core publisher instrumented with the o11y SDK.
|
Package main demonstrates a NATS Core publisher instrumented with the o11y SDK. |
|
nats-core/subscriber
command
Package main demonstrates a NATS Core subscriber instrumented with the o11y SDK.
|
Package main demonstrates a NATS Core subscriber instrumented with the o11y SDK. |
|
nats-ws-browser/backend
command
Package main is the backend subscriber for the nats-ws-browser example.
|
Package main is the backend subscriber for the nats-ws-browser example. |
|
profiling
command
Package main demonstrates continuous profiling with the o11y SDK.
|
Package main demonstrates continuous profiling with the o11y SDK. |
|
Package gin provides gin instrumentation wrappers for the o11y SDK.
|
Package gin provides gin instrumentation wrappers for the o11y SDK. |
|
Package http provides HTTP instrumentation wrappers for the o11y SDK.
|
Package http provides HTTP instrumentation wrappers for the o11y SDK. |
|
internal
|
|
|
log
Package log encapsulates the OTel LoggerProvider and the slog handler chain (multi-handler, OTel-aware trace context injector) used by the top-level o11y SDK.
|
Package log encapsulates the OTel LoggerProvider and the slog handler chain (multi-handler, OTel-aware trace context injector) used by the top-level o11y SDK. |
|
metrics
Package metrics encapsulates the OTel MeterProvider used by the top-level o11y SDK.
|
Package metrics encapsulates the OTel MeterProvider used by the top-level o11y SDK. |
|
metricscap
Package metricscap rewrites high-cardinality metric attribute values at export boundaries.
|
Package metricscap rewrites high-cardinality metric attribute values at export boundaries. |
|
profiling
Package profiling encapsulates the SDK's Pyroscope profiler lifecycle.
|
Package profiling encapsulates the SDK's Pyroscope profiler lifecycle. |
|
testutil
Package testutil provides helpers shared across the o11y test suites.
|
Package testutil provides helpers shared across the o11y test suites. |
|
trace
Package trace encapsulates the OTel TracerProvider and OTLP/HTTP trace exporter used by the top-level o11y SDK.
|
Package trace encapsulates the OTel TracerProvider and OTLP/HTTP trace exporter used by the top-level o11y SDK. |
|
Package mongo provides a tracing-aware MongoDB client wrapper that wires the o11y SDK's TracerProvider and Propagator into otel-mongo/v2.
|
Package mongo provides a tracing-aware MongoDB client wrapper that wires the o11y SDK's TracerProvider and Propagator into otel-mongo/v2. |
|
Package nats provides a tracing-aware NATS connection wrapper that wires the o11y SDK's TracerProvider and Propagator into otelnats / oteljetstream.
|
Package nats provides a tracing-aware NATS connection wrapper that wires the o11y SDK's TracerProvider and Propagator into otelnats / oteljetstream. |