telemetry

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: Apache-2.0 Imports: 35 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package telemetry wires OpenTelemetry tracing, metrics and logs for the server, and provides the HTTP middleware and tool metrics built on them.

Index

Constants

View Source
const (
	ProtocolGRPC         = "grpc"
	ProtocolHTTPProtobuf = "http/protobuf"
	ProtocolHTTPJSON     = "http/json"
)

OTLP protocols accepted in Config.Protocol and the OTEL_EXPORTER_OTLP_*PROTOCOL variables.

View Source
const (
	OutcomeSuccess = "success"
	OutcomeError   = "error"
)

Tool outcomes passed to Timer.Stop and recorded on ToolInvocation.Outcome.

View Source
const (

	// DefaultServiceName is the service.name reported when OTEL_SERVICE_NAME is unset.
	DefaultServiceName = "dapr-mcp-server"

	// DefaultServiceVersion is the service.version reported when neither
	// OTEL_SERVICE_VERSION nor WithServiceVersion supplies one.
	DefaultServiceVersion = "unknown"
)

Variables

This section is empty.

Functions

func HTTPMiddleware

func HTTPMiddleware(next http.Handler, logger *slog.Logger, httpMetrics *HTTPMetrics) http.Handler

HTTPMiddleware returns HTTP middleware that creates a server span and records metrics for each request.

Spans and metrics are labeled with the route pattern the ServeMux matched (http.Request.Pattern), never the raw path, so arbitrary paths cannot create unbounded series. Requests with no matched pattern carry no route label. The raw path is kept only as the span's url.path attribute.

Server-sent event streams are counted but left out of the duration histogram, since their duration is the client's session length rather than latency.

func Initialize

func Initialize(ctx context.Context, opts ...Option) (func(context.Context) error, error)

Initialize initializes OpenTelemetry with DefaultConfig and returns a shutdown function.

func ParseLogLevel

func ParseLogLevel(name string) slog.Level

ParseLogLevel maps a case-insensitive level name to a slog.Level, defaulting to Info for empty or unrecognized names.

Types

type Config

type Config struct {
	ServiceName    string
	ServiceVersion string
	Endpoint       string
	Protocol       string // ProtocolGRPC or ProtocolHTTPProtobuf
	Headers        map[string]string
	MetricsEnabled bool
	LogsEnabled    bool
	// Insecure selects plaintext for an Endpoint given without a scheme.
	// An explicit http:// or https:// scheme always wins.
	Insecure bool
}

Config holds the telemetry configuration.

Endpoint, Protocol, Insecure and Headers are the generic OTLP settings. The signal-specific OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_* variables override them per signal when Init runs.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a configuration from the generic OTEL_* environment variables.

type HTTPMetrics

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

HTTPMetrics provides metrics instrumentation for HTTP requests. A nil *HTTPMetrics is valid and records nothing.

func NewHTTPMetrics

func NewHTTPMetrics() (*HTTPMetrics, error)

NewHTTPMetrics creates a new HTTPMetrics instance on the global meter provider.

func (*HTTPMetrics) EndRequest

func (m *HTTPMetrics) EndRequest()

EndRequest decrements in-flight counter.

func (*HTTPMetrics) RecordRequest

func (m *HTTPMetrics) RecordRequest(method, route string, statusCode int, durationMs float64)

RecordRequest records a completed HTTP request. route must be a bounded route template such as "/" or "/items/{id}", never the raw request path; pass "" when no route matched.

func (*HTTPMetrics) StartRequest

func (m *HTTPMetrics) StartRequest()

StartRequest increments in-flight counter.

type OTELHandler

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

OTELHandler is a slog.Handler that sends every record to both an OTEL logger and an inner handler, such as a JSON handler on stderr.

Groups opened with WithGroup qualify later keys with a dot-joined prefix in the OTEL record, matching how slog's built-in handlers render them.

func NewOTELHandler

func NewOTELHandler(provider *sdklog.LoggerProvider, inner slog.Handler) *OTELHandler

NewOTELHandler creates a new OTELHandler that sends logs to both OTEL and the inner handler.

func (*OTELHandler) Enabled

func (h *OTELHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled implements slog.Handler. The inner handler's level decides for both sinks.

func (*OTELHandler) Handle

func (h *OTELHandler) Handle(ctx context.Context, record slog.Record) error

Handle implements slog.Handler.

func (*OTELHandler) WithAttrs

func (h *OTELHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs implements slog.Handler. It never modifies h.

func (*OTELHandler) WithGroup

func (h *OTELHandler) WithGroup(name string) slog.Handler

WithGroup implements slog.Handler. It never modifies h.

type Option

type Option func(*options)

Option customizes Initialize.

func WithServiceVersion

func WithServiceVersion(version string) Option

WithServiceVersion sets the service.version reported when OTEL_SERVICE_VERSION is unset, typically the version stamped into the binary at build time.

type ResponseWriterWrapper

type ResponseWriterWrapper struct {
	http.ResponseWriter
	StatusCode int
	Written    int64
	// contains filtered or unexported fields
}

ResponseWriterWrapper wraps http.ResponseWriter to capture the status code and the number of body bytes written.

func NewResponseWriterWrapper

func NewResponseWriterWrapper(w http.ResponseWriter) *ResponseWriterWrapper

NewResponseWriterWrapper creates a new ResponseWriterWrapper.

func (*ResponseWriterWrapper) Flush

func (w *ResponseWriterWrapper) Flush()

Flush implements http.Flusher by delegating to the underlying ResponseWriter. This is critical for SSE (text/event-stream) responses used by the MCP Streamable HTTP transport. Without this, Go buffers the entire response, sets Content-Length and Connection: keep-alive, which causes MCP clients to block waiting for more events that never arrive. It does nothing when the underlying writer cannot flush.

func (*ResponseWriterWrapper) Hijack

Hijack implements http.Hijacker by delegating to the underlying ResponseWriter. It returns an error wrapping http.ErrNotSupported when that writer cannot be hijacked.

func (*ResponseWriterWrapper) Unwrap

Unwrap returns the original ResponseWriter.

func (*ResponseWriterWrapper) Write

func (w *ResponseWriterWrapper) Write(b []byte) (int, error)

Write captures the number of bytes written. Writing before WriteHeader implies 200.

func (*ResponseWriterWrapper) WriteHeader

func (w *ResponseWriterWrapper) WriteHeader(statusCode int)

WriteHeader captures the status code. Like net/http, it ignores every call after the first final status; informational 1xx headers pass through.

type Telemetry

type Telemetry struct {
	TracerProvider *sdktrace.TracerProvider
	MeterProvider  *sdkmetric.MeterProvider
	LoggerProvider *sdklog.LoggerProvider
	Logger         *slog.Logger
	// contains filtered or unexported fields
}

Telemetry holds the telemetry providers.

func Init

func Init(ctx context.Context, cfg Config) (*Telemetry, error)

Init initializes OpenTelemetry with the given configuration. Each signal is exported only when it has an endpoint, from either cfg.Endpoint or its signal-specific variable.

func (*Telemetry) Shutdown

func (t *Telemetry) Shutdown(ctx context.Context) error

Shutdown flushes and stops every provider and returns all of their errors joined.

Providers stop in the order they were started: traces, metrics, then logs. Logs go last so that errors logged while the others flush are still exported; once the log provider is down, records still reach stderr through the base handler.

type Timer

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

Timer measures one tool execution. Only the first Stop records anything, and a Timer from a nil *ToolMetrics is a usable no-op.

func (*Timer) Stop

func (t *Timer) Stop(outcome string)

Stop records the invocation, its duration and, for OutcomeError, an error. Calls after the first are ignored.

type ToolInvocation

type ToolInvocation struct {
	ToolName    string
	ToolPackage string
	Outcome     string
}

ToolInvocation represents attributes for a tool invocation.

type ToolMetrics

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

ToolMetrics provides metrics instrumentation for tool invocations. A nil *ToolMetrics is valid and records nothing.

func NewToolMetrics

func NewToolMetrics() (*ToolMetrics, error)

NewToolMetrics creates a new ToolMetrics instance on the global meter provider.

func (*ToolMetrics) EndInProgress

func (m *ToolMetrics) EndInProgress(ctx context.Context, toolName, toolPackage string)

EndInProgress marks a tool as completed.

func (*ToolMetrics) RecordDuration

func (m *ToolMetrics) RecordDuration(ctx context.Context, inv ToolInvocation, durationMs float64)

RecordDuration records tool execution duration.

func (*ToolMetrics) RecordError

func (m *ToolMetrics) RecordError(ctx context.Context, inv ToolInvocation, errorType string)

RecordError records a tool error.

func (*ToolMetrics) RecordInvocation

func (m *ToolMetrics) RecordInvocation(ctx context.Context, inv ToolInvocation)

RecordInvocation records a tool invocation with its attributes.

func (*ToolMetrics) StartInProgress

func (m *ToolMetrics) StartInProgress(ctx context.Context, toolName, toolPackage string)

StartInProgress marks a tool as in-progress.

func (*ToolMetrics) StartTimer

func (m *ToolMetrics) StartTimer(ctx context.Context, toolName, toolPackage string) *Timer

StartTimer marks the tool in progress and starts timing it. The timer keeps ctx's values but not its cancellation, so a canceled request still has its outcome recorded.

Jump to

Keyboard shortcuts

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