oti

package
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2025 License: GPL-3.0 Imports: 43 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OTEL_TRACES_EXPORTER_ARG_NAME = "otel-traces-exporter"
	OTEL_TRACES_EXPORTER_DEFAULT  = "none"
	OTEL_TRACES_EXPORTER_HELP     = "Selects the exporter to use for tracing: otlp | console | none"

	OTEL_METRICS_EXPORTER_ARG_NAME = "otel-metrics-exporter"
	OTEL_METRICS_EXPORTER_DEFAULT  = "none"
	OTEL_METRICS_EXPORTER_HELP     = "Selects the exporter to use for metrics: otlp | prometheus | console | none"

	OTEL_EXPORTER_PROMETHEUS_PORT_ARG_NAME = "otel-exporter-prometheus-port"
	OTEL_EXPORTER_PROMETHEUS_PORT_DEFAULT  = 9464
	OTEL_EXPORTER_PROMETHEUS_PORT_HELP     = "the port used by the Prometheus exporter"

	FieldTraceID        = attribute.Key("trace.id")
	FieldSpanID         = attribute.Key("span.id")
	FieldSpanKind       = attribute.Key("span.kind")
	FieldSpan           = attribute.Key("span")
	FieldSpanErr        = attribute.Key("span.err")
	FieldValue          = attribute.Key("value")
	FieldDuration       = attribute.Key("duration")
	FieldMetricName     = attribute.Key("metric.name")
	FieldMetricExporter = attribute.Key("metric.exporter")
	FieldSubject        = attribute.Key("subject")
	FieldSubscrSubject  = attribute.Key("subscr.subject")
	FieldSubscrQueue    = attribute.Key("subscr.queue")
	FieldReply          = attribute.Key("reply")
	FieldApp            = attribute.Key("app")
	FieldService        = semconv.ServiceNameKey
	FieldVersion        = attribute.Key("version")
	FieldComponent      = attribute.Key("component")
	FieldNetLayer       = attribute.Key("network.layer")
	FieldExporter       = attribute.Key("exporter")
	FieldStatusCode     = semconv.HTTPResponseStatusCodeKey
	FieldReqLen         = semconv.HTTPRequestBodySizeKey
	FieldRespLen        = semconv.HTTPResponseBodySizeKey
	FieldHttpMethod     = semconv.HTTPRequestMethodKey
	FieldUrlFull        = semconv.URLFullKey
	FieldUrlPath        = semconv.URLPathKey
	FieldUrlHost        = semconv.URLDomainKey
	FieldUrlPattern     = semconv.URLTemplateKey
	FieldMsgType        = attribute.Key("message.type")

	FieldMessageType = "messageType"

	FieldError = attribute.Key("error")

	EventOK = "ok"

	MsgOutReq    = "HTTP_OUT_REQ"
	MsgOutResp   = "HTTP_OUT_RESP"
	MsgInReq     = "HTTP_IN_REQ"
	MsgInResp    = "HTTP_IN_RESP"
	MsgSpanIn    = "SPAN_IN"
	MsgSpanNew   = "SPAN_NEW"
	MsgSpanStart = "SPAN_START"

	MsgOtelError = "OTEL_ERROR"
)
View Source
const (
	// MetrAttrErr is the metric attribute for error
	MetrAttrErr           = attribute.Key("error")
	MetrAttrMethod        = semconv.HTTPRequestMethodKey
	MetrAttrUrl           = semconv.URLFullKey
	MetrAttrStatus        = semconv.HTTPResponseStatusCodeKey
	MetrAttrPathPattern   = semconv.URLTemplateKey
	MetrAttrPath          = semconv.URLPathKey
	MetrAttrHost          = semconv.URLDomainKey
	MetrAttrService       = semconv.ServiceNameKey
	MetrAttrTargetService = semconv.PeerServiceKey

	MetrHttpOut      = "http_out"
	MetrHttpOutDescr = "HTTP out response"
)
View Source
const (
	// Log fields
	KeyError      = "error.message"
	KeyMetricName = "metric.name"
	KeyTestSuite  = "test.suite"

	// Metric labels
	KeyApp     = "app"
	KeyService = "service"
)
View Source
const (
	SpanKeyComponent = attribute.Key("app")
	SpanKeyService   = semconv.ServiceNameKey
	SpanKeyInstance  = attribute.Key("instance")

	TraceparentHeader = "traceparent"
)

Variables

View Source
var (
	ErrOtelConfig = errors.New("invalid otel configuration")

	FieldNetOut = semconv.NetworkIoDirectionTransmit
	FieldNetIn  = semconv.NetworkIoDirectionReceive
)
View Source
var (
	// ErrTypeCast is an error for type assertion from interface
	ErrTypeCast     = errors.New("unable to cast interface to type")
	ErrorEventName  = "ERROR"
	ErrUnableToCast = errors.New("interface cast error")
)
View Source
var (
	DefaultPrometheusRegisterer = client_prometheus.DefaultRegisterer
)
View Source
var ErrPanic = errors.New("captured panic")

ErrPanic is an error for captured panic

View Source
var (
	// ReplaceDotToUs controls whether to replace dots with underscores in log keys
	// Reason: Loki will replace dots with underscores,
	// so to keep consistency, it will be visible on console, too.
	ReplaceDotToUs = true
)

Functions

func CopyLogger added in v2.1.0

func CopyLogger(ctxTo context.Context, ctxFrom context.Context) context.Context

func DecorateHttpTransport added in v2.1.0

func DecorateHttpTransport(ctx context.Context, httpTransport http.RoundTripper,
	traceAttributes []attribute.KeyValue,
	metricName string, metricDescription string, metricLabels []attribute.KeyValue,
	log logr.Logger, logReqLevel int, logRespLevel int,
	captureConfig CaptureConfiger,
) http.RoundTripper

func DotToUs added in v2.1.0

func DotToUs[T ~string](s T) string

func DotToUsIf added in v2.1.0

func DotToUsIf[T ~string](s T, dotToUs bool) string

func FirstErr added in v2.0.3

func FirstErr(err error) string

FirstErr returns the first part of error text before ':'

func FirstErrPart added in v2.1.0

func FirstErrPart(err error) string

FirstErrPart returns the characters before first ;:, characters

func Float64CounterGetInstrument added in v2.0.3

func Float64CounterGetInstrument(name string, options ...metric_api.Float64CounterOption) (metric_api.Float64Counter, error)

func FullErr added in v2.0.3

func FullErr(err error) string

FullErr returns the full error text. Be careful about the cardinality, if the error text has dynamic part(s) (see: Prometheus label)

func GetHost added in v2.1.0

func GetHost(r *http.Request) string

func GetMeter added in v2.0.3

func GetMeter(ctx context.Context) metric_api.Meter

GetMeter returns the default meter. Inits meter and InstrumentRegs (if needed)

func HttpServerLoggerBaseMiddleware added in v2.1.0

func HttpServerLoggerBaseMiddleware(ctxRoot context.Context) func(next http.Handler) http.Handler

HttpServerLoggerBaseMiddleware sets a minimal logger to the request context, before the Span middleware

func HttpServerLoggerMiddleware added in v2.1.0

func HttpServerLoggerMiddleware(beginLevel int, endLevel int) func(next http.Handler) http.Handler

func HttpServerMetricMiddleware added in v2.1.0

func HttpServerMetricMiddleware(ctx context.Context, meter metric_api.Meter, name string,
	description string, attributes []attribute.KeyValue,
) func(next http.Handler) http.Handler

func HttpServerTracerMiddleware added in v2.1.0

func HttpServerTracerMiddleware(tr trace.Tracer, instance string, spanLogLevel int) func(next http.Handler) http.Handler

TODO TraceState propagation (client command) spanLogLevel: Debug

func Int64CounterGetInstrument added in v2.0.3

func Int64CounterGetInstrument(name string, options ...metric_api.Int64CounterOption) (metric_api.Int64Counter, error)

func Log added in v2.1.0

func Log(ctx context.Context, level int, msg string, args ...any)

func LogError added in v2.1.0

func LogError(ctx context.Context, err error, msg string, args ...any)

func LogWithValues added in v2.1.0

func LogWithValues(ctx context.Context, args ...any) context.Context

func NewHttpTransport added in v2.1.0

func NewHttpTransport() *http.Transport

func NewLoggingResponseWriter added in v2.1.0

func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter

func NoErr added in v2.0.3

func NoErr(error) string

NoErr always returns "". Can be used to skip any error stats in the metrics

func ObsNatsConsumerMessageHandler added in v2.1.0

func ObsNatsConsumerMessageHandler(rootCtx context.Context, fn func(context.Context, jetstream.Msg) error,
	serviceName string,
	startLevel int, endLevel int,
) func(jetstream.Msg)

func ObsNatsMsgHandler added in v2.1.0

func ObsNatsMsgHandler(rootCtx context.Context, fn func(context.Context, *nats.Msg) error,
	serviceName string, netLayer string,
	startLevel int, endLevel int,
) nats.MsgHandler

ObsNatsMsgHandler observes the NATS MsgHandler calls Adds ctx and error to the original function signature: type MsgHandler func(msg *Msg) error

func ObsPublishMsg added in v2.1.0

func ObsPublishMsg(ctx context.Context, fn func(ctx context.Context, msg *nats.Msg, opts ...jetstream.PublishOpt) (*jetstream.PubAck, error),
	serviceName string, netLayer string,
	startLevel int, endLevel int,
) func(ctx context.Context, msg *nats.Msg, opts ...jetstream.PublishOpt) (*jetstream.PubAck, error)

ObsPublishMsg observes the NATS JS PublishMsg calls (ctx context.Context, msg *nats.Msg, opts ...PublishOpt) (*PubAck, error)

func ObsRequestMsg added in v2.1.0

func ObsRequestMsg(ctx context.Context, fn func(msg *nats.Msg, timeout time.Duration) (*nats.Msg, error),
	serviceName string, netLayer string,
	startLevel int, endLevel int,
) func(msg *nats.Msg, timeout time.Duration) (*nats.Msg, error)

ObsRequestMsg observes the NATS RequestMsg calls

func PatchLogArgs added in v2.1.0

func PatchLogArgs(args []any) []any

PatchLogArgs ensures that all keys are strings (zap and slog require string keys) and replaces '.' with '_' in the keys if ReplaceDotToUs is true

Types

type CaptureConfiger added in v2.1.0

type CaptureConfiger interface {
}

type Config

type Config struct {
	// OtelTracesExporter specifies which exporter is used for tracing
	// Possible values are: "otlp": OTLP, "jaeger": Jaeger, "zipkin": Zipkin, "console": Standard Output, "none": No automatically configured exporter for tracing
	OtelTracesExporter string `mapstructure:"otel-traces-exporter"`

	// OtelMetricsExporter specifies which exporter is used for metrics
	// Possible values are: "otlp": OTLP, "prometheus": Prometheus, "console": Standard Output, "none": No automatically configured exporter for metrics
	OtelMetricsExporter string `mapstructure:"otel-metrics-exporter"`

	// OtelExporterPrometheusPort specifies the port that the prometheus exporter uses to provide the metrics
	OtelExporterPrometheusPort int `mapstructure:"otel-exporter-prometheus-port"`
}

Config holds the configuration parameters for the Open Telemetry instrumentation

func (*Config) GetConfigFlagSet

func (cfg *Config) GetConfigFlagSet(flagSet *pflag.FlagSet)

func (*Config) LoadConfig

func (cfg *Config) LoadConfig(flagSet *pflag.FlagSet) error

type ConsoleMeterProviderOut added in v2.1.0

type ConsoleMeterProviderOut int
const (
	ConsoleNone ConsoleMeterProviderOut = iota
	ConsoleStdout
	ConsoleStderr
)

type ErrFormatter added in v2.0.3

type ErrFormatter func(error) string

ErrFormatter is a func type to format metric error attribute

type HttpMiddlewareFunc added in v2.1.0

type HttpMiddlewareFunc func(http.Handler) http.Handler

type InstrumentReg added in v2.0.3

type InstrumentReg[T any, O any] struct {
	// contains filtered or unexported fields
}

InstrumentReg stores the already registered instruments

func (*InstrumentReg[T, O]) GetInstrument added in v2.0.3

func (r *InstrumentReg[T, O]) GetInstrument(name string, options ...O) (T, error)

GetInstrument registers a new instrument, otherwise returns the already created.

type InternalMiddleware added in v2.0.3

type InternalMiddleware[T any] func(next InternalMiddlewareFn[T]) InternalMiddlewareFn[T]

func InternalMiddlewareChain added in v2.1.0

func InternalMiddlewareChain[T any](mws ...InternalMiddleware[T]) InternalMiddleware[T]

func Logger added in v2.1.0

func Logger[T any](
	beginMessage string, beginLevel int, endMessage string, endLevel int, errMessage string,
	values []attribute.KeyValue,
) InternalMiddleware[T]

Logger is a middleware for logging begin and end messages. A new logger with values is added to the context.

func Metrics added in v2.0.3

func Metrics[T any](ctx context.Context, meter metric_api.Meter, name string,
	description string, attributes []attribute.KeyValue, errFormatter ErrFormatter,
) InternalMiddleware[T]

Metrics is a middleware to make count and duration report

Prometheus-specific implementation:
The "_total" suffix is appended to the counter name, defined in "counterSuffix", see:
https://github.com/open-telemetry/opentelemetry-go/blob/main/exporters/prometheus/exporter.go#L100
The unit "s" is appended as "_seconds" to the metric name (injected before the "_total" suffix),
defined in "unitSuffixes", see
https://github.com/open-telemetry/opentelemetry-go/blob/main/exporters/prometheus/exporter.go#L343

func Span added in v2.1.0

func Span[T any](tr trace.Tracer, spanKind trace.SpanKind, spanName string) InternalMiddleware[T]

Span is a middleware to start/end a new span, using from context. Sets "traceID", "spanParentID" and "spanID" log values.

func TryCatch added in v2.1.0

func TryCatch[T any]() InternalMiddleware[T]

TryCatch is a middleware for catching Go panic and propagating it as an error

type InternalMiddlewareFn added in v2.0.3

type InternalMiddlewareFn[T any] func(ctx context.Context) (T, error)

type LogTransport added in v2.1.0

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

LogTransport implements the http.RoundTripper interface and wraps outbound HTTP(S) requests with logs.

func NewLogTransport added in v2.1.0

func NewLogTransport(base http.RoundTripper, beginLevel int, endLevel int) *LogTransport

NewLogTransport wraps the provided http.RoundTripper with one that logs request and respnse.

If the provided http.RoundTripper is nil, http.DefaultTransport will be used as the base http.RoundTripper.

func (*LogTransport) RoundTrip added in v2.1.0

func (t *LogTransport) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip logs outgoing request and response.

type MetricExporterType added in v2.0.3

type MetricExporterType string
var (
	MetricExporterTypeOTLP       MetricExporterType = "otlp"
	MetricExporterTypePrometheus MetricExporterType = "prometheus"
	MetricExporterTypeConsole    MetricExporterType = "console"
	MetricExporterTypeNone       MetricExporterType = "none"
)

type MetricTransport added in v2.1.0

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

MetricTransport implements the http.RoundTripper interface and wraps outbound HTTP(S) requests with metrics.

func NewMetricTransport added in v2.1.0

func NewMetricTransport(base http.RoundTripper, meter metric_api.Meter, name string,
	description string, attributes []attribute.KeyValue, errFormatter ErrFormatter,
) *MetricTransport

NewMetricTransport wraps the provided http.RoundTripper with one that meters metrics.

If the provided http.RoundTripper is nil, http.DefaultTransport will be used as the base http.RoundTripper.

func (*MetricTransport) RoundTrip added in v2.1.0

func (t *MetricTransport) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip meters outgoing request-response pair.

type NatsCarrier added in v2.1.0

type NatsCarrier nats.Header

NatsCarrier adapts nats.Header to satisfy the TextMapCarrier interface.

func (NatsCarrier) Get added in v2.1.0

func (hc NatsCarrier) Get(key string) string

Get returns the value associated with the passed key.

func (NatsCarrier) Keys added in v2.1.0

func (hc NatsCarrier) Keys() []string

Keys lists the keys stored in this carrier.

func (NatsCarrier) Set added in v2.1.0

func (hc NatsCarrier) Set(key string, value string)

Set stores the key-value pair.

type Otel

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

func NewOtel

func NewOtel(wg *sync.WaitGroup, config Config) Otel

Create a Otel instance

func (*Otel) Shutdown

func (o *Otel) Shutdown(ctx context.Context)

Shut down the Otel services

func (*Otel) Startup

func (o *Otel) Startup(ctx context.Context) context.Context

Setup the Otel providers and exporter services

type OtelErrorHandler added in v2.1.0

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

func (*OtelErrorHandler) Handle added in v2.1.0

func (e *OtelErrorHandler) Handle(err error)

type RecoveryLogger added in v2.1.0

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

func NewRecoveryLogger added in v2.1.0

func NewRecoveryLogger(log *slog.Logger) *RecoveryLogger

func (*RecoveryLogger) Println added in v2.1.0

func (rl *RecoveryLogger) Println(v ...any)

type TraceExporterType added in v2.0.3

type TraceExporterType string
var (
	TraceExporterTypeOTLP    TraceExporterType = "otlp"
	TraceExporterTypeConsole TraceExporterType = "console"
	TraceExporterTypeNone    TraceExporterType = "none"
)

Jump to

Keyboard shortcuts

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