Documentation
¶
Overview ¶
Package otel is Plinth's OpenTelemetry SDK initialisation.
One Init call in main configures the global tracer provider with the resource attributes Plinth expects (service.name, service.version, module.name, deployment.environment), wires the OTLP exporter, and installs the W3C trace-context propagator. The caller defers the returned shutdown.
The package name is `otel`, identical to the official OpenTelemetry Go module's root package. Consumers naming their import alias `otel` gets our package; our own source file aliases the SDK as `sdkotel` internally to disambiguate. See https://plinth.run/sdk/go/otel/.
Index ¶
- Constants
- func AttrModule(name string) attribute.KeyValue
- func HTTPMiddleware(next http.Handler, opts ...HTTPOption) http.Handler
- func Init(ctx context.Context, opts Options) (shutdown func(context.Context) error, err error)
- func RecordError(ctx context.Context, err error)
- type HTTPOption
- type Options
Constants ¶
const ( DefaultExporterEndpoint = "http://otel-collector.observability:4318" DefaultExporterProtocol = "http" // EnvOTELSamplerArg overrides Options.TracesSamplerArg. EnvOTELSamplerArg = "OTEL_TRACES_SAMPLER_ARG" // EnvENV is read when Options.Environment is empty. EnvENV = "ENV" )
Defaults; exposed so callers can compute "is this the default?" if needed.
const AttrModuleKey = attribute.Key("module.name")
AttrModuleKey is the OTel attribute key for "module.name" — Plinth's per-module dimension. Use AttrModule to build the attribute.
Variables ¶
This section is empty.
Functions ¶
func AttrModule ¶
AttrModule returns the AttrModuleKey attribute populated with name. Use for manual span tagging when the module name isn't already on the resource (e.g. cross-module spans).
func HTTPMiddleware ¶
func HTTPMiddleware(next http.Handler, opts ...HTTPOption) http.Handler
HTTPMiddleware wraps an http.Handler with otelhttp.NewHandler plus Plinth-specific span-name customisation (METHOD path).
For chi routers, callers can wire WithRouteFromContext (future option) to use the matched route pattern instead of the literal path — that's more useful for cardinality control.
func Init ¶
Init configures the global tracer provider, propagator, and resource. Returns a shutdown closure that flushes pending spans; defer it from main.
Standard usage:
shutdown, err := otel.Init(ctx, otel.Options{
ServiceName: "items-api",
ServiceVersion: version,
ModuleName: "items",
})
if err != nil { log.Fatal(err) }
defer func() { _ = shutdown(context.Background()) }()
Init returns an error for any configuration problem (missing ServiceName, unknown protocol, malformed endpoint). The OTLP exporter doesn't dial eagerly; an unreachable collector at startup doesn't fail Init — the SDK retries each batch internally.
func RecordError ¶
RecordError tags the current span with the error and sets its status. No-op if ctx has no span or err is nil.
Convenience over the verbose otel/codes + span.RecordError + span.SetStatus combination most call sites end up writing.
Types ¶
type HTTPOption ¶
type HTTPOption func(*httpConfig)
HTTPOption customizes HTTPMiddleware.
func WithOperationName ¶
func WithOperationName(name string) HTTPOption
WithOperationName overrides the default span-name prefix ("http.server").
type Options ¶
type Options struct {
// ServiceName is the OTel `service.name` resource attribute. Required.
// Use the running module's identifier (e.g. "items-api").
ServiceName string
// ServiceVersion populates `service.version`. Defaults to "unknown" if empty.
// Inject from build-time ldflags: -X 'main.version=$(git describe --tags)'.
ServiceVersion string
// Environment populates `deployment.environment.name`. Defaults to
// os.Getenv(EnvENV) → "dev". Recognised values: "production", "staging", "dev".
Environment string
// ModuleName populates the Plinth-specific `module.name` attribute.
// Optional; matches the convention used by sdk-go/audit and sdk-go/errors.
ModuleName string
// ExporterEndpoint is the OTLP target. Defaults to the in-cluster
// collector at http://otel-collector.observability:4318.
ExporterEndpoint string
// ExporterProtocol selects "http" (OTLP/HTTP, default) or "grpc".
ExporterProtocol string
// ExporterHeaders are sent on every export. Useful for hosted backends.
ExporterHeaders map[string]string
// TracesSamplerArg is the parent-based ratio sampler arg in [0, 1].
// Defaults: 1.0 in dev, 0.5 in staging, 0.05 in production.
// Set OTEL_TRACES_SAMPLER_ARG in the env to override this (and any
// explicit value passed in code — env wins, matching the OpenTelemetry
// spec). Pointer so zero is distinguishable from unset; pass nil
// (or leave zero-value) to use env-or-default, &0 for explicit
// no-sampling.
TracesSamplerArg *float64
// BatchTimeout caps how long the BatchSpanProcessor buffers before flushing.
// Defaults to the SDK's default (5 seconds).
BatchTimeout time.Duration
// Logger receives init / exporter / shutdown messages. Defaults to slog.Default().
Logger *slog.Logger
// Exporter overrides the OTLP exporter selection. Tests pass in-memory
// recorders here; production typically leaves this nil and lets Init
// build an OTLP exporter from ExporterEndpoint / ExporterProtocol.
Exporter sdktrace.SpanExporter
}
Options configure Init. ServiceName is the only required field; sensible defaults fill the rest.