Documentation
¶
Overview ¶
Package telemetry provides functionality for collecting and exporting telemetry data, including distributed tracing and metrics.
This file contains the configuration structures and loading functions for the telemetry package. It defines the configuration schema for all telemetry components, including tracing, metrics, and OTLP exporters. The configuration can be loaded from a koanf instance, and default values are provided for quick setup in development environments.
Package telemetry provides functionality for collecting and exporting telemetry data, including distributed tracing and metrics.
This file contains default configuration functions for the telemetry package. These functions provide sensible default values for all telemetry components, making it easy to get started with telemetry without having to specify every configuration option. The defaults are suitable for development environments and can be overridden as needed for production use.
Package telemetry provides functionality for collecting and exporting telemetry data, including distributed tracing and metrics.
This package integrates with OpenTelemetry and Prometheus to provide a unified interface for telemetry collection. It supports tracing requests across service boundaries, collecting metrics about application performance, and exporting this data to various backends for analysis and visualization.
Key features:
- Distributed tracing with OpenTelemetry
- Metrics collection with OpenTelemetry and Prometheus
- HTTP middleware for automatic request tracing and metrics
- Database operation tracing and metrics
- Error tracking and metrics
- Configurable exporters for different backends
The package provides several main components:
- TelemetryProvider: A unified provider for both tracing and metrics
- Tracer: An interface for creating and managing trace spans
- Span: An interface representing a single trace span
- MetricsProvider: A provider for metrics collection
Example usage:
// Initialize telemetry provider
provider, err := telemetry.NewTelemetryProvider(ctx, logger, config)
if err != nil {
logger.Fatal(ctx, "Failed to initialize telemetry", zap.Error(err))
}
defer provider.Shutdown(ctx)
// Create a span
ctx, span := provider.Tracer().Start(ctx, "operation_name")
defer span.End()
// Add attributes to the span
span.SetAttributes(attribute.String("key", "value"))
// Record an error
if err := someOperation(); err != nil {
span.RecordError(err)
telemetry.RecordErrorMetric(ctx, "operation_error", "someOperation")
return err
}
// Record HTTP metrics
telemetry.RecordHTTPRequest(ctx, "GET", "/api/resource", 200, duration, responseSize)
// Record database operation metrics
telemetry.RecordDBOperation(ctx, "query", "users_db", "users", duration, nil)
The package also provides utility functions for wrapping operations with spans:
// Execute a function with a span
err := telemetry.WithSpan(ctx, "operation_name", func(ctx context.Context) error {
// Operation code here
return nil
})
// Execute a function with a span and measure duration
duration, err := telemetry.WithSpanTimed(ctx, "timed_operation", func(ctx context.Context) error {
// Operation code here
return nil
})
For HTTP servers, the package provides middleware for automatic request tracing and metrics:
// Create HTTP middleware
middleware := provider.NewHTTPMiddleware()
// Apply middleware to HTTP handler
http.Handle("/", middleware(myHandler))
The telemetry package is designed to be used throughout the application to provide comprehensive visibility into application performance and behavior.
Package telemetry provides functionality for collecting and exporting telemetry data, including distributed tracing and metrics.
This file contains HTTP-specific telemetry components, including middleware and instrumentation for HTTP handlers and clients. It provides functions for adding tracing to HTTP requests and responses, propagating trace context across service boundaries, and recording span attributes and errors in HTTP handlers.
Package telemetry provides functionality for collecting and exporting telemetry data, including distributed tracing and metrics.
This file contains metrics-specific components of the telemetry package, including the MetricsProvider for collecting and exporting metrics, common metrics for HTTP, database, and application operations, and utility functions for recording metrics. It integrates with OpenTelemetry and Prometheus to provide a comprehensive metrics collection and reporting system.
Package telemetry provides functionality for monitoring and tracing application behavior. It offers a unified interface for both metrics collection and distributed tracing using OpenTelemetry and Prometheus.
Package telemetry provides functionality for collecting and exporting telemetry data, including distributed tracing and metrics.
This file contains utility functions for working with spans in the context. It provides helper functions for retrieving and manipulating spans, which are useful for testing, debugging, and integrating with other parts of the application that need access to the current span.
Package telemetry provides functionality for collecting and exporting telemetry data, including distributed tracing and metrics.
This file contains the tracing-specific components of the telemetry package, including interfaces and implementations for creating and managing trace spans. It provides abstractions over the underlying OpenTelemetry tracing implementation, making it easier to use tracing throughout the application and to mock tracing in tests.
Index ¶
- func AddSpanAttributes(ctx context.Context, attrs ...attribute.KeyValue)
- func CreatePrometheusHandler() http.Handler
- func DecrementRequestsInFlight(ctx context.Context, method, path string)
- func GetSpanFromContext(ctx context.Context) trace.Span
- func GetTelemetryDefaults(serviceName ...string) map[string]interface{}
- func IncrementRequestsInFlight(ctx context.Context, method, path string)
- func InitCommonMetrics(mp *MetricsProvider) error
- func InstrumentClient(client *http.Client, opts ...otelhttp.Option) *http.Client
- func InstrumentHandler(handler http.Handler, operation string, opts ...otelhttp.Option) http.Handler
- func IsMetricsEnabled(k *koanf.Koanf) bool
- func NewHTTPMiddleware(logger *logging.ContextLogger) func(http.Handler) http.Handler
- func RecordDBOperation(ctx context.Context, operation, database, collection string, ...)
- func RecordErrorMetric(ctx context.Context, errorType, operation string)
- func RecordErrorSpan(ctx context.Context, err error, opts ...trace.EventOption)
- func RecordHTTPRequest(ctx context.Context, method, path string, statusCode int, ...)
- func StartSpan(ctx context.Context, name string) (context.Context, trace.Span)
- func UpdateDBConnections(ctx context.Context, database string, delta int64)
- func WithSpan(ctx context.Context, name string, fn func(context.Context) error) error
- func WithSpanTimed(ctx context.Context, name string, fn func(context.Context) error) (time.Duration, error)
- type Config
- type HTTPConfig
- type MetricsConfig
- type MetricsProvider
- type OTLPConfig
- type PrometheusConfig
- type Span
- type TelemetryProvider
- func (tp *TelemetryProvider) CreatePrometheusHandler() http.Handler
- func (tp *TelemetryProvider) InstrumentHandler(handler http.Handler, operation string) http.Handler
- func (tp *TelemetryProvider) Meter() metric.Meter
- func (tp *TelemetryProvider) NewHTTPMiddleware() func(http.Handler) http.Handler
- func (tp *TelemetryProvider) Shutdown(ctx context.Context) error
- func (tp *TelemetryProvider) Tracer() trace.Tracer
- type Tracer
- type TracingConfig
- type TracingProvider
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddSpanAttributes ¶
AddSpanAttributes adds attributes to the current span in context. This is useful for adding additional information to a span.
Parameters:
- ctx: The context containing the span
- attrs: The attributes to add to the span
func CreatePrometheusHandler ¶
CreatePrometheusHandler creates a handler for the /metrics endpoint
Returns:
- http.Handler: The Prometheus metrics handler
func DecrementRequestsInFlight ¶
DecrementRequestsInFlight decrements the in-flight requests counter
Parameters:
- ctx: The context for the operation
- method: The HTTP method
- path: The HTTP path
func GetSpanFromContext ¶
GetSpanFromContext retrieves the current span from the context. This is a helper function for testing and debugging.
Parameters:
- ctx: The context containing the span
Returns:
- trace.Span: The span from the context, or nil if no span is present
func GetTelemetryDefaults ¶
GetTelemetryDefaults returns default values for telemetry configuration
Parameters:
- serviceName: The name of the service (optional, defaults to "service")
Returns:
- map[string]interface{}: Default values for telemetry configuration
func IncrementRequestsInFlight ¶
IncrementRequestsInFlight increments the in-flight requests counter
Parameters:
- ctx: The context for the operation
- method: The HTTP method
- path: The HTTP path
func InitCommonMetrics ¶
func InitCommonMetrics(mp *MetricsProvider) error
InitCommonMetrics initializes common metrics
Parameters:
- mp: The metrics provider
Returns:
- error: An error if the metrics initialization fails
func InstrumentClient ¶
InstrumentClient wraps an http.Client with OpenTelemetry instrumentation. This adds tracing to all HTTP requests made by the provided client.
Parameters:
- client: The HTTP client to instrument
- opts: Additional options for the instrumentation
Returns:
- *http.Client: The instrumented HTTP client
func InstrumentHandler ¶
func InstrumentHandler(handler http.Handler, operation string, opts ...otelhttp.Option) http.Handler
InstrumentHandler wraps an http.Handler with OpenTelemetry instrumentation. This adds tracing to all HTTP requests handled by the provided handler.
Parameters:
- handler: The HTTP handler to instrument
- operation: The name of the operation for tracing
- opts: Additional options for the instrumentation
Returns:
- http.Handler: The instrumented HTTP handler
func IsMetricsEnabled ¶
IsMetricsEnabled returns whether metrics are enabled
Parameters:
- k: The koanf instance to load configuration from
Returns:
- bool: Whether metrics are enabled
func NewHTTPMiddleware ¶
NewHTTPMiddleware creates a new middleware for HTTP request tracing. This middleware adds tracing to all HTTP requests and logs request information.
Parameters:
- logger: The logger to use for logging request information
Returns:
- func(http.Handler) http.Handler: The middleware function
func RecordDBOperation ¶
func RecordDBOperation(ctx context.Context, operation, database, collection string, duration time.Duration, err error)
RecordDBOperation records metrics for a database operation
Parameters:
- ctx: The context for the operation
- operation: The database operation
- database: The database name
- collection: The collection or table name
- duration: The operation duration
- err: The error if the operation failed
func RecordErrorMetric ¶
RecordErrorMetric records an application error in metrics
Parameters:
- ctx: The context for the operation
- errorType: The type of error
- operation: The operation that failed
func RecordErrorSpan ¶
func RecordErrorSpan(ctx context.Context, err error, opts ...trace.EventOption)
RecordErrorSpan records an error on the current span in context. This is useful for recording errors that occur during a traced operation.
Parameters:
- ctx: The context containing the span
- err: The error to record
- opts: Additional options for the error event
func RecordHTTPRequest ¶
func RecordHTTPRequest(ctx context.Context, method, path string, statusCode int, duration time.Duration, responseSize int64)
RecordHTTPRequest records metrics for an HTTP request
Parameters:
- ctx: The context for the operation
- method: The HTTP method
- path: The HTTP path
- statusCode: The HTTP status code
- duration: The request duration
- responseSize: The response size in bytes
func StartSpan ¶
StartSpan is a helper function to start a new span from a context. This is useful for tracing operations within a request.
Parameters:
- ctx: The context to start the span from
- name: The name of the span
Returns:
- context.Context: The context with the span
- trace.Span: The span
func UpdateDBConnections ¶
UpdateDBConnections updates the open database connections counter
Parameters:
- ctx: The context for the operation
- database: The database name
- delta: The change in the number of connections
func WithSpan ¶
WithSpan wraps a function with a span for tracing. This utility function creates a new span with the given name, executes the provided function with the context containing the span, and automatically ends the span when the function completes. It's a convenient way to add tracing to any function without having to manually create and end spans.
The span will be created as a child of any existing span in the provided context, allowing for proper trace context propagation and hierarchical span relationships.
Example usage:
err := telemetry.WithSpan(ctx, "database_operation", func(ctx context.Context) error {
return db.ExecuteQuery(ctx, query)
})
Parameters:
- ctx: The context to start the span from. This should contain any parent span.
- name: The name of the span, which should describe the operation being performed.
- fn: The function to execute within the span. This function receives the context containing the span and should pass it to any operations that should be included in the span.
Returns:
- error: The error returned by the function, if any. This allows for transparent error propagation from the wrapped function.
func WithSpanTimed ¶
func WithSpanTimed(ctx context.Context, name string, fn func(context.Context) error) (time.Duration, error)
WithSpanTimed wraps a function with a span and records the execution time. This utility function is similar to WithSpan, but it also measures and returns the execution time of the wrapped function. It creates a new span with the given name, executes the provided function with the context containing the span, records the execution time as a span attribute, and automatically ends the span when the function completes.
The execution time is recorded as a "duration_ms" attribute on the span, making it visible in trace visualizations. If the function returns an error, it is also recorded on the span.
Example usage:
duration, err := telemetry.WithSpanTimed(ctx, "expensive_operation", func(ctx context.Context) error {
return performExpensiveOperation(ctx)
})
logger.Info(ctx, "Operation completed", zap.Duration("duration", duration))
Parameters:
- ctx: The context to start the span from. This should contain any parent span.
- name: The name of the span, which should describe the operation being performed.
- fn: The function to execute within the span. This function receives the context containing the span and should pass it to any operations that should be included in the span.
Returns:
- time.Duration: The execution time of the function, which can be used for logging or other purposes outside the span.
- error: The error returned by the function, if any. This allows for transparent error propagation from the wrapped function.
Types ¶
type Config ¶
type Config struct {
// Enabled indicates whether telemetry is enabled
Enabled bool `mapstructure:"enabled"`
// ServiceName is the name of the service
ServiceName string `mapstructure:"service_name"`
// Environment is the environment the service is running in
Environment string `mapstructure:"environment"`
// Version is the version of the service
Version string `mapstructure:"version"`
// ShutdownTimeout is the timeout for shutting down telemetry in seconds
ShutdownTimeout int `mapstructure:"shutdown_timeout"`
// OTLP is the configuration for the OTLP exporter
OTLP OTLPConfig `mapstructure:"otlp"`
// Tracing is the configuration for tracing
Tracing TracingConfig `mapstructure:"tracing"`
// Metrics is the configuration for metrics
Metrics MetricsConfig `mapstructure:"metrics"`
// HTTP is the configuration for HTTP telemetry
HTTP HTTPConfig `mapstructure:"http"`
}
Config holds all telemetry configuration
func DefaultConfig ¶ added in v1.5.0
func DefaultConfig() Config
DefaultConfig returns a default configuration for telemetry. This function provides a complete default configuration for all telemetry components, including tracing, metrics, and HTTP telemetry. The defaults are suitable for development environments and include:
- Service name: "service"
- Environment: "development"
- Version: "1.0.0"
- Enabled telemetry with a 5-second shutdown timeout
- Default OTLP, tracing, metrics, and HTTP configurations
Returns:
- Config: A complete default configuration for telemetry
func LoadConfig ¶
LoadConfig loads telemetry configuration from koanf
Parameters:
- k: The koanf instance to load configuration from
Returns:
- Config: The loaded telemetry configuration
type HTTPConfig ¶
type HTTPConfig struct {
// TracingEnabled indicates whether HTTP tracing is enabled
TracingEnabled bool `mapstructure:"tracing_enabled"`
}
HTTPConfig holds configuration for HTTP telemetry
func DefaultHTTPConfig ¶ added in v1.5.0
func DefaultHTTPConfig() HTTPConfig
DefaultHTTPConfig returns a default configuration for HTTP telemetry. This function provides default values for the HTTP telemetry configuration, which controls how HTTP requests and responses are traced and monitored. The defaults include:
- TracingEnabled: true (HTTP request tracing is enabled)
With these defaults, all HTTP requests will be traced, allowing you to see the full request flow in your distributed tracing system. This is useful for debugging and monitoring HTTP-based services.
Returns:
- HTTPConfig: A default configuration for HTTP telemetry
type MetricsConfig ¶
type MetricsConfig struct {
// Enabled indicates whether metrics are enabled
Enabled bool `mapstructure:"enabled"`
// ReportingFreq is the frequency of metrics reporting in seconds
ReportingFreq int `mapstructure:"reporting_frequency_seconds"`
// Prometheus is the configuration for Prometheus metrics
Prometheus PrometheusConfig `mapstructure:"prometheus"`
}
MetricsConfig holds configuration for metrics
func DefaultMetricsConfig ¶ added in v1.5.0
func DefaultMetricsConfig() MetricsConfig
DefaultMetricsConfig returns a default configuration for metrics collection. This function provides default values for the metrics configuration, which controls how metrics are collected and reported. The defaults include:
- Enabled: true (metrics collection is enabled)
- ReportingFreq: 15 seconds (metrics are reported every 15 seconds)
- Prometheus: Default Prometheus configuration (see DefaultPrometheusConfig)
These defaults are suitable for most environments. You may want to adjust the reporting frequency based on your monitoring needs and system load.
Returns:
- MetricsConfig: A default configuration for metrics collection
type MetricsProvider ¶
type MetricsProvider struct {
// contains filtered or unexported fields
}
MetricsProvider holds the metrics provider and meters
func NewMetricsProvider ¶
func NewMetricsProvider(ctx context.Context, logger *logging.ContextLogger, k *koanf.Koanf) (*MetricsProvider, error)
NewMetricsProvider creates a new metrics provider
Parameters:
- ctx: The context for the operation
- logger: The logger to use for logging metrics events
- k: The koanf instance to load configuration from
Returns:
- *MetricsProvider: The metrics provider
- error: An error if the metrics provider creation fails
func (*MetricsProvider) Meter ¶
func (mp *MetricsProvider) Meter() metric.Meter
Meter returns the meter
Returns:
- metric.Meter: The OpenTelemetry meter
type OTLPConfig ¶
type OTLPConfig struct {
// Endpoint is the OTLP endpoint
Endpoint string `mapstructure:"endpoint"`
// Insecure indicates whether to use insecure connections
Insecure bool `mapstructure:"insecure"`
// Timeout is the timeout for OTLP operations in seconds
Timeout int `mapstructure:"timeout_seconds"`
}
OTLPConfig holds configuration for OTLP exporter
func DefaultOTLPConfig ¶ added in v1.5.0
func DefaultOTLPConfig() OTLPConfig
DefaultOTLPConfig returns a default configuration for the OTLP exporter. This function provides default values for the OpenTelemetry Protocol (OTLP) exporter, which is used to send telemetry data to an OTLP-compatible backend. The defaults include:
- Endpoint: "localhost:4317" (standard OTLP gRPC endpoint)
- Insecure: true (no TLS for development environments)
- Timeout: 5 seconds for OTLP operations
These defaults are suitable for development with a local OpenTelemetry Collector. For production environments, you should configure a secure endpoint and adjust the timeout.
Returns:
- OTLPConfig: A default configuration for the OTLP exporter
type PrometheusConfig ¶
type PrometheusConfig struct {
// Enabled indicates whether Prometheus metrics are enabled
Enabled bool `mapstructure:"enabled"`
// Listen is the address to listen on for Prometheus metrics
Listen string `mapstructure:"listen"`
// Path is the path to expose Prometheus metrics on
Path string `mapstructure:"path"`
}
PrometheusConfig holds configuration for Prometheus metrics
func DefaultPrometheusConfig ¶ added in v1.5.0
func DefaultPrometheusConfig() PrometheusConfig
DefaultPrometheusConfig returns a default configuration for Prometheus metrics. This function provides default values for the Prometheus metrics configuration, which controls how metrics are exposed for scraping by Prometheus. The defaults include:
- Enabled: true (Prometheus metrics endpoint is enabled)
- Listen: "0.0.0.0:8089" (listen on all interfaces, port 8089)
- Path: "/metrics" (standard Prometheus metrics endpoint path)
These defaults allow Prometheus to scrape metrics from the application on the standard /metrics endpoint. You may need to adjust the listen address and port based on your network configuration and security requirements.
Returns:
- PrometheusConfig: A default configuration for Prometheus metrics
type Span ¶ added in v1.5.0
type Span interface {
// End completes the span.
// This should be called when the operation represented by the span is finished.
// It is typically used in a defer statement after creating a span.
End()
// SetAttributes sets attributes on the span.
// Attributes provide additional context about the operation being traced.
//
// Parameters:
// - attributes: Key-value pairs to add as attributes to the span.
SetAttributes(attributes ...attribute.KeyValue)
// RecordError records an error on the span.
// This marks the span as having encountered an error and adds error details.
//
// Parameters:
// - err: The error to record.
// - opts: Additional options for the error event.
RecordError(err error, opts ...trace.EventOption)
}
Span represents a tracing span that can be used across packages. It provides methods for ending the span, setting attributes, and recording errors. This interface abstracts away the underlying tracing implementation, allowing for easier testing and flexibility in choosing tracing backends.
type TelemetryProvider ¶
type TelemetryProvider struct {
// contains filtered or unexported fields
}
TelemetryProvider is a unified provider for tracing and metrics. It encapsulates both metrics and tracing functionality, providing a single entry point for all telemetry operations in the application. The provider manages the lifecycle of telemetry components, including initialization and shutdown.
TelemetryProvider implements a facade pattern, hiding the complexity of the underlying telemetry implementations and providing a simple, consistent interface for the application.
func NewTelemetryProvider ¶
func NewTelemetryProvider(ctx context.Context, logger *logging.ContextLogger, k *koanf.Koanf) (*TelemetryProvider, error)
NewTelemetryProvider creates a new telemetry provider. This function initializes both metrics and tracing components based on the provided configuration. If telemetry is disabled in the configuration, it returns nil without an error. The provider manages the lifecycle of all telemetry components and provides a unified interface for telemetry operations.
Parameters:
- ctx: The context for the operation, which can be used to cancel initialization.
- logger: The logger to use for logging telemetry events and errors.
- k: The koanf instance to load configuration from. This should contain telemetry configuration under the "telemetry" key.
Returns:
- *TelemetryProvider: The initialized telemetry provider, or nil if telemetry is disabled.
- error: An error if the telemetry provider creation fails, such as if metrics initialization fails.
func (*TelemetryProvider) CreatePrometheusHandler ¶
func (tp *TelemetryProvider) CreatePrometheusHandler() http.Handler
CreatePrometheusHandler creates a handler for the Prometheus metrics endpoint. This method returns an HTTP handler that exposes metrics in the Prometheus format. The handler can be registered with an HTTP server to provide a metrics endpoint that can be scraped by Prometheus.
This is a convenience method that delegates to the global CreatePrometheusHandler function. It's provided as a method on TelemetryProvider to maintain a consistent interface for telemetry operations.
Returns:
- http.Handler: The Prometheus metrics handler that can be registered with an HTTP server. This handler will expose all metrics that have been registered with the OpenTelemetry meter provider.
func (*TelemetryProvider) InstrumentHandler ¶
InstrumentHandler wraps an http.Handler with OpenTelemetry instrumentation. This method adds tracing and metrics collection to an HTTP handler, allowing requests to be traced and metrics to be collected automatically. The instrumented handler will create a span for each request, record request duration, and track response status codes.
This is a convenience method that delegates to the global InstrumentHandler function. It's provided as a method on TelemetryProvider to maintain a consistent interface for telemetry operations.
Parameters:
- handler: The HTTP handler to instrument. This is the handler that will be wrapped with telemetry instrumentation.
- operation: The name of the operation for tracing. This will be used as the span name and will appear in traces and metrics.
Returns:
- http.Handler: The instrumented HTTP handler that can be used in place of the original handler to automatically collect telemetry data for HTTP requests.
func (*TelemetryProvider) Meter ¶
func (tp *TelemetryProvider) Meter() metric.Meter
Meter returns the OpenTelemetry meter for creating and recording metrics. This method provides access to the meter instance that can be used to create various types of metrics (counters, gauges, histograms) and record measurements.
If the metrics provider is nil or its meter is nil (which can happen when metrics are disabled), this method returns a default meter from the global OpenTelemetry provider.
Returns:
- metric.Meter: The OpenTelemetry meter that can be used to create and record metrics. This will never be nil, even if metrics are disabled.
func (*TelemetryProvider) NewHTTPMiddleware ¶
func (tp *TelemetryProvider) NewHTTPMiddleware() func(http.Handler) http.Handler
NewHTTPMiddleware creates a new middleware for HTTP request tracing and metrics. This method returns a middleware function that can be used to add telemetry instrumentation to all HTTP handlers in an application. The middleware will create a span for each request, record request duration, track response status codes, and collect other HTTP-related metrics.
This middleware is particularly useful when using a router or framework that supports middleware, as it allows you to add telemetry to all routes with a single middleware registration.
This is a convenience method that delegates to the global NewHTTPMiddleware function. It's provided as a method on TelemetryProvider to maintain a consistent interface for telemetry operations.
Returns:
- func(http.Handler) http.Handler: A middleware function that takes an HTTP handler and returns a new handler with telemetry instrumentation. This function can be passed to router or framework middleware registration functions.
func (*TelemetryProvider) Shutdown ¶
func (tp *TelemetryProvider) Shutdown(ctx context.Context) error
Shutdown shuts down the telemetry provider. This method gracefully shuts down all telemetry components, ensuring that any buffered telemetry data is flushed to its destination. It should be called when the application is shutting down to prevent data loss.
If the telemetry provider is nil (which happens when telemetry is disabled), this method is a no-op and returns nil.
Parameters:
- ctx: The context for the operation, which can be used to set a timeout for the shutdown process or cancel it.
Returns:
- error: An error if the shutdown fails, such as if the metrics provider fails to shut down properly.
func (*TelemetryProvider) Tracer ¶
func (tp *TelemetryProvider) Tracer() trace.Tracer
Tracer returns the OpenTelemetry tracer for creating spans. This method provides access to the tracer instance that can be used to create spans for tracing operations across the application. The tracer is used to create spans that track the execution of operations and record events, attributes, and errors.
If the tracing provider is nil or its tracer is nil (which can happen when tracing is disabled), this method returns a default tracer from the global OpenTelemetry provider.
Returns:
- trace.Tracer: The OpenTelemetry tracer that can be used to create spans. This will never be nil, even if tracing is disabled.
type Tracer ¶ added in v1.5.0
type Tracer interface {
// Start creates a new span with the given name.
// It returns a new context containing the span and the span itself.
// The returned context should be passed to downstream operations to maintain
// the trace context across function calls.
//
// Parameters:
// - ctx: The parent context.
// - name: The name of the operation being traced.
//
// Returns:
// - context.Context: A new context containing the span.
// - Span: The newly created span.
Start(ctx context.Context, name string) (context.Context, Span)
}
Tracer is an interface for creating spans that can be used across packages. It provides a method for starting new spans to trace operations. This interface abstracts away the underlying tracing implementation, allowing for easier testing and flexibility in choosing tracing backends.
func GetTracer ¶ added in v1.5.0
GetTracer returns a tracer that can be used for tracing operations. This function provides a convenient way to get a tracer, either using a provided OpenTelemetry tracer or creating a default one if none is provided.
Parameters:
- tracer: An optional OpenTelemetry trace.Tracer. If nil, a default tracer will be created.
Returns:
- Tracer: An implementation of the Tracer interface that can be used for tracing operations. If tracer is nil, a new tracer with the name "github.com/abitofhelp/servicelib/telemetry" will be created.
func NewNoopTracer ¶ added in v1.5.0
func NewNoopTracer() Tracer
NewNoopTracer creates a new no-op tracer. The no-op tracer implements the Tracer interface but does not perform any actual tracing. This is useful for testing, when tracing is disabled, or when you want to avoid the overhead of tracing in certain environments.
Returns:
- Tracer: A no-op implementation of the Tracer interface.
func NewOtelTracer ¶ added in v1.5.0
NewOtelTracer creates a new OpenTelemetry tracer. This function wraps an OpenTelemetry trace.Tracer in our Tracer interface, allowing it to be used with the rest of our telemetry system.
Parameters:
- tracer: The OpenTelemetry trace.Tracer to wrap.
Returns:
- Tracer: An implementation of the Tracer interface that uses OpenTelemetry.
type TracingConfig ¶
type TracingConfig struct {
// Enabled indicates whether tracing is enabled
Enabled bool `mapstructure:"enabled"`
// SamplingRatio is the ratio of traces to sample
SamplingRatio float64 `mapstructure:"sampling_ratio"`
// PropagationKeys are the keys to propagate in trace context
PropagationKeys []string `mapstructure:"propagation_keys"`
}
TracingConfig holds configuration for tracing
func DefaultTracingConfig ¶ added in v1.5.0
func DefaultTracingConfig() TracingConfig
DefaultTracingConfig returns a default configuration for distributed tracing. This function provides default values for the tracing configuration, which controls how traces are sampled and propagated. The defaults include:
- Enabled: true (tracing is enabled)
- SamplingRatio: 1.0 (100% of traces are sampled)
- PropagationKeys: ["traceparent", "tracestate", "baggage"] (standard W3C trace context keys)
These defaults are suitable for development environments where you want to see all traces. For production environments with high traffic, you may want to reduce the sampling ratio to avoid generating too much telemetry data.
Returns:
- TracingConfig: A default configuration for distributed tracing
type TracingProvider ¶
type TracingProvider struct {
// contains filtered or unexported fields
}
TracingProvider holds the tracing provider and tracer. It encapsulates the OpenTelemetry tracer and provides a way to create and manage trace spans. This struct is used internally by TelemetryProvider to handle the tracing aspect of telemetry.