telemetry

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 37 Imported by: 0

Documentation

Overview

Package telemetry provides a unified, zero-wrapper bootstrap library for OpenTelemetry Tracing, Metrics, and Logs, pushing data over OTLP gRPC to any compatible collector (Grafana Alloy, OpenTelemetry Collector, ...).

Index

Constants

View Source
const (
	DefaultMaxExportBatchSize = 500
	DefaultBatchTimeout       = 5 * time.Second
	DefaultMetricInterval     = 30 * time.Second
)

Defaults applied when the corresponding Config field is zero.

Variables

View Source
var DefaultLatencyBuckets = []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}

DefaultLatencyBuckets are the histogram bucket boundaries, in seconds, used for request latency. They match the Prometheus client defaults, from 5ms to 10s, so percentiles are meaningful for typical service calls. The OpenTelemetry SDK's own defaults are sized for milliseconds and would put every sub-5-second request into a single bucket.

Functions

func Adapt added in v0.4.0

func Adapt[Req any, Resp any](mw kitendpoint.Middleware) middleware.Middleware[endpoint.Endpoint[Req, Resp]]

Adapt is the other direction: it turns a go-kit endpoint middleware, such as go-kit's rate limiter or circuit breaker, into a middleware for a typed endpoint:

greet = telemetry.Adapt[GreetRequest, GreetResponse](ratelimit.NewErroringLimiter(limiter))(greet)

The go-kit middleware sees the request and the response as any, so this direction needs a type assertion on the way back. One that replaces the request or the response with a value of another type makes the adapted endpoint return an error instead of panicking. Tracing, Logging and Metrics need no adapting: instantiate them with the endpoint's types.

It lives here rather than in the endpoint package so that package keeps no dependency beyond the standard library.

func ExtractGRPCTraceContext

func ExtractGRPCTraceContext() grpctransport.ServerRequestFunc

ExtractGRPCTraceContext extracts OTel tracing context from gRPC metadata.

func ExtractHTTPTraceContext

func ExtractHTTPTraceContext() httptransport.RequestFunc

ExtractHTTPTraceContext extracts OTel tracing context from HTTP Headers and injects it into the Go-kit context before the endpoint runs.

func InitPropagators

func InitPropagators()

InitPropagators registers the standard W3C TraceContext and Baggage propagators globally, enabling context propagation across network layers (HTTP headers, gRPC metadata). It is called by InitTraces; applications that skip tracing but still forward trace headers can call it directly.

func InjectGRPCTraceContext

func InjectGRPCTraceContext() grpctransport.ClientRequestFunc

InjectGRPCTraceContext returns a Go-kit ClientRequestFunc that injects the active trace/baggage context from the execution thread into outgoing gRPC metadata.

func InjectHTTPTraceContext

func InjectHTTPTraceContext() httptransport.RequestFunc

InjectHTTPTraceContext returns a Go-kit ClientRequestFunc that extracts the active trace/baggage context from the execution thread and injects it into outbound HTTP headers.

func Kit added in v0.4.0

Kit converts a middleware over endpoint.Endpoint[any, any] into a go-kit endpoint middleware. go-kit's endpoint type is Endpoint[any, any] under another name, so this is a type conversion: no assertion, no extra call. It is how Tracing, Logging and Metrics, or any typed middleware instantiated with [any, any], decorate a go-kit endpoint:

ep = telemetry.Kit(telemetry.Tracing[any, any]("greet"))(ep)

func Logging added in v0.4.0

func Logging[Req, Resp any](operationName string, logger *slog.Logger) middleware.Middleware[endpoint.Endpoint[Req, Resp]]

Logging returns a middleware that logs one record per call of a typed endpoint: "endpoint execution succeeded" at Info, or "endpoint execution failed" at Error with the error, both with the operation and the duration. Records go through the context-aware slog methods, so they carry the active trace and span IDs. A nil logger means slog.Default(), resolved on every call, so the middleware can be built before InitTelemetry installs the default logger.

func LoggingMiddleware deprecated

func LoggingMiddleware(operationName string, logger *slog.Logger) kitendpoint.Middleware

LoggingMiddleware is Logging for a go-kit endpoint.

Deprecated: use Kit(Logging[any, any](operationName, logger)).

func Metrics added in v0.4.0

func Metrics[Req, Resp any](recorder *MetricsRecorder, operationName string) middleware.Middleware[endpoint.Endpoint[Req, Resp]]

Metrics returns a middleware that records every call of a typed endpoint on recorder as method operationName: one request, its latency and, on failure, one error, in <subsystem>_requests_total, <subsystem>_request_duration_seconds and <subsystem>_errors_total with the attribute method. The subsystem is the recorder's, so a service names its own series (auth_endpoint_requests_total for a recorder created with NewMetricsRecorder(meter, "auth_endpoint")), and one recorder serves every endpoint of that subsystem. The generated metrics middlewares record on the same instruments with the interface name as subsystem.

func MetricsMiddleware deprecated

func MetricsMiddleware(operationName string) kitendpoint.Middleware

MetricsMiddleware is Metrics for a go-kit endpoint on a recorder for the subsystem "endpoint", created on this package's meter: the instruments are endpoint_requests_total, endpoint_errors_total and endpoint_request_duration_seconds with the attribute method. Earlier versions recorded gokit_requests_total and gokit_request_duration_seconds with the attributes operation and success.

Deprecated: use Kit(Metrics[any, any](recorder, operationName)) with a recorder for your own subsystem.

func NewFanoutHandler

func NewFanoutHandler(handlers ...slog.Handler) slog.Handler

NewFanoutHandler returns a slog.Handler that forwards each record to every handler in handlers that is enabled for the record's level. It is what InitLogs installs to keep logs visible locally while exporting them to the collector. Handle returns the errors of all failing handlers joined; one failing destination never prevents the others from receiving the record.

func NewLogger deprecated

func NewLogger(ctx context.Context, _ Config) log.Logger

NewLogger creates a new go-kit compatible logger backed by slog.

Deprecated: use NewSlogAdapter, which this function delegates to.

func NewResource

func NewResource(ctx context.Context, cfg Config) (*resource.Resource, error)

NewResource defines the standard service metadata injected into all Traces, Metrics, and Logs. Besides the attributes derived from cfg it includes the telemetry SDK attributes, host.name (unless cfg.SkipHostDetection), and honours OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES; non-empty cfg values take precedence over the environment, which takes precedence over detection.

The resource's schema URL comes from the SDK's own detectors, so it always matches the semantic-conventions version the installed SDK was built with. The environment is emitted under both deployment.environment.name (current semantic conventions) and deployment.environment (pre-1.27 name) so existing dashboards keep working.

func NewSlogAdapter

func NewSlogAdapter(ctx context.Context) log.Logger

NewSlogAdapter creates a new go-kit compatible logger backed by slog. The adapter resolves slog.Default() lazily on every Log call, so it can be constructed before InitLogs/InitTelemetry without losing OTel routing.

func Tracing added in v0.4.0

func Tracing[Req, Resp any](operationName string) middleware.Middleware[endpoint.Endpoint[Req, Resp]]

Tracing returns a middleware that wraps every call of a typed endpoint in a span named operationName, of kind internal, from the global tracer provider. An error is recorded on the span and sets its status; success leaves the status unset, as the OpenTelemetry specification asks of instrumentation.

The request and response are never inspected, so the type parameters only carry the endpoint's types through. For a go-kit endpoint instantiate with [any, any] and convert with Kit.

func TracingMiddleware deprecated

func TracingMiddleware(operationName string) kitendpoint.Middleware

TracingMiddleware is Tracing for a go-kit endpoint.

Deprecated: use Kit(Tracing[any, any](operationName)).

Types

type Config

type Config struct {
	ServiceName    string // Name of the application (e.g., "order-service")
	ServiceVersion string // Build/semantic version of the service (e.g., "1.2.4")
	Environment    string // Runtime stage (e.g., "production", "staging", "dev")

	// Endpoint is the address of the OTLP gRPC collector, either host:port
	// ("grafana-alloy.monitoring:4317") or a URL ("https://collector:4317",
	// "http://localhost:4317"). A URL's scheme decides transport security:
	// http means plaintext and https means TLS. In both forms a missing port
	// defaults to 4317, the OTLP gRPC port, rather than to the gRPC default
	// of 443.
	//
	// When set, InitTelemetry opens one gRPC connection that all three
	// exporters share. When empty, each exporter dials on its own, following
	// OTEL_EXPORTER_OTLP_ENDPOINT (and the per-signal variables) and then
	// the OTLP default, localhost:4317.
	Endpoint string

	// AlloyEndpoint is an alias for Endpoint, used only when Endpoint is empty.
	//
	// Deprecated: use Endpoint.
	AlloyEndpoint string

	// Insecure disables transport security for the exporter connections.
	// When false (the default), TLS with the system certificate pool is used.
	// Ignored when Endpoint is a URL, whose scheme decides.
	Insecure bool

	// TLSConfig configures TLS for the exporter connections: a private CA in
	// RootCAs, client certificates for mutual TLS, and so on. Nil uses the
	// system certificate pool. Ignored for plaintext connections.
	TLSConfig *tls.Config

	// Compression names the gRPC compressor used for exports: "gzip", or
	// empty for none.
	Compression string

	// DialOptions are extra gRPC options (keepalive parameters, a custom
	// resolver, ...) applied to the shared connection when Endpoint is set.
	DialOptions []grpc.DialOption

	// Headers are extra gRPC metadata sent with every export request,
	// typically used for collector authentication tokens.
	Headers map[string]string

	// TraceSampleRatio is the fraction of new traces to record, in (0, 1].
	// Child spans always follow their parent's decision. Zero leaves the SDK
	// default: OTEL_TRACES_SAMPLER when set, otherwise every trace.
	TraceSampleRatio float64

	// MaxExportBatchSize is the largest batch of spans or log records sent
	// in one export. Zero means DefaultMaxExportBatchSize.
	MaxExportBatchSize int

	// BatchTimeout is the longest a span or log record waits in a batch
	// before it is exported. Zero means DefaultBatchTimeout.
	BatchTimeout time.Duration

	// MetricInterval is how often metrics are collected and pushed. Zero
	// means DefaultMetricInterval.
	MetricInterval time.Duration

	// SkipHostDetection leaves host.name out of the resource.
	SkipHostDetection bool

	// SkipSlogDefault prevents InitLogs from replacing the process-wide
	// slog default logger with the OTel-bridged logger. The OTel logger
	// provider is still registered globally, so a custom handler can be
	// built with otelslog.NewHandler.
	SkipSlogDefault bool

	// LocalLogHandler receives every log record in addition to the OTLP
	// exporter, so logs stay visible on the machine when the collector is
	// unreachable. When nil, a text handler writing to os.Stderr is used.
	// Ignored when SkipSlogDefault or DisableLocalLogs is set.
	LocalLogHandler slog.Handler

	// LocalLogLevel is the minimum level of the default local handler. Nil
	// means slog.LevelInfo. Ignored when LocalLogHandler is set.
	LocalLogLevel slog.Leveler

	// DisableLocalLogs sends slog output to the collector only. Note that
	// slog.SetDefault also routes the standard library "log" package through
	// the default slog handler, so with this set nothing is written locally.
	DisableLocalLogs bool
}

Config represents the parameter set required to wire up your microservices to an OTLP gRPC collector (e.g. Grafana Alloy, the OpenTelemetry Collector).

type MetricsRecorder

type MetricsRecorder struct {
	// contains filtered or unexported fields
}

MetricsRecorder records request counts, error counts and latency for one subsystem (typically one decorated interface).

func NewMetricsRecorder

func NewMetricsRecorder(meter metric.Meter, subsystem string) *MetricsRecorder

NewMetricsRecorder creates the instruments <subsystem>_requests_total, <subsystem>_errors_total and <subsystem>_request_duration_seconds on meter.

func (*MetricsRecorder) Meter

func (r *MetricsRecorder) Meter() metric.Meter

Meter returns the meter the recorder's instruments were created on, so callers can add custom instruments next to them.

func (*MetricsRecorder) Observe

func (r *MetricsRecorder) Observe(ctx context.Context, method string, start time.Time, err error, attrs ...attribute.KeyValue)

Observe records one call of method that started at start: one request, its latency, and one error when err is non-nil.

type ShutdownFunc

type ShutdownFunc func(context.Context) error

ShutdownFunc safely flushes and releases OTel collectors on app termination.

func InitLogs

func InitLogs(ctx context.Context, cfg Config, res *resource.Resource) (ShutdownFunc, error)

InitLogs instantiates the OpenTelemetry logs engine, registers its logger provider globally, and, unless cfg.SkipSlogDefault is set, installs a default slog logger that writes every record both locally (cfg.LocalLogHandler, or stderr) and to the OTLP exporter, so logs carry the active trace/span IDs without disappearing from the machine when the collector is down.

func InitMetrics

func InitMetrics(ctx context.Context, cfg Config, res *resource.Resource) (ShutdownFunc, error)

InitMetrics bootstraps the periodic push metric pipeline to the collector.

func InitTelemetry

func InitTelemetry(ctx context.Context, cfg Config) (ShutdownFunc, error)

InitTelemetry simplifies bootstrap logic by configuring all three pipelines in one step, returning a composite ShutdownFunc that safely winds down the stack. When cfg.Endpoint is set the three exporters share one gRPC connection, closed by the returned ShutdownFunc.

func InitTraces

func InitTraces(ctx context.Context, cfg Config, res *resource.Resource) (ShutdownFunc, error)

InitTraces configures the global tracer provider, registers the OTLP/gRPC exporter, sets up batch processing, and initializes standard context propagators.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址