Documentation
¶
Overview ¶
Package observability provides OpenTelemetry-based tracing, metrics, and structured logging for all Codefang application modes (CLI, MCP, server).
Index ¶
- Constants
- func HTTPMiddleware(tracer trace.Tracer, logger *slog.Logger, next http.Handler) http.Handler
- func HealthHandler() http.Handler
- func NewAttributeFilter(delegate sdktrace.SpanProcessor, logger *slog.Logger) sdktrace.SpanProcessor
- func NewFilteringTracerProvider(delegate trace.TracerProvider) trace.TracerProvider
- func ParseOTLPHeaders(raw string) map[string]string
- func PrometheusHandler() (http.Handler, error)
- func ReadyHandler(checks ...ReadyCheck) http.Handler
- func RecordSpanError(span trace.Span, err error, errType, errSource string)
- func RegisterCacheMetrics(mt metric.Meter, blob, diff CacheStatsProvider) error
- type AnalysisMetrics
- type AnalysisStats
- type AppMode
- type CacheStatsProvider
- type Config
- type Providers
- type REDMetrics
- type ReadyCheck
- type SchedulerMetrics
- type TracingHandler
Constants ¶
const ( ErrTypeTimeout = "timeout" ErrTypeCancel = "cancel" ErrTypeValidation = "validation" ErrTypeInternal = "internal" )
Error type classification constants per OTel semantic conventions.
const ( ErrSourceClient = "client" ErrSourceServer = "server" ErrSourceDependency = "dependency" )
Error source classification constants.
Variables ¶
This section is empty.
Functions ¶
func HTTPMiddleware ¶
HTTPMiddleware returns an http.Handler that creates a span per request, emits a one-line access log, and recovers panics. Span names use route-template format: "METHOD /path".
func HealthHandler ¶
HealthHandler returns an http.Handler for liveness checks at /healthz. It always returns HTTP 200 with {"status":"ok"}.
func NewAttributeFilter ¶
func NewAttributeFilter(delegate sdktrace.SpanProcessor, logger *slog.Logger) sdktrace.SpanProcessor
NewAttributeFilter returns a SpanProcessor that filters span attributes. Allowed attributes pass through; blocked attributes (user.*, email, request.body, response.body) are stripped. When logger is non-nil, blocked attributes are logged as warnings (intended for dev mode).
func NewFilteringTracerProvider ¶
func NewFilteringTracerProvider(delegate trace.TracerProvider) trace.TracerProvider
NewFilteringTracerProvider wraps delegate so that hot-path spans are replaced with no-op spans. This drops per-commit/per-file/per-git-op spans while preserving structural pipeline spans.
func ParseOTLPHeaders ¶
ParseOTLPHeaders parses an OTLP headers string in "key=value,key=value" format. Returns nil for empty or invalid input.
func PrometheusHandler ¶
PrometheusHandler creates a Prometheus metrics exporter backed by an OTel MeterProvider and returns an http.Handler that serves the /metrics scrape endpoint. Each call creates an independent Prometheus registry to avoid collector conflicts when called multiple times.
func ReadyHandler ¶
func ReadyHandler(checks ...ReadyCheck) http.Handler
ReadyHandler returns an http.Handler for readiness checks at /readyz. It runs all provided checks; if any fail, it returns HTTP 503 with {"status":"unavailable"}. If no checks are provided or all pass, it returns HTTP 200 with {"status":"ok"}.
func RecordSpanError ¶
RecordSpanError records an error on a span with structured classification attributes (error.type and optionally error.source).
func RegisterCacheMetrics ¶
func RegisterCacheMetrics(mt metric.Meter, blob, diff CacheStatsProvider) error
RegisterCacheMetrics registers observable gauges that report cache hit/miss counters from blob and diff caches. Either provider may be nil.
Types ¶
type AnalysisMetrics ¶
type AnalysisMetrics struct {
// contains filtered or unexported fields
}
AnalysisMetrics holds OTel instruments for analysis-specific metrics.
func NewAnalysisMetrics ¶
func NewAnalysisMetrics(mt metric.Meter) (*AnalysisMetrics, error)
NewAnalysisMetrics creates analysis metric instruments from the given meter.
func (*AnalysisMetrics) RecordRun ¶
func (am *AnalysisMetrics) RecordRun(ctx context.Context, stats AnalysisStats)
RecordRun records analysis statistics for a completed streaming run. Safe to call on a nil receiver (no-op).
type AnalysisStats ¶
type AnalysisStats struct {
Commits int64
Chunks int
ChunkDurations []time.Duration
BlobCacheHits int64
BlobCacheMisses int64
DiffCacheHits int64
DiffCacheMisses int64
}
AnalysisStats holds the statistics for a single streaming run, decoupled from framework types.
type CacheStatsProvider ¶
CacheStatsProvider exposes cache hit/miss counters for OTel export.
type Config ¶
type Config struct {
// ServiceName is the OTel resource service name.
ServiceName string
// ServiceVersion is the semantic version of the running binary.
ServiceVersion string
// Environment is the deployment environment (e.g. "production", "staging", "dev").
Environment string
// Mode identifies how the binary was launched.
Mode AppMode
// OTLPEndpoint is the OTLP gRPC collector address (e.g. "localhost:4317").
// Empty disables export; providers become no-op.
OTLPEndpoint string
// OTLPHeaders are additional gRPC metadata headers for the OTLP exporter.
OTLPHeaders map[string]string
// OTLPInsecure disables TLS for the OTLP gRPC connection.
OTLPInsecure bool
// DebugTrace forces 100% trace sampling when true.
DebugTrace bool
// SampleRatio is the trace sampling ratio (0.0 to 1.0) when DebugTrace is false.
// Zero uses the OTel SDK default (parent-based with always-on root).
SampleRatio float64
// LogLevel controls the minimum slog severity.
LogLevel slog.Level
// TraceVerbose enables hot-path spans (per-commit, per-file, per-git-op).
// When false (default), only structural pipeline spans are recorded.
TraceVerbose bool
// LogJSON enables JSON-formatted log output.
LogJSON bool
// ShutdownTimeoutSec is the maximum seconds to wait for flush on shutdown.
ShutdownTimeoutSec int
}
Config holds all observability configuration.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults for zero-config startup.
type Providers ¶
type Providers struct {
// Tracer is the named tracer for creating spans.
Tracer trace.Tracer
// Meter is the named meter for creating instruments.
Meter metric.Meter
// Logger is the context-aware structured logger.
Logger *slog.Logger
// Shutdown flushes all pending telemetry and releases resources.
// Must be called before process exit.
Shutdown func(ctx context.Context) error
}
Providers holds the initialized observability providers.
type REDMetrics ¶
type REDMetrics struct {
// contains filtered or unexported fields
}
REDMetrics holds the OTel instruments for Rate, Error, Duration metrics.
func NewREDMetrics ¶
func NewREDMetrics(mt metric.Meter) (*REDMetrics, error)
NewREDMetrics creates RED metric instruments from the given meter.
func (*REDMetrics) RecordRequest ¶
RecordRequest records a completed request with its operation, status, and duration.
func (*REDMetrics) TrackInflight ¶
func (rm *REDMetrics) TrackInflight(ctx context.Context, op string) func()
TrackInflight increments the in-flight gauge and returns a function to decrement it.
type ReadyCheck ¶
ReadyCheck is a function that checks if a subsystem is ready. It returns nil if the check passes, or an error describing the failure.
type SchedulerMetrics ¶
type SchedulerMetrics struct {
// contains filtered or unexported fields
}
SchedulerMetrics exposes Go runtime scheduler metrics as OTel instruments. Goroutine and thread counts are read from runtime/metrics on each collection cycle.
func NewSchedulerMetrics ¶
func NewSchedulerMetrics(mt metric.Meter) (*SchedulerMetrics, error)
NewSchedulerMetrics creates OTel instruments backed by Go 1.26 runtime/metrics. The meter's periodic reader invokes the callback automatically; no manual polling is needed.
type TracingHandler ¶
type TracingHandler struct {
// contains filtered or unexported fields
}
TracingHandler is an slog.Handler that injects OpenTelemetry trace context (trace_id, span_id) and service metadata into every log record. Service attributes (service, env, mode) are pre-attached at construction so they remain at the top level even when groups are used.
func NewTracingHandler ¶
func NewTracingHandler(inner slog.Handler, service, env string, appMode AppMode) *TracingHandler
NewTracingHandler wraps an slog.Handler, injecting trace context and service metadata. Service attributes are pre-attached to the inner handler so they appear at the top level regardless of subsequent WithGroup calls.
func (*TracingHandler) Handle ¶
Handle adds trace context attributes from the span context, then delegates.