Documentation
¶
Index ¶
- Constants
- func ConfigureLogger(cfg Config)
- func Ctx(ctx context.Context) *zerolog.Logger
- func Debug() *zerolog.Event
- func DebugCtx(ctx context.Context) *zerolog.Event
- func Duration(e *zerolog.Event, d time.Duration) *zerolog.Event
- func EndSpan(span trace.Span, err error)
- func Error() *zerolog.Event
- func ErrorCtx(ctx context.Context) *zerolog.Event
- func Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context
- func ExtractContext(ctx context.Context, headers map[string][]string) context.Context
- func Func(e *zerolog.Event, name string) *zerolog.Event
- func Info() *zerolog.Event
- func InfoCtx(ctx context.Context) *zerolog.Event
- func InitLogger(opts LoggerOptions)
- func Inject(ctx context.Context, carrier propagation.TextMapCarrier)
- func InjectContext(ctx context.Context, headers map[string][]string) map[string][]string
- func Logger() zerolog.Logger
- func MessagingOperationProcess() attribute.KeyValue
- func MessagingOperationPublish() attribute.KeyValue
- func MessagingSubject(subject string) attribute.KeyValue
- func MessagingSystem() attribute.KeyValue
- func MustReloadConfig(cfg *Config)
- func ReloadConfig(cfg *Config) error
- func SetExitFunc(fn func(int))
- func SetGlobal(t *Telemetry)
- func SetLogger(l zerolog.Logger)
- func StatusTraceIDRatioBased(fraction float64) sdktrace.Sampler
- func TraceFunc(ctx context.Context, name string, fn func(context.Context) error) error
- func Warn() *zerolog.Event
- func WarnCtx(ctx context.Context) *zerolog.Event
- func WithFields(ctx context.Context, fields ...Field) context.Context
- func WrapContext(ctx context.Context, l *Telemetry) context.Context
- type AttrCache
- type CardinalityDetectorConfig
- type Config
- type FastCounter
- type FastGauge
- type FastHistogram
- type FatalEvent
- type Field
- type HistogramOpt
- type LoggerOptions
- type MetricsConfig
- type MonitorConfig
- type RateSampler
- type Registry
- func (r *Registry) AttrCache() *AttrCache
- func (r *Registry) Counter(name string, opts ...metric.Int64CounterOption) (*FastCounter, error)
- func (r *Registry) Gauge(name string, opts ...metric.Int64GaugeOption) (*FastGauge, error)
- func (r *Registry) Histogram(name string, opts ...metric.Float64HistogramOption) (*FastHistogram, error)
- type TLSRawConfig
- type TelConfig
- type Telemetry
- func FromCtx(ctx context.Context) *Telemetry
- func Global() *Telemetry
- func Init(ctx context.Context) (*Telemetry, func(context.Context) error)
- func InitWithConfig(ctx context.Context, cfg Config) (*Telemetry, func(context.Context) error, error)
- func New() *Telemetry
- func NewWithConfig(cfg Config) *Telemetry
- func NewWithTracerProvider(cfg Config, provider trace.TracerProvider) *Telemetry
- func (t *Telemetry) Config() Config
- func (t *Telemetry) Meter(ins string, opts ...metric.MeterOption) metric.Meter
- func (t *Telemetry) Registry() *Registry
- func (t *Telemetry) Shutdown(ctx context.Context) error
- func (t *Telemetry) Start(ctx context.Context) error
- func (t *Telemetry) StartSpan(ctx context.Context, spanName string, opts ...trace.SpanStartOption) (context.Context, trace.Span)
- func (t *Telemetry) Tracer(name string) trace.Tracer
- type Timer
- type TracesConfig
Examples ¶
Constants ¶
const ( FieldTraceID = "trace_id" FieldSpanID = "span_id" FieldService = "service" FieldPod = "pod" FieldNamespace = "namespace" FieldEnvironment = "environment" FieldVersion = "version" FieldFunction = "function" FieldDurationMs = "duration_ms" FieldDurationS = "duration_s" )
Structured log field keys for correlation and operation metadata.
Variables ¶
This section is empty.
Functions ¶
func ConfigureLogger ¶
func ConfigureLogger(cfg Config)
ConfigureLogger applies Config.LogLevel / LogEncode to the process logger. Call once at process startup before concurrent logging (not from NewWithConfig).
func Ctx ¶
Ctx returns a logger for ctx. When ctx carries a valid OTel span and/or WithFields bag, a child logger is built once; otherwise the context/process logger is reused.
func Duration ¶ added in v0.3.0
Duration attaches elapsed time: duration_ms when under 1s, otherwise duration_s.
func Extract ¶ added in v0.3.0
func Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context
Extract reads W3C trace context from carrier.
func ExtractContext ¶
func InitLogger ¶
func InitLogger(opts LoggerOptions)
InitLogger configures structured logging. Safe to call at startup (and again to reconfigure).
func Inject ¶ added in v0.3.0
func Inject(ctx context.Context, carrier propagation.TextMapCarrier)
Inject writes W3C trace context into carrier.
func InjectContext ¶
Example ¶
ExampleInjectContext demonstrates W3C trace context propagation via headers.
headers := InjectContext(context.Background(), map[string][]string{})
_ = ExtractContext(context.Background(), headers)
func MessagingSubject ¶
func MessagingSystem ¶
func MustReloadConfig ¶ added in v0.3.0
func MustReloadConfig(cfg *Config)
func ReloadConfig ¶ added in v0.3.0
func SetExitFunc ¶
func SetExitFunc(fn func(int))
SetExitFunc overrides the function called after Fatal logs (for tests).
func StatusTraceIDRatioBased ¶ added in v0.3.0
StatusTraceIDRatioBased samples like TraceIDRatioBased, but always records when start attributes or links include an "error" key.
func TraceFunc ¶ added in v0.3.0
TraceFunc starts a span named name, runs fn, ends the span, and logs once with function + adaptive duration (and trace_id/span_id via the span context).
func WithFields ¶ added in v0.3.0
WithFields returns a child context that carries additional log fields. Nested calls append (last-wins when applied). Parent slice is copied — never mutated.
Types ¶
type AttrCache ¶
type AttrCache struct {
// contains filtered or unexported fields
}
AttrCache interns attribute sets and metric options for hot-path label reuse. Entries are sharded by subject hash; hits take a short shard RLock.
func (*AttrCache) SetDetector ¶
func (c *AttrCache) SetDetector(d *cardinalityDetector)
SetDetector wires optional cardinality observation into the hot path.
func (*AttrCache) SubjectRecordOpts ¶
func (c *AttrCache) SubjectRecordOpts(subject string) []metric.RecordOption
type CardinalityDetectorConfig ¶ added in v0.3.0
type CardinalityDetectorConfig struct {
MaxCardinality int `env:"METRICS_CARDINALITY_DETECTOR_MAX_CARDINALITY" default:"100"`
MaxInstruments int `env:"METRICS_CARDINALITY_DETECTOR_MAX_INSTRUMENTS" default:"500"`
DiagnosticInterval time.Duration `env:"METRICS_CARDINALITY_DETECTOR_DIAGNOSTIC_INTERVAL" default:"10m"`
Enable bool `env:"METRICS_CARDINALITY_DETECTOR_ENABLE" default:"true"`
}
CardinalityDetectorConfig limits metric label / instrument cardinality.
goalign:ignore
type Config ¶
type Config struct {
MonitorConfig MonitorConfig
TelConfig TelConfig
Service string `env:"TEL_SERVICE_NAME"`
// Pod is the instance identity (K8s pod name). Falls back to HOSTNAME / os.Hostname.
Pod string `env:"POD_NAME"`
Namespace string `env:"NAMESPACE" default:"default"`
Environment string `env:"DEPLOY_ENVIRONMENT" default:"dev"`
Version string `env:"VERSION" default:"dev"`
LogLevel string `env:"LOG_LEVEL" default:"info"`
LogEncode string `env:"LOG_ENCODE" default:"console"`
MaxMessagesPerSecond int `env:"LOGS_MAX_MESSAGES_PER_SECOND" default:"0"`
MaxLevelMessagesPerSecond string `env:"LOGS_MAX_LEVEL_MESSAGES_PER_SECOND"`
Debug bool `env:"DEBUG" default:"false"`
}
Config holds process-wide telemetry settings. Embedded configs stay first (embeddedstructfieldcheck); fieldalignment is excluded for this file in .golangci.yml and make align.
goalign:ignore
func DefaultConfig ¶
func DefaultConfig() Config
func DefaultDebugConfig ¶
func DefaultDebugConfig() Config
func GetConfigFromEnv ¶ added in v0.3.0
GetConfigFromEnv loads `.env` (if present), then parses Config from the process environment. Empty TEL_SERVICE_NAME falls back to a hostname-derived service name.
func LoadConfig ¶ added in v0.3.0
func LoadConfigFrom ¶ added in v0.3.0
func LoadConfigFrom(snap *env.EnvSnapshot) (Config, error)
func MustLoadConfig ¶ added in v0.3.0
func MustLoadConfig() Config
type FastCounter ¶
type FastCounter struct {
// contains filtered or unexported fields
}
func (*FastCounter) AddWith ¶
func (c *FastCounter) AddWith(ctx context.Context, n int64, subject string)
func (*FastCounter) WithAttrs ¶
func (c *FastCounter) WithAttrs(attrs attribute.Set) *FastCounter
type FastGauge ¶
type FastGauge struct {
// contains filtered or unexported fields
}
func (*FastGauge) RecordWith ¶
type FastHistogram ¶
type FastHistogram struct {
// contains filtered or unexported fields
}
func (*FastHistogram) RecordWith ¶
func (h *FastHistogram) RecordWith(ctx context.Context, value float64, subject string)
func (*FastHistogram) WithAttrs ¶
func (h *FastHistogram) WithAttrs(attrs attribute.Set) *FastHistogram
type FatalEvent ¶
type FatalEvent struct {
// contains filtered or unexported fields
}
FatalEvent mirrors zerolog's chainable API but exits via SetExitFunc instead of os.Exit directly.
func Fatal ¶
func Fatal() *FatalEvent
Fatal logs at fatal level and invokes the configured exit function (default os.Exit).
func (*FatalEvent) Err ¶
func (f *FatalEvent) Err(err error) *FatalEvent
func (*FatalEvent) Msg ¶
func (f *FatalEvent) Msg(msg string)
func (*FatalEvent) Msgf ¶
func (f *FatalEvent) Msgf(format string, v ...any)
func (*FatalEvent) Str ¶
func (f *FatalEvent) Str(key, val string) *FatalEvent
type Field ¶ added in v0.3.0
Field is a typed context log attribute. goalign:ignore // trailing bool padding is unavoidable
type HistogramOpt ¶
type LoggerOptions ¶
type LoggerOptions struct {
Level string
JSON bool
Pretty bool // indent JSON lines (only when JSON is true)
}
LoggerOptions configures the process-global zerolog logger.
goalign:ignore
type MetricsConfig ¶ added in v0.3.0
type MetricsConfig struct {
CardinalityDetector CardinalityDetectorConfig
EnableRetry bool `env:"METRICS_ENABLE_RETRY" default:"false"`
}
MetricsConfig holds metric export / cardinality settings.
goalign:ignore
type MonitorConfig ¶
type MonitorConfig struct {
MonitorAddr string `env:"MONITOR_ADDR" default:"127.0.0.1:8011"`
Enable bool `env:"MONITOR_ENABLE" default:"true"`
}
MonitorConfig holds health/stats monitor settings.
goalign:ignore
type RateSampler ¶ added in v0.3.0
type RateSampler struct {
// contains filtered or unexported fields
}
RateSampler caps log volume per second (global and optional per-level). Sample is allocation-free: atomics + fixed per-level counters.
func NewRateSampler ¶ added in v0.3.0
func NewRateSampler(globalLimit int, levelLimits map[zerolog.Level]uint64) *RateSampler
NewRateSampler builds a sampler. globalLimit 0 disables global capping (per-level limits may still apply). levelLimits maps zerolog level → max/sec; unset levels are unlimited.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
func (*Registry) Counter ¶
func (r *Registry) Counter(name string, opts ...metric.Int64CounterOption) (*FastCounter, error)
func (*Registry) Histogram ¶
func (r *Registry) Histogram(name string, opts ...metric.Float64HistogramOption) (*FastHistogram, error)
type TLSRawConfig ¶ added in v0.3.0
type TLSRawConfig struct {
CA []byte `env:"OTEL_COLLECTOR_TLS_CA_CERT"`
Cert []byte `env:"OTEL_COLLECTOR_TLS_CLIENT_CERT"`
Key []byte `env:"OTEL_COLLECTOR_TLS_CLIENT_KEY"`
}
TLSRawConfig holds PEM material for collector mTLS.
goalign:ignore
type TelConfig ¶
type TelConfig struct {
Address string `env:"TEL_COLLECTOR_GRPC_ADDR" default:"127.0.0.1:4317"`
ServerName string `env:"TEL_COLLECTOR_TLS_SERVER_NAME"`
Raw TLSRawConfig `env:"-"`
BucketView []HistogramOpt `env:"-"` // runtime-only
Metrics MetricsConfig `env:"-"`
MetricsPeriodicIntervalSec int `env:"TEL_METRIC_PERIODIC_INTERVAL_SEC" default:"15"`
ExportIntervalSec int `env:"TEL_EXPORT_INTERVAL_SEC" default:"0"`
WithInsecure bool `env:"TEL_EXPORTER_WITH_INSECURE" default:"true"`
Enable bool `env:"TEL_ENABLE" default:"true"`
WithCompression bool `env:"TEL_ENABLE_COMPRESSION" default:"true"`
Traces TracesConfig `env:"-"`
}
TelConfig holds OTLP export and related collector settings.
goalign:ignore
type Telemetry ¶
type Telemetry struct {
// contains filtered or unexported fields
}
Telemetry is the process-wide metrics/traces runtime.
goalign:ignore
func Init ¶ added in v0.3.0
Init loads .env + env config, configures the logger, creates telemetry, sets the process global, and starts exporters. On failure it Fatals (does not return an error). The returned shutdown flushes exporters; call it on process exit (e.g. defer).
func InitWithConfig ¶ added in v0.3.0
func InitWithConfig(ctx context.Context, cfg Config) (*Telemetry, func(context.Context) error, error)
InitWithConfig is like Init but uses an explicit Config (tests / custom setup). It does not load .env. The returned shutdown flushes exporters.
func NewWithConfig ¶
func NewWithTracerProvider ¶
func NewWithTracerProvider(cfg Config, provider trace.TracerProvider) *Telemetry
NewWithTracerProvider wires a custom tracer provider (useful in tests and custom setups).
func (*Telemetry) Shutdown ¶
Shutdown flushes exporters and releases resources. Safe to call after Start, and again after a subsequent Start (restart-safe; not sync.Once).
type Timer ¶
type Timer struct {
// contains filtered or unexported fields
}
func NewTimer ¶
func NewTimer(hist *FastHistogram) Timer
type TracesConfig ¶ added in v0.3.0
type TracesConfig struct {
Enable bool `env:"TEL_TRACES_ENABLE" default:"true"`
Sampler string `env:"TEL_TRACES_SAMPLER" default:"parentbased_statustraceidratio:0.1"`
}
TracesConfig holds trace export settings.
goalign:ignore
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
Example of tel lifecycle and subject-keyed metrics.
|
Example of tel lifecycle and subject-keyed metrics. |
|
internal
|
|
|
bytesconv
Package bytesconv provides zero-allocation string↔[]byte conversions.
|
Package bytesconv provides zero-allocation string↔[]byte conversions. |
|
middleware
|
|