Documentation
¶
Overview ¶
Package observability provides OpenTelemetry tracing and metrics integration for comprehensive service observability.
Tracing:
tp, err := observability.InitTracer(ctx, observability.DefaultTracerConfig("my-service"))
defer tp.Shutdown(ctx)
ctx, span := observability.StartSpan(ctx, "my.operation")
defer span.End()
Metrics:
mp, err := observability.InitMeter(ctx, observability.DefaultMeterConfig("my-service"))
defer mp.Shutdown(ctx)
metrics, err := observability.NewMetrics(observability.Meter("my-service"))
metrics.RecordRequestEnd(ctx, observability.RequestMetric{Service: "my-service", Method: "GET /users", Status: "ok", Duration: duration})
Health Checks:
health := observability.NewServiceHealth("my-service", "1.0.0")
health.AddComponent(checker.CheckHealth(ctx))
Index ¶
- Constants
- func ExtractTraceContext(ctx context.Context, carrier TextMapCarrier) context.Context
- func InitMeter(ctx context.Context, config *MeterConfig) (*sdkmetric.MeterProvider, error)
- func InitTracer(ctx context.Context, config *TracerConfig) (*sdktrace.TracerProvider, error)
- func InjectTraceContext(ctx context.Context, carrier TextMapCarrier)
- func Meter(name string) metric.Meter
- func PrometheusHandler() http.Handler
- func RegisterPrometheusEndpoint(mux *http.ServeMux, path string)
- func SetSpanAttributes(ctx context.Context, attrs ...SpanAttribute)
- func SetSpanError(ctx context.Context, err error)
- func SpanFromContext(ctx context.Context) trace.Span
- func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
- func Tracer(name string) trace.Tracer
- func WithOperationContext(ctx context.Context, oc *OperationContext) context.Context
- type AuditEvent
- type Auditor
- type AuditorFunc
- type Float64Histogram
- type HeaderCarrier
- type Health
- type HealthChecker
- type HealthStatus
- type InstrumentOption
- type Int64Counter
- type MapCarrier
- type MeterConfig
- type MetricAttribute
- func MetricBoolAttribute(key string, value bool) MetricAttribute
- func MetricFloat64Attribute(key string, value float64) MetricAttribute
- func MetricInt64Attribute(key string, value int64) MetricAttribute
- func MetricIntAttribute(key string, value int) MetricAttribute
- func MetricStringAttribute(key, value string) MetricAttribute
- type Metrics
- type OTLPProtocol
- type OperationContext
- type OperationMetric
- type OperationSpec
- type RequestMetric
- type ServiceHealth
- type Span
- type SpanAttribute
- func BoolAttribute(key string, value bool) SpanAttribute
- func Float64Attribute(key string, value float64) SpanAttribute
- func Int64Attribute(key string, value int64) SpanAttribute
- func IntAttribute(key string, value int) SpanAttribute
- func StringAttribute(key, value string) SpanAttribute
- func StringSliceAttribute(key string, value []string) SpanAttribute
- type SpanKind
- type SpanOption
- type TextMapCarrier
- type TracerConfig
Constants ¶
const ( SpanHTTPRequest = "http.request" SpanGRPCCall = "grpc.call" SpanDBQuery = "db.query" )
Common span names.
const ( AttrServiceName = "service.name" AttrOperationName = "operation.name" AttrRequestID = "request.id" AttrUserID = "user.id" AttrDurationMs = "duration_ms" AttrStatus = "status" AttrErrorMessage = "error.message" )
Common attribute keys.
Variables ¶
This section is empty.
Functions ¶
func ExtractTraceContext ¶
func ExtractTraceContext(ctx context.Context, carrier TextMapCarrier) context.Context
ExtractTraceContext reads trace context from a transport carrier.
func InitMeter ¶
func InitMeter(ctx context.Context, config *MeterConfig) (*sdkmetric.MeterProvider, error)
InitMeter initializes the OpenTelemetry meter provider. Returns a MeterProvider that should be shut down on application exit.
func InitTracer ¶
func InitTracer(ctx context.Context, config *TracerConfig) (*sdktrace.TracerProvider, error)
InitTracer initializes the OpenTelemetry tracer provider. Returns a TracerProvider that should be shut down on application exit.
func InjectTraceContext ¶
func InjectTraceContext(ctx context.Context, carrier TextMapCarrier)
InjectTraceContext writes the current trace context into a transport carrier.
func PrometheusHandler ¶
PrometheusHandler returns the HTTP handler that exposes Prometheus metrics.
func RegisterPrometheusEndpoint ¶
RegisterPrometheusEndpoint registers a metrics endpoint on mux.
func SetSpanAttributes ¶
func SetSpanAttributes(ctx context.Context, attrs ...SpanAttribute)
SetSpanAttributes sets typed attributes on the current span in context.
func SetSpanError ¶
SetSpanError records an error on the current span in context.
func SpanFromContext ¶
SpanFromContext returns the span from context.
func StartSpan ¶
func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
StartSpan starts a new span using the default tracer.
func WithOperationContext ¶
func WithOperationContext(ctx context.Context, oc *OperationContext) context.Context
WithOperationContext stores an OperationContext in the context.
Types ¶
type AuditEvent ¶
type Auditor ¶
type Auditor interface {
Audit(context.Context, AuditEvent)
}
type AuditorFunc ¶
type AuditorFunc func(context.Context, AuditEvent)
func (AuditorFunc) Audit ¶
func (f AuditorFunc) Audit(ctx context.Context, event AuditEvent)
type Float64Histogram ¶
type Float64Histogram struct {
// contains filtered or unexported fields
}
Float64Histogram wraps a float64 histogram instrument.
func NewFloat64Histogram ¶
func NewFloat64Histogram(meterName, instrumentName string, opts ...InstrumentOption) (*Float64Histogram, error)
NewFloat64Histogram creates a float64 histogram from the named meter.
func (*Float64Histogram) Record ¶
func (h *Float64Histogram) Record(ctx context.Context, value float64, attrs ...MetricAttribute)
Record records a histogram value.
type HeaderCarrier ¶
HeaderCarrier adapts HTTP headers for trace propagation.
func (HeaderCarrier) Get ¶
func (c HeaderCarrier) Get(key string) string
Get returns the carrier value for key.
func (HeaderCarrier) Set ¶
func (c HeaderCarrier) Set(key, value string)
Set stores value under key.
type Health ¶
type Health struct {
Name string `json:"name"`
Status HealthStatus `json:"status"`
Message string `json:"message,omitempty"`
Details map[string]string `json:"details,omitempty"`
}
Health describes the health of an individual component.
type HealthChecker ¶
HealthChecker is implemented by components that can report their health.
type HealthStatus ¶
type HealthStatus string
HealthStatus represents the health state of a component or service.
const ( HealthStatusUp HealthStatus = "up" HealthStatusDown HealthStatus = "down" HealthStatusDegraded HealthStatus = "degraded" )
type InstrumentOption ¶
type InstrumentOption func(*instrumentOptions)
InstrumentOption configures a metric instrument.
func WithInstrumentDescription ¶
func WithInstrumentDescription(description string) InstrumentOption
WithInstrumentDescription sets the instrument description.
func WithInstrumentUnit ¶
func WithInstrumentUnit(unit string) InstrumentOption
WithInstrumentUnit sets the instrument unit.
type Int64Counter ¶
type Int64Counter struct {
// contains filtered or unexported fields
}
Int64Counter wraps an int64 counter instrument.
func NewInt64Counter ¶
func NewInt64Counter(meterName, instrumentName string, opts ...InstrumentOption) (*Int64Counter, error)
NewInt64Counter creates an int64 counter from the named meter.
func (*Int64Counter) Add ¶
func (c *Int64Counter) Add(ctx context.Context, value int64, attrs ...MetricAttribute)
Add records a counter increment.
type MapCarrier ¶
MapCarrier adapts map-backed message headers for trace propagation.
func (MapCarrier) Get ¶
func (c MapCarrier) Get(key string) string
Get returns the carrier value for key.
type MeterConfig ¶
type MeterConfig struct {
// ServiceName is the name of the service.
ServiceName string
// ServiceVersion is the version of the service.
ServiceVersion string
// Environment is the deployment environment (dev, staging, prod).
Environment string
// Endpoint is the OTLP endpoint host:port (e.g., "localhost:4318" for HTTP, "localhost:4317" for gRPC).
Endpoint string
// Protocol selects the OTLP wire protocol (HTTP or gRPC). Defaults to HTTP.
Protocol OTLPProtocol
// Insecure allows insecure connections (for development).
Insecure bool
// Interval is the metric export interval.
Interval time.Duration
// SkipGlobalRegistration, when true,
// prevents InitMeter from mutating the global otel.SetMeterProvider state.
// See TracerConfig.SkipGlobalRegistration.
SkipGlobalRegistration bool
}
MeterConfig configures the OpenTelemetry meter provider.
func DefaultMeterConfig ¶
func DefaultMeterConfig(serviceName string) MeterConfig
DefaultMeterConfig returns sensible defaults for development.
type MetricAttribute ¶
type MetricAttribute struct {
// contains filtered or unexported fields
}
MetricAttribute is a typed, transport-neutral metric attribute.
func MetricBoolAttribute ¶
func MetricBoolAttribute(key string, value bool) MetricAttribute
MetricBoolAttribute creates a bool metric attribute.
func MetricFloat64Attribute ¶
func MetricFloat64Attribute(key string, value float64) MetricAttribute
MetricFloat64Attribute creates a float64 metric attribute.
func MetricInt64Attribute ¶
func MetricInt64Attribute(key string, value int64) MetricAttribute
MetricInt64Attribute creates an int64 metric attribute.
func MetricIntAttribute ¶
func MetricIntAttribute(key string, value int) MetricAttribute
MetricIntAttribute creates an int metric attribute.
func MetricStringAttribute ¶
func MetricStringAttribute(key, value string) MetricAttribute
MetricStringAttribute creates a string metric attribute.
type Metrics ¶
type Metrics struct {
// contains filtered or unexported fields
}
Metrics holds OpenTelemetry metric instruments for common service observability.
func NewMetrics ¶
NewMetrics creates metric instruments on the given meter.
func (*Metrics) RecordError ¶
RecordError records an error by type and component.
func (*Metrics) RecordOperation ¶
func (m *Metrics) RecordOperation(ctx context.Context, op OperationMetric)
RecordOperation records an operation execution.
func (*Metrics) RecordRequestEnd ¶
func (m *Metrics) RecordRequestEnd(ctx context.Context, r RequestMetric)
RecordRequestEnd decrements active requests and records the completed request.
func (*Metrics) RecordRequestStart ¶
RecordRequestStart increments the active request count.
type OTLPProtocol ¶
type OTLPProtocol int
OTLPProtocol selects the OTLP exporter wire protocol for traces and metrics. It lets callers pick the transport their collector exposes instead of being locked to HTTP, matching the protocol selection in the sibling kits.
const ( // OTLPHTTP exports over OTLP/HTTP with protobuf payloads (default; collector port 4318). OTLPHTTP OTLPProtocol = iota // OTLPGRPC exports over OTLP/gRPC (collector port 4317). OTLPGRPC )
func ParseOTLPProtocol ¶
func ParseOTLPProtocol(value string) (OTLPProtocol, error)
ParseOTLPProtocol maps a config string ("grpc"/"otlp/grpc", "http"/"http/protobuf", or "") to a protocol. An empty value defaults to OTLPHTTP; any other unrecognized value is rejected so a typo such as "grcp" fails configuration instead of silently exporting over the wrong transport.
func (OTLPProtocol) String ¶
func (p OTLPProtocol) String() string
String returns the canonical lowercase name of the protocol.
func (OTLPProtocol) Validate ¶
func (p OTLPProtocol) Validate() error
Validate rejects a protocol value outside the known set, so a directly-assigned enum cannot select an unintended exporter at export time.
type OperationContext ¶
type OperationContext struct {
ServiceName string
OperationName string
RequestID string
UserID string
StartTime time.Time
Metrics *Metrics
}
OperationContext holds observability context for a tracked operation.
func NewOperationContext ¶
func NewOperationContext(spec OperationSpec) *OperationContext
NewOperationContext creates a new operation context from spec. If spec.Metrics is nil, metric recording is silently skipped.
func OperationContextFromContext ¶
func OperationContextFromContext(ctx context.Context) *OperationContext
OperationContextFromContext retrieves the OperationContext from context, or nil.
func (*OperationContext) Duration ¶
func (oc *OperationContext) Duration() time.Duration
Duration returns the elapsed time since operation start.
func (*OperationContext) EndOperation ¶
func (oc *OperationContext) EndOperation(ctx context.Context, span trace.Span, status string, err error)
EndOperation ends the span and records request-end metrics.
func (*OperationContext) StartSpanForOperation ¶
func (oc *OperationContext) StartSpanForOperation(ctx context.Context, spanName string) (context.Context, trace.Span)
StartSpanForOperation starts a traced span and records the request start metric.
type OperationMetric ¶
type OperationMetric struct {
Service string
Operation string
Status string
Duration time.Duration
}
OperationMetric describes an executed operation for Metrics.RecordOperation.
type OperationSpec ¶
type OperationSpec struct {
ServiceName string
OperationName string
RequestID string
UserID string
Metrics *Metrics
}
OperationSpec identifies a tracked operation for NewOperationContext. Metrics may be nil to silently skip metric recording.
type RequestMetric ¶
RequestMetric describes a completed request for Metrics.RecordRequestEnd.
type ServiceHealth ¶
type ServiceHealth struct {
Service string `json:"service"`
Status HealthStatus `json:"status"`
Version string `json:"version,omitempty"`
Components []Health `json:"components,omitempty"`
}
ServiceHealth describes the overall health of a service and its components.
func NewServiceHealth ¶
func NewServiceHealth(service, version string) *ServiceHealth
NewServiceHealth creates a ServiceHealth with status up.
func (*ServiceHealth) AddComponent ¶
func (sh *ServiceHealth) AddComponent(ch Health)
AddComponent adds a component health result and degrades overall status if needed.
type Span ¶
type Span struct {
// contains filtered or unexported fields
}
Span wraps an OpenTelemetry span behind the kit observability API.
func StartNamedSpan ¶
func StartNamedSpan(ctx context.Context, tracerName, spanName string, opts ...SpanOption) (context.Context, *Span)
StartNamedSpan starts a span from a named tracer.
func (*Span) RecordError ¶
RecordError records err on the span.
func (*Span) SetAttributes ¶
func (s *Span) SetAttributes(attrs ...SpanAttribute)
SetAttributes sets attributes on the span.
type SpanAttribute ¶
type SpanAttribute struct {
// contains filtered or unexported fields
}
SpanAttribute is a typed, transport-neutral span attribute.
func BoolAttribute ¶
func BoolAttribute(key string, value bool) SpanAttribute
BoolAttribute creates a bool span attribute.
func Float64Attribute ¶
func Float64Attribute(key string, value float64) SpanAttribute
Float64Attribute creates a float64 span attribute.
func Int64Attribute ¶
func Int64Attribute(key string, value int64) SpanAttribute
Int64Attribute creates an int64 span attribute.
func IntAttribute ¶
func IntAttribute(key string, value int) SpanAttribute
IntAttribute creates an int span attribute.
func StringAttribute ¶
func StringAttribute(key, value string) SpanAttribute
StringAttribute creates a string span attribute.
func StringSliceAttribute ¶
func StringSliceAttribute(key string, value []string) SpanAttribute
StringSliceAttribute creates a string-slice span attribute.
type SpanKind ¶
type SpanKind int
SpanKind identifies the role a span plays in a distributed trace.
const ( // SpanKindInternal is for work internal to a process. SpanKindInternal SpanKind = iota // SpanKindServer is for inbound request handling. SpanKindServer // SpanKindClient is for outbound requests. SpanKindClient // SpanKindProducer is for message production. SpanKindProducer // SpanKindConsumer is for message consumption. SpanKindConsumer )
type SpanOption ¶
type SpanOption func(*spanOptions)
SpanOption configures a span without exposing OpenTelemetry option types.
func WithSpanAttributes ¶
func WithSpanAttributes(attrs ...SpanAttribute) SpanOption
WithSpanAttributes adds attributes to the span.
type TextMapCarrier ¶
TextMapCarrier is the transport-neutral carrier used for trace propagation.
type TracerConfig ¶
type TracerConfig struct {
// ServiceName is the name of the service.
ServiceName string
// ServiceVersion is the version of the service.
ServiceVersion string
// Environment is the deployment environment (dev, staging, prod).
Environment string
// Endpoint is the OTLP endpoint host:port (e.g., "localhost:4318" for HTTP, "localhost:4317" for gRPC).
Endpoint string
// Protocol selects the OTLP wire protocol (HTTP or gRPC). Defaults to HTTP.
Protocol OTLPProtocol
// Insecure allows insecure connections (for development).
Insecure bool
// SampleRate is the sampling rate (0.0 to 1.0).
SampleRate float64
// SkipGlobalRegistration, when true,
// prevents InitTracer from mutating the global otel.SetTracerProvider / otel.SetTextMapPropagator state.
// Callers that want to thread the returned *TracerProvider through DI can opt out of process-global state.
// Defaults to false to preserve the convenient "init once,
// instrument anywhere via observability.Tracer(...)" pattern.
SkipGlobalRegistration bool
}
TracerConfig configures the OpenTelemetry tracer.
func DefaultTracerConfig ¶
func DefaultTracerConfig(serviceName string) TracerConfig
DefaultTracerConfig returns sensible defaults for development.