gotel

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2025 License: Apache-2.0 Imports: 43 Imported by: 0

README

gotel

gotel is a reusable library for setting up OpenTelemetry exporters in Go with configurations.

Documentation

Overview

Package gotel is a reusable library for setting up OpenTelemetry exporters in Go with configurations.

Index

Constants

This section is empty.

Variables

View Source
var UserVisibilityAttribute = attribute.String("internal.visibility", "user")

UserVisibilityAttribute is the attribute to display on the Trace view.

Functions

func GetLogger

func GetLogger(ctx context.Context) *slog.Logger

GetLogger gets the logger instance from context.

func GetRequestLogger added in v0.2.0

func GetRequestLogger(r *http.Request) *slog.Logger

GetRequestLogger get the logger from the an http request.

func IsSensitiveHeader

func IsSensitiveHeader(name string) bool

IsSensitiveHeader checks if the header name is sensitive.

func MaskString

func MaskString(input string) string

MaskString masks the string value for security.

func NewContextWithLogger added in v0.2.0

func NewContextWithLogger(parentContext context.Context, logger *slog.Logger) context.Context

NewContextWithLogger creates a new context with a logger set.

func NewJSONLogger

func NewJSONLogger(logLevel string) (*slog.Logger, slog.Level, error)

NewJSONLogger creates a JSON logger from a log level string.

func NewTelemetryHeaders

func NewTelemetryHeaders(httpHeaders http.Header, allowedHeaders ...string) http.Header

NewTelemetryHeaders creates a new header map with sensitive values masked.

func NewTracingMiddleware added in v0.2.0

func NewTracingMiddleware(
	exporters *OTelExporterResults,
	options ...TracingMiddlewareOption,
) func(http.Handler) http.Handler

NewTracingMiddleware creates a middleware with tracing and logger.

func SetSpanHeaderAttributes

func SetSpanHeaderAttributes(
	span trace.Span,
	prefix string,
	headers http.Header,
	allowedHeaders ...string,
)

SetSpanHeaderAttributes sets header attributes to the otel span.

Types

type LogHandler

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

LogHandler wraps slog logger with the OpenTelemetry logs exporter handler.

func (LogHandler) Enabled

func (l LogHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled reports whether the handler handles records at the given level.

func (LogHandler) Handle

func (l LogHandler) Handle(ctx context.Context, record slog.Record) error

Handle handles the Record. It will only be called when Enabled returns true.

func (LogHandler) WithAttrs

func (l LogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new Handler whose attributes consist of both the receiver's attributes and the arguments. The Handler owns the slice: it may retain, modify or discard it.

func (LogHandler) WithGroup

func (l LogHandler) WithGroup(name string) slog.Handler

WithGroup returns a new Handler with the given group appended to the receiver's existing groups.

type NewWrapResponseWriterFunc added in v0.2.0

type NewWrapResponseWriterFunc func(w http.ResponseWriter, protoMajor int) WrapResponseWriter

NewWrapResponseWriterFunc abstracts an interface for the http.ResponseWriter wrapper constructor.

type OTELLogsExporterType added in v0.2.0

type OTELLogsExporterType string

OTELLogsExporterType defines the type of OpenTelemetry logs exporter.

const (
	// OTELLogsExporterNone represents a enum that disables the logs exporter.
	OTELLogsExporterNone OTELLogsExporterType = "none"
	// OTELLogsExporterOTLP represents a enum that enables the logs exporter via OTLP protocol.
	OTELLogsExporterOTLP OTELLogsExporterType = "otlp"
)

type OTELMetricsExporterType

type OTELMetricsExporterType string

OTELMetricsExporterType defines the type of OpenTelemetry metrics exporter.

const (
	// OTELMetricsExporterNone represents a enum that disables the metrics exporter.
	OTELMetricsExporterNone OTELMetricsExporterType = "none"
	// OTELMetricsExporterOTLP represents a enum that enables the metrics exporter via OTLP protocol.
	OTELMetricsExporterOTLP OTELMetricsExporterType = "otlp"
	// OTELMetricsExporterPrometheus represents a enum that enables the metrics exporter via Prometheus.
	OTELMetricsExporterPrometheus OTELMetricsExporterType = "prometheus"
)

type OTLPCompressionType

type OTLPCompressionType string

OTLPCompressionType represents the compression type enum for OTLP.

const (
	// OTLPCompressionNone is the enum that disables compression.
	OTLPCompressionNone OTLPCompressionType = "none"
	// OTLPCompressionGzip is the enum that enable compression of gzip algorithm.
	OTLPCompressionGzip OTLPCompressionType = "gzip"
)

type OTLPConfig

type OTLPConfig struct {
	ServiceName            string              `env:"OTEL_SERVICE_NAME"                      help:"OpenTelemetry service name."`
	OtlpEndpoint           string              `env:"OTEL_EXPORTER_OTLP_ENDPOINT"            help:"OpenTelemetry receiver endpoint that is set as default for all types."`
	OtlpTracesEndpoint     string              `env:"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"     help:"OpenTelemetry endpoint for traces."`
	OtlpMetricsEndpoint    string              `env:"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"    help:"OpenTelemetry endpoint for metrics."`
	OtlpLogsEndpoint       string              `env:"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"       help:"OpenTelemetry endpoint for logs."`
	OtlpInsecure           *bool               `env:"OTEL_EXPORTER_OTLP_INSECURE"            help:"Disable LTS for OpenTelemetry exporters."`
	OtlpTracesInsecure     *bool               `env:"OTEL_EXPORTER_OTLP_TRACES_INSECURE"     help:"Disable LTS for OpenTelemetry traces exporter."`
	OtlpMetricsInsecure    *bool               `env:"OTEL_EXPORTER_OTLP_METRICS_INSECURE"    help:"Disable LTS for OpenTelemetry metrics exporter."`
	OtlpLogsInsecure       *bool               `env:"OTEL_EXPORTER_OTLP_LOGS_INSECURE"       help:"Disable LTS for OpenTelemetry logs exporter."`
	OtlpProtocol           OTLPProtocol        `env:"OTEL_EXPORTER_OTLP_PROTOCOL"            help:"OpenTelemetry receiver protocol for all types."`
	OtlpTracesProtocol     OTLPProtocol        `env:"OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"     help:"OpenTelemetry receiver protocol for traces."`
	OtlpMetricsProtocol    OTLPProtocol        `env:"OTEL_EXPORTER_OTLP_METRICS_PROTOCOL"    help:"OpenTelemetry receiver protocol for metrics."`
	OtlpLogsProtocol       OTLPProtocol        `env:"OTEL_EXPORTER_OTLP_LOGS_PROTOCOL"       help:"OpenTelemetry receiver protocol for logs."`
	OtlpCompression        OTLPCompressionType `` /* 153-byte string literal not displayed */
	OtlpTraceCompression   OTLPCompressionType `` /* 153-byte string literal not displayed */
	OtlpMetricsCompression OTLPCompressionType `` /* 153-byte string literal not displayed */
	OtlpLogsCompression    OTLPCompressionType `` /* 153-byte string literal not displayed */

	MetricsExporter  OTELMetricsExporterType `` /* 137-byte string literal not displayed */
	LogsExporter     OTELLogsExporterType    `default:"none" enum:"none,otlp"            env:"OTEL_LOGS_EXPORTER"            help:"Logs export type. Accept: none, otlp"`
	PrometheusPort   *uint                   `` /* 188-byte string literal not displayed */
	DisableGoMetrics *bool                   `                                                                               help:"Disable internal Go and process metrics"`
}

OTLPConfig contains configuration for OpenTelemetry exporter.

type OTLPProtocol

type OTLPProtocol string

OTLPProtocol represents the OTLP protocol enum.

const (
	// OTLPProtocolGRPC represents the gRPC OTLP protocol enum.
	OTLPProtocolGRPC OTLPProtocol = "grpc"
	// OTLPProtocolHTTPProtobuf represents the HTTP Protobuf OTLP protocol enum.
	OTLPProtocolHTTPProtobuf OTLPProtocol = "http/protobuf"
)

type OTelExporterResults

type OTelExporterResults struct {
	Tracer   *Tracer
	Meter    metricapi.Meter
	Logger   *slog.Logger
	Shutdown func(context.Context) error
}

OTelExporterResults contains outputs of OpenTelemetry exporters.

func SetupOTelExporters

func SetupOTelExporters(
	ctx context.Context,
	config *OTLPConfig,
	serviceVersion string,
	logger *slog.Logger,
) (*OTelExporterResults, error)

SetupOTelExporters set up OpenTelemetry exporters from configuration.

type Tracer

type Tracer struct {
	traceapi.Tracer
}

Tracer is the wrapper of traceapi.Tracer with user visibility on Hasura Console.

func NewTracer

func NewTracer(name string, opts ...traceapi.TracerOption) *Tracer

NewTracer creates a new OpenTelemetry tracer.

func (*Tracer) Start

func (t *Tracer) Start(
	ctx context.Context,
	spanName string,
	opts ...traceapi.SpanStartOption,
) (context.Context, traceapi.Span)

Start creates a span and a context.Context containing the newly-created span with `internal.visibility: "user"` so that it shows up in the Hasura Console.

func (*Tracer) StartInternal

func (t *Tracer) StartInternal(
	ctx context.Context,
	spanName string,
	opts ...traceapi.SpanStartOption,
) (context.Context, traceapi.Span)

StartInternal creates a span and a context.Context containing the newly-created span. It won't show up in the Hasura Console.

type TracingMiddlewareOption added in v0.2.0

type TracingMiddlewareOption func(*tracingMiddlewareOptions)

TracingMiddlewareOption abstracts a function to apply options to the tracing middleware.

func AllowRequestHeaders added in v0.2.0

func AllowRequestHeaders(names []string) TracingMiddlewareOption

AllowRequestHeaders return an option to set allowed request headers. If empty, all headers are allowed.

func AllowResponseHeaders added in v0.2.0

func AllowResponseHeaders(names []string) TracingMiddlewareOption

AllowResponseHeaders return an option to set allowed response headers. If empty, all headers are allowed.

func DebugPaths added in v0.2.0

func DebugPaths(paths []string) TracingMiddlewareOption

DebugPaths return an option to add request paths to be printed logs in the debug level. By default, metrics and health check endpoints are added to avoid noisy logs.

func DisableHighCardinalityMetrics added in v0.2.0

func DisableHighCardinalityMetrics(disabled bool) TracingMiddlewareOption

DisableHighCardinalityMetrics set the option to disable high cardinality http_path labels.

func DisableHighCardinalitySpans added in v0.2.0

func DisableHighCardinalitySpans(disabled bool) TracingMiddlewareOption

DisableHighCardinalitySpans set the option to disable high cardinality spans. The request path is removed from the span name.

func ResponseWriterWrapperFunc added in v0.2.0

func ResponseWriterWrapperFunc(wrapper NewWrapResponseWriterFunc) TracingMiddlewareOption

ResponseWriterWrapperFunc return an option to set the response writer wrapper function.

type WrapResponseWriter added in v0.2.0

type WrapResponseWriter interface {
	http.ResponseWriter
	// Status returns the HTTP status of the request, or 0 if one has not
	// yet been sent.
	Status() int
	// BytesWritten returns the total number of bytes sent to the client.
	BytesWritten() int
	// Tee causes the response body to be written to the given io.Writer in
	// addition to proxying the writes through. Only one io.Writer can be
	// tee'd to at once: setting a second one will overwrite the first.
	// Writes will be sent to the proxy before being written to this
	// io.Writer. It is illegal for the tee'd writer to be modified
	// concurrently with writes.
	Tee(w io.Writer)
	// Unwrap returns the original proxied target.
	Unwrap() http.ResponseWriter
	// Discard causes all writes to the original ResponseWriter be discarded,
	// instead writing only to the tee'd writer if it's set.
	// The caller is responsible for calling WriteHeader and Write on the
	// original ResponseWriter once the processing is done.
	Discard()
}

WrapResponseWriter is a proxy around an http.ResponseWriter that allows you to hook into various parts of the response process. The original work was derived from Chi's middleware, source: https://github.com/go-chi/chi/blob/master/middleware/wrap_writer.go

Jump to

Keyboard shortcuts

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