observability

package
v0.0.0-...-05004e4 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: Apache-2.0, Apache-2.0 Imports: 32 Imported by: 0

Documentation

Overview

Package observability provides OpenTelemetry-based tracing, metrics, and structured logging for all Codefang application modes (CLI, MCP, server).

Index

Constants

View Source
const (
	ErrTypeTimeout               = "timeout"
	ErrTypeCancel                = "cancel"
	ErrTypeValidation            = "validation"
	ErrTypeDependencyUnavailable = "dependency_unavailable"
	ErrTypeInternal              = "internal"
)

Error type classification constants per OTel semantic conventions.

View Source
const (
	ErrSourceClient     = "client"
	ErrSourceServer     = "server"
	ErrSourceDependency = "dependency"
)

Error source classification constants.

Variables

This section is empty.

Functions

func HTTPMiddleware

func HTTPMiddleware(tracer trace.Tracer, logger *slog.Logger, next http.Handler) http.Handler

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

func HealthHandler() http.Handler

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

func ParseOTLPHeaders(raw string) map[string]string

ParseOTLPHeaders parses an OTLP headers string in "key=value,key=value" format. Returns nil for empty or invalid input.

func PrometheusHandler

func PrometheusHandler() (http.Handler, error)

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

func RecordSpanError(span trace.Span, err error, errType, errSource string)

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 AppMode

type AppMode string

AppMode identifies the application execution mode.

const (
	// ModeCLI is the CLI command execution mode.
	ModeCLI AppMode = "cli"
	// ModeMCP is the MCP stdio server mode.
	ModeMCP AppMode = "mcp"
	// ModeServe is the HTTP/gRPC server mode.
	ModeServe AppMode = "serve"
)

type CacheStatsProvider

type CacheStatsProvider interface {
	CacheHits() int64
	CacheMisses() int64
}

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.

func Init

func Init(cfg Config) (Providers, error)

Init initializes OpenTelemetry tracing, metrics, and structured logging. When OTLPEndpoint is empty, no-op providers are used with zero export overhead.

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

func (rm *REDMetrics) RecordRequest(ctx context.Context, op, status string, duration time.Duration)

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

type ReadyCheck func(ctx context.Context) error

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) Enabled

func (th *TracingHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled delegates to the inner handler.

func (*TracingHandler) Handle

func (th *TracingHandler) Handle(ctx context.Context, record slog.Record) error

Handle adds trace context attributes from the span context, then delegates.

func (*TracingHandler) WithAttrs

func (th *TracingHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new TracingHandler with additional attributes on the inner handler.

func (*TracingHandler) WithGroup

func (th *TracingHandler) WithGroup(name string) slog.Handler

WithGroup returns a new TracingHandler with a group prefix on the inner handler.

Jump to

Keyboard shortcuts

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