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
- func HTTPMiddleware(next http.Handler, logger *slog.Logger, httpMetrics *HTTPMetrics) http.Handler
- func Initialize(ctx context.Context, opts ...Option) (func(context.Context) error, error)
- func ParseLogLevel(name string) slog.Level
- type Config
- type HTTPMetrics
- type OTELHandler
- type Option
- type ResponseWriterWrapper
- type Telemetry
- type Timer
- type ToolInvocation
- type ToolMetrics
- func (m *ToolMetrics) EndInProgress(ctx context.Context, toolName, toolPackage string)
- func (m *ToolMetrics) RecordDuration(ctx context.Context, inv ToolInvocation, durationMs float64)
- func (m *ToolMetrics) RecordError(ctx context.Context, inv ToolInvocation, errorType string)
- func (m *ToolMetrics) RecordInvocation(ctx context.Context, inv ToolInvocation)
- func (m *ToolMetrics) StartInProgress(ctx context.Context, toolName, toolPackage string)
- func (m *ToolMetrics) StartTimer(ctx context.Context, toolName, toolPackage string) *Timer
Constants ¶
const ( ProtocolGRPC = "grpc" ProtocolHTTPProtobuf = "http/protobuf" ProtocolHTTPJSON = "http/json" )
OTLP protocols accepted in Config.Protocol and the OTEL_EXPORTER_OTLP_*PROTOCOL variables.
const ( OutcomeSuccess = "success" OutcomeError = "error" )
Tool outcomes passed to Timer.Stop and recorded on ToolInvocation.Outcome.
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 ¶
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 ¶
Initialize initializes OpenTelemetry with DefaultConfig and returns a shutdown function.
func ParseLogLevel ¶
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 ¶
Enabled implements slog.Handler. The inner handler's level decides for both sinks.
type Option ¶
type Option func(*options)
Option customizes Initialize.
func WithServiceVersion ¶
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 ¶
func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error)
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 ¶
func (w *ResponseWriterWrapper) Unwrap() http.ResponseWriter
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 ¶
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 ¶
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.
type ToolInvocation ¶
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.