observability

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2025 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package observability provides OpenTelemetry tracing, metrics, and health monitoring.

Index

Constants

View Source
const (
	AttrPackageID      = attribute.Key("nuget.package.id")
	AttrPackageVersion = attribute.Key("nuget.package.version")
	AttrSourceURL      = attribute.Key("nuget.source.url")
	AttrFramework      = attribute.Key("nuget.framework")
	AttrOperation      = attribute.Key("nuget.operation")
	AttrCacheHit       = attribute.Key("nuget.cache.hit")
	AttrRetryCount     = attribute.Key("nuget.retry.count")
)

Common attribute keys

View Source
const (
	// TracerName is the tracer name for gonuget operations
	TracerName = "github.com/willibrandon/gonuget"
)

Variables

View Source
var (
	// HTTPRequestsTotal counts HTTP requests by method, status code, and source
	HTTPRequestsTotal = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "gonuget_http_requests_total",
			Help: "Total number of HTTP requests by method and status",
		},
		[]string{"method", "status_code", "source"},
	)

	// HTTPRequestDuration tracks HTTP request duration in seconds
	HTTPRequestDuration = promauto.NewHistogramVec(
		prometheus.HistogramOpts{
			Name:    "gonuget_http_request_duration_seconds",
			Help:    "HTTP request duration in seconds",
			Buckets: prometheus.ExponentialBuckets(0.001, 2, 15),
		},
		[]string{"method", "source"},
	)

	// CacheHitsTotal counts cache hits by cache tier
	CacheHitsTotal = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "gonuget_cache_hits_total",
			Help: "Total number of cache hits by cache tier",
		},
		[]string{"tier"},
	)

	// CacheMissesTotal counts cache misses by cache tier
	CacheMissesTotal = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "gonuget_cache_misses_total",
			Help: "Total number of cache misses by cache tier",
		},
		[]string{"tier"},
	)

	// CacheSizeBytes tracks current cache size in bytes by tier
	CacheSizeBytes = promauto.NewGaugeVec(
		prometheus.GaugeOpts{
			Name: "gonuget_cache_size_bytes",
			Help: "Current cache size in bytes by tier",
		},
		[]string{"tier"},
	)

	// PackageDownloadsTotal counts package downloads by status
	PackageDownloadsTotal = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "gonuget_package_downloads_total",
			Help: "Total number of package downloads by status",
		},
		[]string{"status"},
	)

	// PackageDownloadDuration tracks package download duration in seconds
	PackageDownloadDuration = promauto.NewHistogramVec(
		prometheus.HistogramOpts{
			Name:    "gonuget_package_download_duration_seconds",
			Help:    "Package download duration in seconds",
			Buckets: prometheus.ExponentialBuckets(0.1, 2, 12),
		},
		[]string{"package_id"},
	)

	// CircuitBreakerState tracks circuit breaker state by host
	CircuitBreakerState = promauto.NewGaugeVec(
		prometheus.GaugeOpts{
			Name: "gonuget_circuit_breaker_state",
			Help: "Circuit breaker state (0=closed, 1=open, 2=half-open)",
		},
		[]string{"host"},
	)

	// CircuitBreakerFailures counts circuit breaker failures
	CircuitBreakerFailures = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "gonuget_circuit_breaker_failures_total",
			Help: "Total number of circuit breaker failures",
		},
		[]string{"host"},
	)

	// RateLimitRequestsTotal counts rate limited requests
	RateLimitRequestsTotal = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "gonuget_rate_limit_requests_total",
			Help: "Total number of rate limited requests",
		},
		[]string{"source", "allowed"},
	)

	// RateLimitTokens tracks current number of available rate limit tokens
	RateLimitTokens = promauto.NewGaugeVec(
		prometheus.GaugeOpts{
			Name: "gonuget_rate_limit_tokens",
			Help: "Current number of available rate limit tokens",
		},
		[]string{"source"},
	)
)

Functions

func AddEvent

func AddEvent(ctx context.Context, name string, attrs ...attribute.KeyValue)

AddEvent adds an event to the current span

func EndSpanWithError

func EndSpanWithError(span trace.Span, err error)

EndSpanWithError ends a span with an error status

func GetCounterValue

func GetCounterValue(counter *prometheus.CounterVec, labels ...string) (float64, error)

GetCounterValue retrieves the current value of a counter metric with the given labels This is primarily intended for testing

func HTTPSpanAttributes

func HTTPSpanAttributes(req *http.Request, resp *http.Response) []attribute.KeyValue

HTTPSpanAttributes returns standard HTTP span attributes

func InstrumentedHTTPClient

func InstrumentedHTTPClient(tracerName string) *http.Client

InstrumentedHTTPClient creates an HTTP client with tracing enabled

func MetricsHandler

func MetricsHandler() http.Handler

MetricsHandler returns an HTTP handler for Prometheus metrics

func RecordCacheHit

func RecordCacheHit(ctx context.Context, hit bool)

RecordCacheHit records cache hit/miss on the current span

func RecordError

func RecordError(ctx context.Context, err error)

RecordError records an error on the current span

func RecordRetry

func RecordRetry(ctx context.Context, attempt int, err error)

RecordRetry records a retry attempt on the current span

func SetAttributes

func SetAttributes(ctx context.Context, attrs ...attribute.KeyValue)

SetAttributes sets attributes on the current span

func SetupTracing

func SetupTracing(ctx context.Context, config TracerConfig) (*sdktrace.TracerProvider, error)

SetupTracing initializes OpenTelemetry tracing

func ShutdownTracing

func ShutdownTracing(ctx context.Context, tp *sdktrace.TracerProvider) error

ShutdownTracing gracefully shuts down the tracer provider

func SpanFromContext

func SpanFromContext(ctx context.Context) trace.Span

SpanFromContext returns the current span from context

func StartCacheLookupSpan

func StartCacheLookupSpan(ctx context.Context, cacheKey string) (context.Context, trace.Span)

StartCacheLookupSpan starts a span for cache lookup

func StartDependencyResolutionSpan

func StartDependencyResolutionSpan(ctx context.Context, packageID, framework string) (context.Context, trace.Span)

StartDependencyResolutionSpan starts a span for dependency resolution

func StartFileWriteSpan

func StartFileWriteSpan(ctx context.Context, filePath string, size int64) (context.Context, trace.Span)

StartFileWriteSpan starts a span for file write operations

func StartFrameworkSelectionSpan

func StartFrameworkSelectionSpan(ctx context.Context, targetFramework string, candidateCount int) (context.Context, trace.Span)

StartFrameworkSelectionSpan starts a span for framework selection

func StartMetadataFetchSpan

func StartMetadataFetchSpan(ctx context.Context, packageID, protocol string) (context.Context, trace.Span)

StartMetadataFetchSpan starts a span for metadata fetching

func StartMetadataFetchV2Span

func StartMetadataFetchV2Span(ctx context.Context, packageID string, source string) (context.Context, trace.Span)

StartMetadataFetchV2Span starts a span for V2 metadata fetch

func StartMetadataFetchV3Span

func StartMetadataFetchV3Span(ctx context.Context, packageID string, source string) (context.Context, trace.Span)

StartMetadataFetchV3Span starts a span for V3 metadata fetch

func StartMetricsServer

func StartMetricsServer(addr string) error

StartMetricsServer starts an HTTP server exposing Prometheus metrics

func StartPackageDownloadSpan

func StartPackageDownloadSpan(ctx context.Context, packageID, version, sourceURL string) (context.Context, trace.Span)

StartPackageDownloadSpan starts a span for package download operation

func StartPackageRestoreSpan

func StartPackageRestoreSpan(ctx context.Context, projectPath string, packageCount int) (context.Context, trace.Span)

StartPackageRestoreSpan starts a span for package restore operation

func StartProtocolDetectionSpan

func StartProtocolDetectionSpan(ctx context.Context, sourceURL string) (context.Context, trace.Span)

StartProtocolDetectionSpan starts a span for protocol detection

func StartRepositoryCreationSpan

func StartRepositoryCreationSpan(ctx context.Context, sourceURL string) (context.Context, trace.Span)

StartRepositoryCreationSpan starts a span for repository creation

func StartResolverWalkSpan

func StartResolverWalkSpan(ctx context.Context, packageID string, targetFramework string) (context.Context, trace.Span)

StartResolverWalkSpan starts a span for dependency walker

func StartServiceIndexFetchSpan

func StartServiceIndexFetchSpan(ctx context.Context, sourceURL string) (context.Context, trace.Span)

StartServiceIndexFetchSpan starts a span for service index fetch

func StartSpan

func StartSpan(ctx context.Context, tracerName string, spanName string, opts ...trace.SpanStartOption) (context.Context, trace.Span)

StartSpan starts a new span with the given name and options

func Tracer

func Tracer(name string) trace.Tracer

Tracer returns a named tracer

Types

type HTTPTracingTransport

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

HTTPTracingTransport wraps http.RoundTripper with OpenTelemetry tracing

func NewHTTPTracingTransport

func NewHTTPTracingTransport(base http.RoundTripper, tracerName string) *HTTPTracingTransport

NewHTTPTracingTransport creates a new HTTP transport with tracing

func (*HTTPTracingTransport) RoundTrip

func (t *HTTPTracingTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper with tracing

type HealthCheck

type HealthCheck struct {
	Name   string
	Check  func(context.Context) HealthCheckResult
	Cached bool
	TTL    time.Duration
}

HealthCheck represents a single health check

func CacheHealthCheck

func CacheHealthCheck(name string, sizeBytes int64, maxSizeBytes int64) HealthCheck

CacheHealthCheck creates a health check for cache availability

func HTTPSourceHealthCheck

func HTTPSourceHealthCheck(name, url string, timeout time.Duration) HealthCheck

HTTPSourceHealthCheck creates a health check for an HTTP source

type HealthCheckResult

type HealthCheckResult struct {
	Status  HealthStatus      `json:"status"`
	Message string            `json:"message,omitempty"`
	Details map[string]string `json:"details,omitempty"`
}

HealthCheckResult represents the result of a health check

type HealthChecker

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

HealthChecker manages and executes health checks

func NewHealthChecker

func NewHealthChecker() *HealthChecker

NewHealthChecker creates a new health checker

func (*HealthChecker) Check

Check executes all health checks and returns aggregate status

func (*HealthChecker) Handler

func (hc *HealthChecker) Handler() http.HandlerFunc

Handler returns an HTTP handler for health checks

func (*HealthChecker) OverallStatus

func (hc *HealthChecker) OverallStatus(ctx context.Context) HealthStatus

OverallStatus returns the aggregate health status

func (*HealthChecker) Register

func (hc *HealthChecker) Register(check HealthCheck)

Register registers a new health check

type HealthStatus

type HealthStatus string

HealthStatus represents the health status of a component

const (
	// HealthStatusHealthy indicates the service is healthy.
	HealthStatusHealthy HealthStatus = "healthy"
	// HealthStatusDegraded indicates the service is degraded.
	HealthStatusDegraded HealthStatus = "degraded"
	// HealthStatusUnhealthy indicates the service is unhealthy.
	HealthStatusUnhealthy HealthStatus = "unhealthy"
)

type LogLevel

type LogLevel int

LogLevel represents log verbosity level

const (
	// VerboseLevel is the most detailed logging level.
	VerboseLevel LogLevel = iota
	// DebugLevel is for debug messages.
	DebugLevel
	// InfoLevel is for informational messages.
	InfoLevel
	// WarnLevel is for warning messages.
	WarnLevel
	// ErrorLevel is for error messages.
	ErrorLevel
	// FatalLevel is for fatal error messages.
	FatalLevel
)

type Logger

type Logger interface {
	// Verbose logs detailed diagnostic information
	Verbose(messageTemplate string, args ...any)
	VerboseContext(ctx context.Context, messageTemplate string, args ...any)

	// Debug logs debugging information
	Debug(messageTemplate string, args ...any)
	DebugContext(ctx context.Context, messageTemplate string, args ...any)

	// Info logs informational messages
	Info(messageTemplate string, args ...any)
	InfoContext(ctx context.Context, messageTemplate string, args ...any)

	// Warn logs warning messages
	Warn(messageTemplate string, args ...any)
	WarnContext(ctx context.Context, messageTemplate string, args ...any)

	// Error logs error messages
	Error(messageTemplate string, args ...any)
	ErrorContext(ctx context.Context, messageTemplate string, args ...any)

	// Fatal logs fatal error messages
	Fatal(messageTemplate string, args ...any)
	FatalContext(ctx context.Context, messageTemplate string, args ...any)

	// ForContext creates a child logger with additional context
	ForContext(key string, value any) Logger

	// WithProperty adds a property to the logger
	WithProperty(key string, value any) Logger
}

Logger is the gonuget logger interface Wraps mtlog for structured logging with zero allocations

func NewDefaultLogger

func NewDefaultLogger() Logger

NewDefaultLogger creates a logger with console output and Info level

func NewLogger

func NewLogger(output io.Writer, level LogLevel) Logger

NewLogger creates a new gonuget logger with sensible defaults

func NewNullLogger

func NewNullLogger() Logger

NewNullLogger creates a logger that discards all output

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 (production, staging, etc.)
	Environment string

	// ExporterType is the type of exporter (otlp, stdout, none)
	ExporterType string

	// OTLPEndpoint is the OTLP collector endpoint (e.g., localhost:4317)
	OTLPEndpoint string

	// OTLPInsecure disables TLS for OTLP connections (use only for local development)
	OTLPInsecure bool

	// SamplingRate is the trace sampling rate (0.0 to 1.0)
	SamplingRate float64
}

TracerConfig holds OpenTelemetry tracer configuration

func DefaultTracerConfig

func DefaultTracerConfig() TracerConfig

DefaultTracerConfig returns default tracer configuration

Jump to

Keyboard shortcuts

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