telemetry

package
v0.0.0-...-ea9222f Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxComponents   = 64
	MaxMessageLen   = 256
	MaxDetails      = 32
	MaxDetailKeyLen = 64
	MaxDetailValLen = 256
	MaxServiceLen   = 64
	MaxEnvLen       = 32
	MaxTenantLen    = 64

	// Bounded warnings to prevent report bloat.
	MaxWarnings = 32
)
View Source
const (
	MaxFields = 64
	MaxKeyLen = 64
	MaxValLen = 512

	// Bound conflict reporting
	MaxConflictKeys = 8

	// Deterministic value encoding bound (before sanitize truncation)
	MaxDeterministicJSONBytes = 2048
)
View Source
const (
	MaxLabelPairs  = 32
	MaxLabelKeyLen = 64
	MaxLabelValLen = 256
)

Variables

View Source
var (
	ErrInvalidLabels = errors.New("telemetry: invalid labels")
	ErrInvalidValue  = errors.New("telemetry: invalid metric value")
)
View Source
var (
	ErrInvalidHealth = errors.New("telemetry: invalid health")
)
View Source
var NopLogger = &Logger{w: io.Discard, opt: Options{Timestamp: true, Level: LevelError}}

NopLogger is a safe no-op logger.

View Source
var NopMeterInstance = NopMeter{}

NopMeterInstance is a convenience singleton.

Functions

func ContextWithSpanContext

func ContextWithSpanContext(ctx context.Context, sc SpanContext) context.Context

ContextWithSpanContext returns a context carrying the provided SpanContext.

func DefaultHistogramBuckets

func DefaultHistogramBuckets() []float64

DefaultHistogramBuckets returns a shared recommended bucket set. These are similar in spirit to common latency buckets (seconds) used in practice. Callers may supply custom buckets; this is a safe default to reduce drift.

func IncCounter

func IncCounter(m Meter, ctx context.Context, name string, delta int64, labels Labels) error

func ObserveHistogram

func ObserveHistogram(m Meter, ctx context.Context, name string, value float64, buckets []float64, labels Labels) error

func SetGauge

func SetGauge(m Meter, ctx context.Context, name string, value float64, labels Labels) error

func ValidateBuckets

func ValidateBuckets(b []float64) error

ValidateBuckets ensures histogram buckets are strictly increasing and finite.

func ValidateFloat

func ValidateFloat(value float64) error

func ValidateMetricName

func ValidateMetricName(name string) error

ValidateMetricName enforces a safe name charset. Pattern: [a-z][a-z0-9:_-]{0,127}

Types

type Carrier

type Carrier map[string]string

Carrier is a simple header map used for trace propagation.

type ComponentStatus

type ComponentStatus struct {
	Name      string            `json:"name"`
	Status    Status            `json:"status"`
	CheckedAt time.Time         `json:"checked_at"`
	Message   string            `json:"message,omitempty"`
	Details   map[string]string `json:"details,omitempty"`
}

ComponentStatus describes a single subsystem check.

func (ComponentStatus) MarshalJSON

func (c ComponentStatus) MarshalJSON() ([]byte, error)

type Event

type Event struct {
	Ts      string  `json:"ts"`
	Level   Level   `json:"level"`
	Service string  `json:"service,omitempty"`
	Msg     string  `json:"msg"`
	Fields  []Field `json:"fields,omitempty"`
}

Event is a single log record (JSON line).

type Field

type Field struct {
	K string `json:"k"`
	V string `json:"v"`
}

Field is a deterministic key/value field representation.

type HealthSnapshot

type HealthSnapshot struct {
	Service     string            `json:"service"`
	Env         string            `json:"env,omitempty"`
	Tenant      string            `json:"tenant,omitempty"`
	GeneratedAt time.Time         `json:"generated_at"`
	Overall     Status            `json:"overall"`
	Components  []ComponentStatus `json:"components"`
	Hash        string            `json:"hash"`

	// Optional warnings emitted during Normalize (e.g. truncation, dedupe).
	Warnings []HealthWarning `json:"warnings,omitempty"`
}

HealthSnapshot is the full health document emitted by a service.

func NewHealthSnapshot

func NewHealthSnapshot(service, env, tenant string, comps []ComponentStatus, now time.Time) (HealthSnapshot, error)

NewHealthSnapshot builds a normalized + validated snapshot. Hybrid time: if now is zero, uses time.Now().UTC().

func (HealthSnapshot) MarshalJSON

func (s HealthSnapshot) MarshalJSON() ([]byte, error)

func (*HealthSnapshot) Normalize

func (s *HealthSnapshot) Normalize() error

Normalize enforces deterministic ordering and bounds-friendly shaping, emitting warnings on: - truncations - dropped invalid detail entries - duplicate component names (deduped deterministically)

func (HealthSnapshot) StableHash

func (s HealthSnapshot) StableHash() (string, error)

StableHash returns deterministic sha256 over normalized snapshot fields. Warnings are intentionally excluded (hash represents health state, not normalization artifacts).

func (HealthSnapshot) Validate

func (s HealthSnapshot) Validate() error

type HealthWarning

type HealthWarning struct {
	Code    string `json:"code"`
	Subject string `json:"subject,omitempty"` // component name or field
	Message string `json:"message"`
}

HealthWarning captures non-fatal normalization decisions (truncations, dedupe, drops).

type Labels

type Labels map[string]string

func NormalizeLabels

func NormalizeLabels(in Labels) (Labels, error)

NormalizeLabels returns a bounded, normalized copy of labels.

  • Lowercases and trims keys
  • Trims values
  • Enforces key/value charset (ASCII) to avoid downstream exporter rejections
  • Drops invalid/empty/oversize keys
  • Truncates oversize values
  • Deterministically limits to MaxLabelPairs by sorted key order

func (Labels) Fingerprint

func (l Labels) Fingerprint() (string, error)

Fingerprint returns a deterministic sha256 over normalized labels. If labels are nil/empty, returns empty string.

type Level

type Level string

Level represents log severity.

const (
	LevelDebug Level = "debug"
	LevelInfo  Level = "info"
	LevelWarn  Level = "warn"
	LevelError Level = "error"
)

type Logger

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

Logger is a structured JSON-lines logger (stdlib-only).

func NewDefaultLogger

func NewDefaultLogger(w io.Writer, service string) *Logger

NewDefaultLogger returns an info-level logger with timestamps enabled.

func NewInfoLogger

func NewInfoLogger(w io.Writer, service string) *Logger

NewInfoLogger is an alias of NewDefaultLogger (clarity).

func NewLogger

func NewLogger(w io.Writer, opt Options) *Logger

NewLogger creates a logger writing JSON lines to w.

func (*Logger) Debug

func (l *Logger) Debug(ctx context.Context, msg string, fields map[string]any)

func (*Logger) Error

func (l *Logger) Error(ctx context.Context, msg string, fields map[string]any)

func (*Logger) Info

func (l *Logger) Info(ctx context.Context, msg string, fields map[string]any)

func (*Logger) Warn

func (l *Logger) Warn(ctx context.Context, msg string, fields map[string]any)

type Meter

type Meter interface {
	IncCounter(ctx context.Context, name string, delta int64, labels Labels) error
	SetGauge(ctx context.Context, name string, value float64, labels Labels) error
	ObserveHistogram(ctx context.Context, name string, value float64, buckets []float64, labels Labels) error
}

Meter is the minimal metrics interface used across Chartly services. Implementations may export to Prometheus, OTel, logs, etc.

type NopMeter

type NopMeter struct{}

NopMeter is a safe no-op meter.

func (NopMeter) IncCounter

func (NopMeter) IncCounter(ctx context.Context, name string, delta int64, labels Labels) error

func (NopMeter) ObserveHistogram

func (NopMeter) ObserveHistogram(ctx context.Context, name string, value float64, buckets []float64, labels Labels) error

func (NopMeter) SetGauge

func (NopMeter) SetGauge(ctx context.Context, name string, value float64, labels Labels) error

type NopPropagator

type NopPropagator struct{}

NopPropagator is a no-op propagator.

func (NopPropagator) Inject

func (NopPropagator) Inject(carrier Carrier, sc SpanContext) error

Inject performs no action and returns nil.

type Options

type Options struct {
	Service   string
	Level     Level
	Timestamp bool
}

Options configures the logger.

type Propagator

type Propagator interface {
	Inject(carrier Carrier, sc SpanContext) error
}

Propagator injects a SpanContext into a Carrier. Implementations are provider-neutral and deterministic.

type SpanContext

type SpanContext struct {
	TraceID      string
	SpanID       string
	ParentSpanID string
	Sampled      bool
}

SpanContext is a minimal tracing context used for log enrichment.

func SpanContextFromContext

func SpanContextFromContext(ctx context.Context) (SpanContext, bool)

SpanContextFromContext extracts a SpanContext from ctx if present.

type Status

type Status string
const (
	StatusOK       Status = "ok"
	StatusDegraded Status = "degraded"
	StatusFatal    Status = "fatal"
	StatusUnknown  Status = "unknown"
)

Jump to

Keyboard shortcuts

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