otelemetry

package module
v0.0.0-...-71ed017 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2024 License: MIT Imports: 25 Imported by: 1

README

OTelemetry

OTelemetry is a wrapper around (over gRPC) the OpenTelemetry library that provides a simple interface to instrument your code with telemetry.

ToDo
  • Jetstream utils
  • RabbitMQ utils
  • TLS support
  • Add tests
  • Modify examples
  • Add documentation
Install
go get -u github.com/rorua/otelemetry
Usage

Here is a simple example of how to use OTelemetry in your Go application:

import "github.com/rorua/otelemetry"

func main() {
	// Configuration for OTelemetry
	cfg := otelemetry.Config{
		Service: otelemetry.ServiceConfig{
			Name: "example-service",
		},
		Collector: otelemetry.CollectorConfig{
			Host: "localhost",
			Port: "4317",
		},
                TracerOptions: otelemetry.TracerOptions{
                    ClientOption: []otlptracegrpc.Option{
                        otlptracegrpc.WithCompressor("gzip"),
                    },
                },
		WithTraces:  true,
		WithMetrics: true,
		WithLogs:    true,
	}

	// Initialize OTelemetry
	tel, err := otelemetry.New(cfg)
	if err != nil {
		log.Fatalf("failed to initialize telemetry: %v", err)
	}
	defer tel.Shutdown(context.Background())
	
	// your code 
}	

Example usage of tracer and span:

// Example usage of tracer and span
ctx, span := tel.Trace().StartSpan(context.Background(), "example-span")
defer span.End()

span.AddEvent("example event", otelemetry.Attribute("key", "value"))

Get span from context:

span := tel.Trace().SpanFromContext(ctx)

span.AddEvent("example of continuing span get from context", otelemetry.Attribute("key", "value"))

Example usage meter:

// Example usage meter
counter, err := tel.Metric().Float64Counter("example_counter")
if err != nil {
    panic(err)
}

counter.Add(ctx, 1)

Example usage of logger:

// Example usage of logger
tel.Log().Info(ctx, "log message", otelemetry.LogAttribute("key", "value"))

Example of getting a context with tracing data from Nats message:


import (
    otelemetryutils "github.com/rorua/otelemetry/utils"
)

func (h *handler) SignedIn(msg jetstream.Msg) {
    
    ctx := otelemetryutils.GetNatsTraceContext(context.Background(), *msg)
    
    ctx, span := tel.Trace().StartSpan(ctx, "NatsHandler: user.SignedIn")
    defer span.End()
    
    // code ...
}

Contributing

Pull requests are welcome.

Documentation

Index

Constants

View Source
const (
	Debug = "DEBUG"
	Info  = "INFO"
	Warn  = "WARN"
	Error = "ERROR"
	Fatal = "FATAL"
)

Variables

This section is empty.

Functions

func AddBaggageItem

func AddBaggageItem(ctx context.Context, key, value string) context.Context

AddBaggageItem adds a key-value pair to the baggage.

func AddBaggageItems

func AddBaggageItems(ctx context.Context, items map[string]string) context.Context

AddBaggageItems adds multiple key-value pairs to the baggage.

func Attribute

func Attribute(k string, v any) attribute.KeyValue

func Extract

func Extract(ctx context.Context, kv map[string]string) context.Context

func ExtractHTTPHeaders

func ExtractHTTPHeaders(ctx context.Context, headers http.Header) context.Context

func GetBaggage

func GetBaggage(ctx context.Context) baggage.Baggage

GetBaggage retrieves the baggage from the context.

func GetBaggageItem

func GetBaggageItem(ctx context.Context, key string) string

GetBaggageItem retrieves the value of a baggage item by key.

func Inject

func Inject(ctx context.Context, kv map[string]string)

func InjectHTTPHeaders

func InjectHTTPHeaders(ctx context.Context, headers http.Header)

func LogAttribute

func LogAttribute(k string, v any) log.KeyValue

func RemoveBaggageItem

func RemoveBaggageItem(ctx context.Context, key string) context.Context

RemoveBaggageItem removes a key-value pair from the baggage.

Types

type Collector

type Collector struct {
	Host string
	Port string
}

Collector holds the collector-related configuration.

type Config

type Config struct {
	// Service configuration.
	Service
	// Collector configuration.
	Collector
	// Flag to enable tracing.
	WithTraces bool
	// Flag to enable metrics.
	WithMetrics bool
	// Flag to enable logging.
	WithLogs bool
	// Options for resource configuration.
	ResourceOptions []sdkresource.Option
	// Options for tracer configuration.
	TracerOptions TracerOptions
	// Options for logger configuration.
	LoggerOptions LoggerOptions
	// Options for metric configuration.
	MetricOptions MetricOptions
}

Config holds the configuration for the telemetry setup.

type Log

type Log interface {
	// Log returns the original logger.
	Log() log.Logger // original logger

	Debug(ctx context.Context, msg string, kv ...log.KeyValue)
	Info(ctx context.Context, msg string, kv ...log.KeyValue)
	Warning(ctx context.Context, msg string, kv ...log.KeyValue)
	Error(ctx context.Context, msg string, kv ...log.KeyValue)
	Fatal(ctx context.Context, msg string, kv ...log.KeyValue)
}

Log interface provides methods for logging operations.

type LoggerOptions

type LoggerOptions struct {
	// Options for the OTLP log exporter.
	ExporterOption []otlploggrpc.Option
	// Options for the logger provider.
	ProviderOption []sdklog.LoggerProviderOption
	// Options for the logger.
	LoggerOption []log.LoggerOption
}

LoggerOptions holds the options for logger configuration.

type Metric

type Metric interface {
	// Metric returns the underlying OpenTelemetry meter.
	Metric() metric.Meter

	Int64Counter(name string, options ...metric.Int64CounterOption) (metric.Int64Counter, error)
	Int64UpDownCounter(name string, options ...metric.Int64UpDownCounterOption) (metric.Int64UpDownCounter, error)
	Int64Histogram(name string, options ...metric.Int64HistogramOption) (metric.Int64Histogram, error)
	Int64Gauge(name string, options ...metric.Int64GaugeOption) (metric.Int64Gauge, error)
	Int64ObservableCounter(name string, options ...metric.Int64ObservableCounterOption) (metric.Int64ObservableCounter, error)
	Int64ObservableUpDownCounter(name string, options ...metric.Int64ObservableUpDownCounterOption) (metric.Int64ObservableUpDownCounter, error)
	Int64ObservableGauge(name string, options ...metric.Int64ObservableGaugeOption) (metric.Int64ObservableGauge, error)
	Float64Counter(name string, options ...metric.Float64CounterOption) (metric.Float64Counter, error)
	Float64UpDownCounter(name string, options ...metric.Float64UpDownCounterOption) (metric.Float64UpDownCounter, error)
	Float64Histogram(name string, options ...metric.Float64HistogramOption) (metric.Float64Histogram, error)
	Float64Gauge(name string, options ...metric.Float64GaugeOption) (metric.Float64Gauge, error)
	Float64ObservableCounter(name string, options ...metric.Float64ObservableCounterOption) (metric.Float64ObservableCounter, error)
	Float64ObservableUpDownCounter(name string, options ...metric.Float64ObservableUpDownCounterOption) (metric.Float64ObservableUpDownCounter, error)
	Float64ObservableGauge(name string, options ...metric.Float64ObservableGaugeOption) (metric.Float64ObservableGauge, error)
	RegisterCallback(f metric.Callback, instruments ...metric.Observable) (metric.Registration, error)
}

Metric interface provides methods for creating and managing various types of metrics.

type MetricOptions

type MetricOptions struct {
	// Options for the OTLP metric exporter.
	ExporterOptions []otlpmetricgrpc.Option
	// Options for the metric provider.
	ProviderOptions []sdkmetric.Option
	// Options for the meter.
	MeterOptions []metric.MeterOption
}

MetricOptions holds the options for metric configuration.

type Service

type Service struct {
	// Name of the service.
	Name string
	// Namespace of the service.
	Namespace string
	// Version of the service.
	Version string
}

Service holds the service-related configuration.

type Span

type Span interface {
	// Span returns the underlying OpenTelemetry span.
	Span() trace.Span // think about naming

	// AddEvent adds an event to the span with the given name and attributes.
	AddEvent(name string, kv ...attribute.KeyValue)

	// AddErrorEvent adds an error event to the span with the given name, error, and attributes.
	AddErrorEvent(name string, err error, kv ...attribute.KeyValue)

	// SetAttribute sets an attribute on the span.
	SetAttribute(kv ...attribute.KeyValue)

	// End ends the span with the given options.
	End(opts ...trace.SpanEndOption) // aka Finish()

	// RecordError records an error on the span with the given attributes.
	RecordError(err error, kv ...attribute.KeyValue)

	// TraceID returns the trace ID of the span.
	TraceID() string

	// SpanID returns the span ID of the span.
	SpanID() string
}

Span represents an OpenTelemetry span and provides methods to interact with it.

type Telemetry

type Telemetry interface {
	// Trace returns the tracer instance.
	Trace() Trace

	// Log returns the logger instance.
	Log() Log

	// Metric returns the meter instance.
	Metric() Metric

	// Shutdown gracefully shuts down the telemetry providers.
	Shutdown(ctx context.Context) error
}

Telemetry implements the OpenTelemetry API. It provides methods to start spans, log messages, and create metrics.

Example: t.Trace().StartSpan(ctx, "name") t.Log().Info(ctx, "message") t.Metric().NewInt64Counter("name")

func New

func New(cfg Config) (Telemetry, error)

New creates a new Telemetry instance based on the provided configuration.

type Trace

type Trace interface {
	// Trace returns the original tracer.
	Trace() trace.Tracer // original trace

	// StartSpan starts a new span with the given name and options.
	StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, Span)
	// SpanFromContext retrieves the span from the given context.
	SpanFromContext(ctx context.Context) Span

	// ContextWithSpan returns a new context with the given span.
	ContextWithSpan(ctx context.Context, span trace.Span) context.Context
	// ContextWithRemoteSpanContext returns a new context with the remote span context.
	ContextWithRemoteSpanContext(ctx context.Context, span trace.Span) context.Context
}

Trace interface provides methods for tracing operations.

type TracerOptions

type TracerOptions struct {
	// Options for the OTLP trace client.
	ClientOption []otlptracegrpc.Option
	// Options for the tracer provider.
	ProviderOption []sdktrace.TracerProviderOption
	// Options for the batch span processor.
	BatchSpanProcessorOption []sdktrace.BatchSpanProcessorOption
	// Options for the tracer.
	TracerOption []trace.TracerOption
}

TracerOptions holds the options for tracer configuration.

Directories

Path Synopsis
examples module

Jump to

Keyboard shortcuts

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