MCPcopy
hub / github.com/redis/go-redis / main

Function main

example/otel-metrics/main.go:22–123  ·  example/otel-metrics/main.go::main

ExampleClient_otel_metrics demonstrates how to enable OpenTelemetry metrics for Redis operations and export them to an OTLP collector.

()

Source from the content-addressed store, hash-verified

20// ExampleClient_otel_metrics demonstrates how to enable OpenTelemetry metrics
21// for Redis operations and export them to an OTLP collector.
22func main() {
23 ctx := context.Background()
24
25 // HIDE_END
26
27 // STEP_START otel_exporter_setup
28 // Create OTLP exporter that sends metrics to the collector
29 // Default endpoint is localhost:4317 (gRPC)
30 exporter, err := otlpmetricgrpc.New(ctx,
31 otlpmetricgrpc.WithInsecure(), // Use insecure for local development
32 // For production, configure TLS and authentication:
33 // otlpmetricgrpc.WithEndpoint("your-collector:4317"),
34 // otlpmetricgrpc.WithTLSCredentials(...),
35 )
36 if err != nil {
37 log.Fatalf("Failed to create OTLP exporter: %v", err)
38 }
39 // STEP_END
40
41 // STEP_START otel_meter_provider
42 // Create meter provider with periodic reader
43 // Metrics are exported every 10 seconds
44 meterProvider := metric.NewMeterProvider(
45 metric.WithReader(
46 metric.NewPeriodicReader(exporter,
47 metric.WithInterval(10*time.Second),
48 ),
49 ),
50 )
51 defer func() {
52 if err := meterProvider.Shutdown(ctx); err != nil {
53 log.Printf("Error shutting down meter provider: %v", err)
54 }
55 }()
56
57 // Set the global meter provider
58 otel.SetMeterProvider(meterProvider)
59 // STEP_END
60
61 // STEP_START redis_client_setup
62 // Initialize OTel instrumentation BEFORE creating Redis clients
63 otelInstance := redisotel.GetObservabilityInstance()
64 config := redisotel.NewConfig().WithEnabled(true)
65 if err := otelInstance.Init(config); err != nil {
66 log.Fatalf("Failed to initialize OTel: %v", err)
67 }
68 defer otelInstance.Shutdown()
69
70 // Create Redis client - automatically instrumented
71 rdb := redis.NewClient(&redis.Options{
72 Addr: "localhost:6379",
73 })
74 defer rdb.Close()
75 // STEP_END
76
77 // STEP_START redis_operations
78 // Execute Redis operations - metrics are automatically collected
79 log.Println("Executing Redis operations...")

Callers

nothing calls this directly

Calls 10

WithReaderMethod · 0.80
WithEnabledMethod · 0.80
InitMethod · 0.80
WaitMethod · 0.80
ShutdownMethod · 0.65
PrintfMethod · 0.65
CloseMethod · 0.65
AddMethod · 0.65
ErrMethod · 0.65
SetMethod · 0.65

Tested by

no test coverage detected