Documentation
¶
Index ¶
- Constants
- Variables
- func CopyLogger(ctxTo context.Context, ctxFrom context.Context) context.Context
- func DecorateHttpTransport(ctx context.Context, httpTransport http.RoundTripper, ...) http.RoundTripper
- func DotToUs[T ~string](s T) string
- func DotToUsIf[T ~string](s T, dotToUs bool) string
- func FirstErr(err error) string
- func FirstErrPart(err error) string
- func Float64CounterGetInstrument(name string, options ...metric_api.Float64CounterOption) (metric_api.Float64Counter, error)
- func FullErr(err error) string
- func GetHost(r *http.Request) string
- func GetMeter(ctx context.Context) metric_api.Meter
- func HttpServerLoggerBaseMiddleware(ctxRoot context.Context) func(next http.Handler) http.Handler
- func HttpServerLoggerMiddleware(beginLevel int, endLevel int) func(next http.Handler) http.Handler
- func HttpServerMetricMiddleware(ctx context.Context, meter metric_api.Meter, name string, description string, ...) func(next http.Handler) http.Handler
- func HttpServerTracerMiddleware(tr trace.Tracer, instance string, spanLogLevel int) func(next http.Handler) http.Handler
- func Int64CounterGetInstrument(name string, options ...metric_api.Int64CounterOption) (metric_api.Int64Counter, error)
- func Log(ctx context.Context, level int, msg string, args ...any)
- func LogError(ctx context.Context, err error, msg string, args ...any)
- func LogWithValues(ctx context.Context, args ...any) context.Context
- func NewHttpTransport() *http.Transport
- func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter
- func NoErr(error) string
- func ObsNatsConsumerMessageHandler(rootCtx context.Context, fn func(context.Context, jetstream.Msg) error, ...) func(jetstream.Msg)
- func ObsNatsMsgHandler(rootCtx context.Context, fn func(context.Context, *nats.Msg) error, ...) nats.MsgHandler
- func ObsPublishMsg(ctx context.Context, ...) ...
- func ObsRequestMsg(ctx context.Context, ...) func(msg *nats.Msg, timeout time.Duration) (*nats.Msg, error)
- func PatchLogArgs(args []any) []any
- type CaptureConfiger
- type Config
- type ConsoleMeterProviderOut
- type ErrFormatter
- type HttpMiddlewareFunc
- type InstrumentReg
- type InternalMiddleware
- func InternalMiddlewareChain[T any](mws ...InternalMiddleware[T]) InternalMiddleware[T]
- func Logger[T any](beginMessage string, beginLevel int, endMessage string, endLevel int, ...) InternalMiddleware[T]
- func Metrics[T any](ctx context.Context, meter metric_api.Meter, name string, description string, ...) InternalMiddleware[T]
- func Span[T any](tr trace.Tracer, spanKind trace.SpanKind, spanName string) InternalMiddleware[T]
- func TryCatch[T any]() InternalMiddleware[T]
- type InternalMiddlewareFn
- type LogTransport
- type MetricExporterType
- type MetricTransport
- type NatsCarrier
- type Otel
- type OtelErrorHandler
- type RecoveryLogger
- type TraceExporterType
Constants ¶
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" )
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" )
const ( // Log fields KeyError = "error.message" KeyMetricName = "metric.name" KeyTestSuite = "test.suite" // Metric labels KeyApp = "app" KeyService = "service" )
const ( SpanKeyComponent = attribute.Key("app") SpanKeyService = semconv.ServiceNameKey SpanKeyInstance = attribute.Key("instance") TraceparentHeader = "traceparent" )
Variables ¶
var ( ErrOtelConfig = errors.New("invalid otel configuration") FieldNetOut = semconv.NetworkIoDirectionTransmit FieldNetIn = semconv.NetworkIoDirectionReceive )
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") )
var (
DefaultPrometheusRegisterer = client_prometheus.DefaultRegisterer
)
var ErrPanic = errors.New("captured panic")
ErrPanic is an error for captured panic
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 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 FirstErrPart ¶ added in v2.1.0
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
FullErr returns the full error text. Be careful about the cardinality, if the error text has dynamic part(s) (see: Prometheus label)
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
HttpServerLoggerBaseMiddleware sets a minimal logger to the request context, before the Span middleware
func HttpServerLoggerMiddleware ¶ added in v2.1.0
func HttpServerMetricMiddleware ¶ added in v2.1.0
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 LogWithValues ¶ added in v2.1.0
func NewHttpTransport ¶ added in v2.1.0
func NewLoggingResponseWriter ¶ added in v2.1.0
func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter
func NoErr ¶ added in v2.0.3
NoErr always returns "". Can be used to skip any error stats in the metrics
func ObsNatsConsumerMessageHandler ¶ added in v2.1.0
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
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 ¶
type ConsoleMeterProviderOut ¶ added in v2.1.0
type ConsoleMeterProviderOut int
const ( ConsoleNone ConsoleMeterProviderOut = iota ConsoleStdout ConsoleStderr )
type ErrFormatter ¶ added in v2.0.3
ErrFormatter is a func type to format metric error attribute
type InstrumentReg ¶ added in v2.0.3
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
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 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.
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.
type NatsCarrier ¶ added in v2.1.0
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 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" )