Files
obsx/config.go
T
M.ShakhmatovandClaude Fable 5.2 c92fd9826b
CI / test (push) Failing after 43s
Harden instrumentation, health checks and the admin server
- Admin pprof is opt-in (AdminConfig.EnablePprof)
- Client spans drop the URL query string; HostFunc bounds the host label
- Config.HTTP/HTTPClient/GRPC configure the Observer's instrumentation
- A panic after a partial HTTP response counts as 500
- GaugeFunc, CounterFunc and RegisterDBStats panic on duplicates
- Abandoned client gRPC streams are recorded as Canceled
- OTEL_EXPORTER_OTLP_PROTOCOL selects the protocol when unset
- Health reports are cached for 1s; hung checks are not restarted
- Environment is exported as deployment.environment.name

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 16:56:39 +03:00

186 lines
5.8 KiB
Go

package obsx
import (
"os"
"path/filepath"
"runtime"
"runtime/debug"
"strconv"
"strings"
"time"
)
// Config configures an Observer: logging, tracing, metrics, health checks and
// the admin HTTP server, all sharing the same service identity.
type Config struct {
ServiceName string // default: executable name
ServiceVersion string // default: main module version from build info
Environment string // e.g. "production", "staging"
Logging LogConfig
Tracing TracerConfig // ServiceName, ServiceVersion and Environment are inherited when empty
Metrics MetricsConfig
Health HealthConfig // Metrics is set automatically
Admin AdminConfig
// HTTP, HTTPClient and GRPC tune the instrumentation created by the
// Observer (RouteFunc, Skip, Buckets, Propagator, HostFunc...). Metrics,
// Logger and TracerProvider default to the Observer's own.
HTTP HTTPServerConfig
HTTPClient HTTPClientConfig
GRPC GRPCConfig
// DisableAccessLog turns off per-request logs from the HTTP and gRPC
// server instrumentation.
DisableAccessLog bool
}
// AdminConfig configures the internal admin HTTP server exposing /metrics,
// /healthz, /readyz, /buildinfo, /loglevel and, when enabled, /debug/pprof/.
// The server has no authentication: bind it to an internal address.
type AdminConfig struct {
// Addr to listen on, e.g. ":9090". When empty no server is started; mount
// Observer.AdminHandler on your own server instead.
Addr string
// EnablePprof serves /debug/pprof/. Off by default: profiling is costly
// and the admin server is unauthenticated.
EnablePprof bool
}
func (c *Config) defaults() {
if c.ServiceName == "" {
c.ServiceName = filepath.Base(os.Args[0])
}
if c.ServiceVersion == "" {
c.ServiceVersion = buildVersion()
}
if c.Tracing.ServiceName == "" {
c.Tracing.ServiceName = c.ServiceName
}
if c.Tracing.ServiceVersion == "" {
c.Tracing.ServiceVersion = c.ServiceVersion
}
if c.Tracing.Environment == "" {
c.Tracing.Environment = c.Environment
}
c.Logging.defaults()
}
// WithEnv returns a copy of c with fields overridden by environment variables,
// so that deployments can tune observability without code changes:
//
// OBSX_SERVICE_NAME, OTEL_SERVICE_NAME ServiceName
// OBSX_SERVICE_VERSION ServiceVersion
// OBSX_ENVIRONMENT Environment
// OBSX_LOG_LEVEL Logging.Level
// OBSX_LOG_FORMAT Logging.Format
// OBSX_TRACING_ENDPOINT Tracing.Endpoint
// OBSX_TRACING_PROTOCOL Tracing.Protocol
// OBSX_TRACING_INSECURE Tracing.Insecure
// OBSX_TRACING_SAMPLER Tracing.Sampler
// OBSX_TRACING_DISABLED, OTEL_SDK_DISABLED Tracing.Disabled
// OBSX_METRICS_NAMESPACE Metrics.Namespace
// OBSX_HEALTH_TIMEOUT Health.Timeout (Go duration, e.g. "3s")
// OBSX_ADMIN_ADDR Admin.Addr
// OBSX_ADMIN_ENABLE_PPROF Admin.EnablePprof
// OBSX_DISABLE_ACCESS_LOG DisableAccessLog
//
// Standard OTEL_EXPORTER_OTLP_* and OTEL_RESOURCE_ATTRIBUTES variables are
// honored by the trace exporter independently of WithEnv.
// Malformed numeric, boolean and duration values are ignored.
func (c Config) WithEnv() Config {
envString(&c.ServiceName, "OTEL_SERVICE_NAME")
envString(&c.ServiceName, "OBSX_SERVICE_NAME")
envString(&c.ServiceVersion, "OBSX_SERVICE_VERSION")
envString(&c.Environment, "OBSX_ENVIRONMENT")
envString(&c.Logging.Level, "OBSX_LOG_LEVEL")
envString(&c.Logging.Format, "OBSX_LOG_FORMAT")
envString(&c.Tracing.Endpoint, "OBSX_TRACING_ENDPOINT")
envString(&c.Tracing.Protocol, "OBSX_TRACING_PROTOCOL")
envBool(&c.Tracing.Insecure, "OBSX_TRACING_INSECURE")
envFloat(&c.Tracing.Sampler, "OBSX_TRACING_SAMPLER")
envBool(&c.Tracing.Disabled, "OTEL_SDK_DISABLED")
envBool(&c.Tracing.Disabled, "OBSX_TRACING_DISABLED")
envString(&c.Metrics.Namespace, "OBSX_METRICS_NAMESPACE")
envDuration(&c.Health.Timeout, "OBSX_HEALTH_TIMEOUT")
envString(&c.Admin.Addr, "OBSX_ADMIN_ADDR")
envBool(&c.Admin.EnablePprof, "OBSX_ADMIN_ENABLE_PPROF")
envBool(&c.DisableAccessLog, "OBSX_DISABLE_ACCESS_LOG")
return c
}
func envString(dst *string, key string) {
if v, ok := os.LookupEnv(key); ok && v != "" {
*dst = v
}
}
func envBool(dst *bool, key string) {
if v, err := strconv.ParseBool(os.Getenv(key)); err == nil {
*dst = v
}
}
func envFloat(dst *float64, key string) {
if v, err := strconv.ParseFloat(os.Getenv(key), 64); err == nil {
*dst = v
}
}
func envDuration(dst *time.Duration, key string) {
if v, err := time.ParseDuration(os.Getenv(key)); err == nil {
*dst = v
}
}
// BuildInfo describes the running binary.
type BuildInfo struct {
Service string `json:"service"`
Version string `json:"version"`
Environment string `json:"environment,omitempty"`
Revision string `json:"revision,omitempty"`
GoVersion string `json:"go_version"`
StartTime time.Time `json:"start_time"`
Uptime string `json:"uptime"`
}
func newBuildInfo(cfg Config, start time.Time) BuildInfo {
return BuildInfo{
Service: cfg.ServiceName,
Version: cfg.ServiceVersion,
Environment: cfg.Environment,
Revision: vcsRevision(),
GoVersion: runtime.Version(),
StartTime: start,
}
}
func buildVersion() string {
bi, ok := debug.ReadBuildInfo()
if !ok || bi.Main.Version == "" || bi.Main.Version == "(devel)" {
return ""
}
return bi.Main.Version
}
func vcsRevision() string {
bi, ok := debug.ReadBuildInfo()
if !ok {
return ""
}
var rev string
var dirty bool
for _, s := range bi.Settings {
switch s.Key {
case "vcs.revision":
rev = s.Value
case "vcs.modified":
dirty = s.Value == "true"
}
}
if rev != "" && dirty {
rev += "-dirty"
}
return strings.TrimSpace(rev)
}