Documentation
¶
Overview ¶
Package gintelemetry provides opinionated OpenTelemetry bootstrap for Gin applications.
Index ¶
- Constants
- type Attribute
- type AttributeAPI
- func (AttributeAPI) Bool(key string, value bool) attribute.KeyValue
- func (AttributeAPI) Float64(key string, value float64) attribute.KeyValue
- func (AttributeAPI) Int(key string, value int) attribute.KeyValue
- func (AttributeAPI) Int64(key string, value int64) attribute.KeyValue
- func (AttributeAPI) String(key, value string) attribute.KeyValue
- func (AttributeAPI) Strings(key string, values []string) attribute.KeyValue
- type Config
- func (c Config) WithExporterRetries(retries int) Config
- func (c Config) WithGRPC() Config
- func (c Config) WithGlobalAttribute(key, value string) Config
- func (c Config) WithGlobalAttributes(attrs map[string]string) Config
- func (c Config) WithHTTP() Config
- func (c Config) WithInsecure(insecure bool) Config
- func (c Config) WithLogLevel(level Level) Config
- func (c Config) WithMTLS(certFile, keyFile, caFile string) Config
- func (c Config) WithNoRetry() Config
- func (c Config) WithProtocol(protocol Protocol) Config
- func (c Config) WithTLS(tls *TLSConfig) Config
- func (c Config) WithTrustedCA(caFile string) Config
- type Level
- type LogAPI
- func (l LogAPI) Debug(ctx context.Context, msg string, args ...any)
- func (l LogAPI) Error(ctx context.Context, msg string, args ...any)
- func (l LogAPI) Info(ctx context.Context, msg string, args ...any)
- func (l LogAPI) Logger() *slog.Logger
- func (l LogAPI) Warn(ctx context.Context, msg string, args ...any)
- func (l LogAPI) With(args ...any) *slog.Logger
- func (l LogAPI) WithGroup(name string) *slog.Logger
- type MetricAPI
- func (m MetricAPI) AddCounter(ctx context.Context, name string, value int64, attrs ...MetricAttribute)
- func (m MetricAPI) AddFloat64Counter(ctx context.Context, name string, value float64, attrs ...MetricAttribute)
- func (m MetricAPI) Counter(name string, opts ...metric.Int64CounterOption) metric.Int64Counter
- func (m MetricAPI) Float64Counter(name string, opts ...metric.Float64CounterOption) metric.Float64Counter
- func (m MetricAPI) Float64Gauge(name string, opts ...metric.Float64GaugeOption) metric.Float64Gauge
- func (m MetricAPI) Float64Histogram(name string, opts ...metric.Float64HistogramOption) metric.Float64Histogram
- func (m MetricAPI) Gauge(name string, opts ...metric.Int64GaugeOption) metric.Int64Gauge
- func (m MetricAPI) Histogram(name string, opts ...metric.Int64HistogramOption) metric.Int64Histogram
- func (m MetricAPI) IncrementCounter(ctx context.Context, name string, attrs ...MetricAttribute)
- func (m MetricAPI) RecordDuration(ctx context.Context, name string, duration time.Duration, ...)
- func (m MetricAPI) RecordFloat64Gauge(ctx context.Context, name string, value float64, attrs ...MetricAttribute)
- func (m MetricAPI) RecordFloat64Histogram(ctx context.Context, name string, value float64, attrs ...MetricAttribute)
- func (m MetricAPI) RecordGauge(ctx context.Context, name string, value int64, attrs ...MetricAttribute)
- func (m MetricAPI) RecordHistogram(ctx context.Context, name string, value int64, attrs ...MetricAttribute)
- type MetricAttribute
- type Protocol
- type TLSConfig
- type Telemetry
- func (t *Telemetry) Attr() AttributeAPI
- func (t *Telemetry) Flush(ctx context.Context) error
- func (t *Telemetry) Log() LogAPI
- func (t *Telemetry) LoggerProvider() *sdklog.LoggerProvider
- func (t *Telemetry) MeasureDuration(ctx context.Context, metricName string, fn func() error) error
- func (t *Telemetry) MeterProvider() *sdkmetric.MeterProvider
- func (t *Telemetry) Metric() MetricAPI
- func (t *Telemetry) Shutdown(ctx context.Context) error
- func (t *Telemetry) ShutdownDone() <-chan struct{}
- func (t *Telemetry) Trace() TraceAPI
- func (t *Telemetry) TraceFunction(ctx context.Context, spanName string, fn func(context.Context) error) error
- func (t *Telemetry) TracerProvider() *sdktrace.TracerProvider
- func (t *Telemetry) WithSpan(ctx context.Context, spanName string, fn func(context.Context) error) error
- type TraceAPI
- func (TraceAPI) AddEvent(ctx context.Context, name string, attrs ...Attribute)
- func (TraceAPI) RecordError(ctx context.Context, err error)
- func (TraceAPI) SetAttributes(ctx context.Context, attrs ...Attribute)
- func (TraceAPI) SetStatus(ctx context.Context, code codes.Code, description string)
- func (TraceAPI) SpanFromContext(ctx context.Context) trace.Span
- func (t TraceAPI) StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, func())
- func (t TraceAPI) StartSpanWithAttributes(ctx context.Context, name string, attrs ...Attribute) (context.Context, func())
Constants ¶
const ( LevelDebug = slog.LevelDebug LevelInfo = slog.LevelInfo LevelWarn = slog.LevelWarn LevelError = slog.LevelError )
Status codes for span status
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AttributeAPI ¶
type AttributeAPI struct{}
AttributeAPI provides unified attribute builders that work across all telemetry types. Attributes created with this API can be used for tracing, metrics, and logging.
func (AttributeAPI) Bool ¶
func (AttributeAPI) Bool(key string, value bool) attribute.KeyValue
Bool creates a bool-valued attribute.
func (AttributeAPI) Float64 ¶
func (AttributeAPI) Float64(key string, value float64) attribute.KeyValue
Float64 creates a float64-valued attribute.
func (AttributeAPI) Int ¶
func (AttributeAPI) Int(key string, value int) attribute.KeyValue
Int creates an int-valued attribute.
func (AttributeAPI) Int64 ¶
func (AttributeAPI) Int64(key string, value int64) attribute.KeyValue
Int64 creates an int64-valued attribute.
type Config ¶
type Config struct {
// ServiceName is required and reported in all telemetry data.
ServiceName string
// Endpoint is the OTLP collector endpoint.
// For gRPC: "localhost:4317" (default port 4317)
// For HTTP: "localhost:4318" (default port 4318)
// Defaults to OTEL_EXPORTER_OTLP_ENDPOINT environment variable.
Endpoint string
// Protocol specifies the transport protocol (grpc or http).
// Defaults to ProtocolGRPC.
Protocol Protocol
// Insecure determines whether to use a non-TLS connection.
// Defaults to true if not explicitly set.
// Set to false to enable TLS.
Insecure bool
// TLS configuration for secure connections (when Insecure = false).
TLS *TLSConfig
// LogLevel sets the minimum log level. Defaults to LevelInfo.
// Use LevelDebug, LevelInfo, LevelWarn, LevelError.
LogLevel Level
// GlobalAttributes are added to all telemetry (traces, metrics, logs).
// Use this for team names, environment, region, etc.
GlobalAttributes map[string]string
// ShutdownTimeout is the maximum time to wait for telemetry shutdown.
// Defaults to 10 seconds if not set.
ShutdownTimeout time.Duration
// SetGlobalProvider controls whether to set the global OpenTelemetry provider.
// WARNING: Setting this to true makes the telemetry system use global state,
// which can cause issues with concurrent tests and multiple service instances.
// Only enable this if you rely on instrumentation libraries that require the
// global provider. The default (false) provides isolated, instance-based telemetry.
SetGlobalProvider bool
// ExporterRetries specifies the number of retry attempts when creating exporters.
// This is useful in environments like Kubernetes where the collector may not be
// immediately available. Set to 0 for no retries (fail fast), or a positive number
// for retry attempts with exponential backoff. Defaults to 3 retries.
ExporterRetries int
}
Config holds the configuration for initializing the telemetry stack.
func NewTestConfig ¶
NewTestConfig creates a configuration suitable for testing with no-op exporters. This allows tests to run without requiring a real OTLP collector.
The returned config uses insecure connections and points to a localhost endpoint that doesn't need to exist (the exporter retries are set to 0 for fast failure).
Example:
func TestMyHandler(t *testing.T) {
ctx := context.Background()
tel, router, err := gintelemetry.Start(ctx, gintelemetry.NewTestConfig("test-service"))
if err != nil {
t.Fatalf("failed to start telemetry: %v", err)
}
defer tel.Shutdown(ctx)
// Test your handlers...
router.GET("/test", myHandler)
}
func (Config) WithExporterRetries ¶
func (Config) WithGlobalAttribute ¶
func (Config) WithGlobalAttributes ¶
func (Config) WithInsecure ¶
func (Config) WithLogLevel ¶
func (Config) WithNoRetry ¶
func (Config) WithProtocol ¶
func (Config) WithTrustedCA ¶
type LogAPI ¶
type LogAPI struct {
// contains filtered or unexported fields
}
func (LogAPI) Debug ¶
Debug logs a debug message with trace correlation. The context should contain an active span from the request or manually created span. If ctx has no span, logs will still be recorded but without trace correlation. Using context.Background() is safe but loses correlation benefits.
Example:
tel.Log().Debug(ctx, "cache hit", "key", cacheKey, "ttl", ttl)
func (LogAPI) Error ¶
Error logs an error message with trace correlation. The context should contain an active span from the request or manually created span. If ctx has no span, logs will still be recorded but without trace correlation. Using context.Background() is safe but loses correlation benefits.
Example:
tel.Log().Error(ctx, "database query failed", "error", err.Error(), "query", query)
func (LogAPI) Info ¶
Info logs an informational message with trace correlation. The context should contain an active span from the request or manually created span. If ctx has no span, logs will still be recorded but without trace correlation. Using context.Background() is safe but loses correlation benefits.
Example:
tel.Log().Info(ctx, "user logged in", "user_id", userID, "ip", clientIP)
func (LogAPI) Warn ¶
Warn logs a warning message with trace correlation. The context should contain an active span from the request or manually created span. If ctx has no span, logs will still be recorded but without trace correlation. Using context.Background() is safe but loses correlation benefits.
Example:
tel.Log().Warn(ctx, "rate limit approaching", "current", count, "limit", maxCount)
type MetricAPI ¶
type MetricAPI struct {
// contains filtered or unexported fields
}
MetricAPI provides functions for recording metrics.
IMPORTANT: Metrics are cached internally (up to 10,000 unique combinations). Do NOT use dynamic values in metric names. Use attributes instead:
✗ BAD: tel.Metric().Counter("user_" + userID).Add(ctx, 1)
✓ GOOD: tel.Metric().IncrementCounter(ctx, "user_events", tel.Attr().String("user.id", userID))
If you exceed the cache limit, metrics will still work but won't be cached, which may impact performance.
Context Usage: All metric recording methods accept a context for trace correlation. If the context contains an active span, metrics can be correlated with traces. Using context.Background() is safe but loses correlation benefits.
func (MetricAPI) AddCounter ¶
func (m MetricAPI) AddCounter(ctx context.Context, name string, value int64, attrs ...MetricAttribute)
AddCounter adds a value to a counter with optional attributes. This is a convenience method equivalent to Counter(name).Add(ctx, value, metric.WithAttributes(attrs...)).
func (MetricAPI) AddFloat64Counter ¶
func (m MetricAPI) AddFloat64Counter(ctx context.Context, name string, value float64, attrs ...MetricAttribute)
AddFloat64Counter adds a value to a float64 counter with optional attributes. This is a convenience method equivalent to Float64Counter(name).Add(ctx, value, metric.WithAttributes(attrs...)).
func (MetricAPI) Counter ¶
func (m MetricAPI) Counter(name string, opts ...metric.Int64CounterOption) metric.Int64Counter
func (MetricAPI) Float64Counter ¶
func (m MetricAPI) Float64Counter(name string, opts ...metric.Float64CounterOption) metric.Float64Counter
func (MetricAPI) Float64Gauge ¶
func (m MetricAPI) Float64Gauge(name string, opts ...metric.Float64GaugeOption) metric.Float64Gauge
func (MetricAPI) Float64Histogram ¶
func (m MetricAPI) Float64Histogram(name string, opts ...metric.Float64HistogramOption) metric.Float64Histogram
func (MetricAPI) Gauge ¶
func (m MetricAPI) Gauge(name string, opts ...metric.Int64GaugeOption) metric.Int64Gauge
func (MetricAPI) Histogram ¶
func (m MetricAPI) Histogram(name string, opts ...metric.Int64HistogramOption) metric.Int64Histogram
func (MetricAPI) IncrementCounter ¶
func (m MetricAPI) IncrementCounter(ctx context.Context, name string, attrs ...MetricAttribute)
IncrementCounter increments a counter by 1 with optional attributes. This is a convenience method equivalent to Counter(name).Add(ctx, 1, metric.WithAttributes(attrs...)).
func (MetricAPI) RecordDuration ¶
func (m MetricAPI) RecordDuration(ctx context.Context, name string, duration time.Duration, attrs ...MetricAttribute)
RecordDuration records a duration as milliseconds to a histogram with optional attributes. This is a convenience method that converts the duration to milliseconds and records it.
func (MetricAPI) RecordFloat64Gauge ¶
func (m MetricAPI) RecordFloat64Gauge(ctx context.Context, name string, value float64, attrs ...MetricAttribute)
RecordFloat64Gauge records a float64 gauge value with optional attributes. This is a convenience method equivalent to Float64Gauge(name).Record(ctx, value, metric.WithAttributes(attrs...)).
func (MetricAPI) RecordFloat64Histogram ¶
func (m MetricAPI) RecordFloat64Histogram(ctx context.Context, name string, value float64, attrs ...MetricAttribute)
RecordFloat64Histogram records a float64 histogram value with optional attributes. This is a convenience method equivalent to Float64Histogram(name).Record(ctx, value, metric.WithAttributes(attrs...)).
func (MetricAPI) RecordGauge ¶
func (m MetricAPI) RecordGauge(ctx context.Context, name string, value int64, attrs ...MetricAttribute)
RecordGauge records a gauge value with optional attributes. This is a convenience method equivalent to Gauge(name).Record(ctx, value, metric.WithAttributes(attrs...)).
func (MetricAPI) RecordHistogram ¶
func (m MetricAPI) RecordHistogram(ctx context.Context, name string, value int64, attrs ...MetricAttribute)
RecordHistogram records a histogram value with optional attributes. This is a convenience method equivalent to Histogram(name).Record(ctx, value, metric.WithAttributes(attrs...)).
type MetricAttribute ¶
type Telemetry ¶
type Telemetry struct {
// contains filtered or unexported fields
}
func (*Telemetry) Attr ¶
func (t *Telemetry) Attr() AttributeAPI
Attr returns the unified attribute builder for use across all telemetry types. Attributes created with this API work for tracing, metrics, and logging.
Example:
attrs := []attribute.KeyValue{
tel.Attr().String("user.id", "123"),
tel.Attr().Int("status", 200),
}
tel.Trace().SetAttributes(ctx, attrs...)
tel.Metric().Counter("requests").Add(ctx, 1, metric.WithAttributes(attrs...))
func (*Telemetry) LoggerProvider ¶
func (t *Telemetry) LoggerProvider() *sdklog.LoggerProvider
func (*Telemetry) MeasureDuration ¶
MeasureDuration executes fn and records its duration to a histogram metric. If fn returns an error, it's automatically recorded in the current span (if one exists).
Example:
err := tel.MeasureDuration(ctx, "db.query.duration", func() error {
return db.Query(ctx, ...)
})
func (*Telemetry) MeterProvider ¶
func (t *Telemetry) MeterProvider() *sdkmetric.MeterProvider
func (*Telemetry) ShutdownDone ¶
func (t *Telemetry) ShutdownDone() <-chan struct{}
func (*Telemetry) TraceFunction ¶
func (t *Telemetry) TraceFunction(ctx context.Context, spanName string, fn func(context.Context) error) error
TraceFunction creates a span, executes fn with the span context, and ends the span. Errors returned by fn are automatically recorded in the span.
Example:
err := tel.TraceFunction(ctx, "process.order", func(ctx context.Context) error {
tel.Log().Info(ctx, "processing order")
return processOrder(ctx, orderID)
})
func (*Telemetry) TracerProvider ¶
func (t *Telemetry) TracerProvider() *sdktrace.TracerProvider
func (*Telemetry) WithSpan ¶
func (t *Telemetry) WithSpan(ctx context.Context, spanName string, fn func(context.Context) error) error
WithSpan creates a span, executes fn with the span context, and ends the span. This is an alias for TraceFunction for more ergonomic usage.
Example:
err := tel.WithSpan(ctx, "database.query", func(ctx context.Context) error {
return db.Query(ctx, query)
})
type TraceAPI ¶
type TraceAPI struct {
// contains filtered or unexported fields
}
func (TraceAPI) AddEvent ¶
AddEvent adds an event to the current span if one exists and is recording. Events represent significant points in time within a span's duration. If no span exists or the span is not recording, this is a safe no-op.
Example:
tel.Trace().AddEvent(ctx, "cache.miss",
tel.Attr().String("cache.key", key),
)
func (TraceAPI) RecordError ¶
RecordError records an error in the current span if one exists and is recording. If no span exists or the span is not recording, this is a safe no-op. This method never returns an error itself and never panics.
The error is recorded with the span status set to Error.
Example:
if err != nil {
tel.Trace().RecordError(ctx, err)
return err
}
func (TraceAPI) SetAttributes ¶
SetAttributes adds attributes to the current span if one exists and is recording. If no span exists or the span is not recording, this is a safe no-op. The context must contain an active span for attributes to be recorded.
Example:
tel.Trace().SetAttributes(ctx,
tel.Attr().String("user.id", userID),
tel.Attr().Int("items.count", len(items)),
)
func (TraceAPI) SetStatus ¶
SetStatus sets the status of the current span if one exists and is recording. Use this to mark a span as successful (StatusOK), failed (StatusError), or unset (StatusUnset). If no span exists or the span is not recording, this is a safe no-op.
Example:
tel.Trace().SetStatus(ctx, gintelemetry.StatusOK, "operation completed successfully")
func (TraceAPI) SpanFromContext ¶
SpanFromContext returns the current span from the context. This is useful for advanced use cases where you need direct access to the span.
func (TraceAPI) StartSpan ¶
func (t TraceAPI) StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, func())
StartSpan creates a new span and returns a context containing the span and a function to end it. The returned context should be used for all operations within this span's scope. Always call the returned function (typically with defer) to properly end the span.
Example:
ctx, stop := tel.Trace().StartSpan(ctx, "database.query") defer stop() // ... perform database query ...
func (TraceAPI) StartSpanWithAttributes ¶
func (t TraceAPI) StartSpanWithAttributes(ctx context.Context, name string, attrs ...Attribute) (context.Context, func())
StartSpanWithAttributes creates a new span with attributes and returns a context and end function. This is a convenience method that combines StartSpan with initial attributes.
Example:
ctx, stop := tel.Trace().StartSpanWithAttributes(ctx, "db.query",
tel.Attr().String("db.system", "postgres"),
tel.Attr().String("db.operation", "SELECT"),
)
defer stop()