MCPcopy
hub / github.com/elastic/go-elasticsearch / main

Function main

_examples/interceptor/cmd/custom_observability/main.go:55–112  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

53)
54
55func main() {
56 // Initialize OpenTelemetry providers
57 shutdown := initOTel()
58 defer shutdown()
59
60 // Start a fake Elasticsearch server
61 srv := fake.NewServer(
62 fake.WithStatusCode(http.StatusOK),
63 fake.WithResponseBody([]byte(`{"cluster_name":"example","version":{"number":"9.2.0"}}`)),
64 fake.WithHeaders(func(h http.Header) {
65 h.Set("X-Elastic-Product", "Elasticsearch")
66 h.Set("Content-Type", "application/json")
67 }),
68 )
69 defer srv.Close()
70
71 // Create metrics instruments
72 meter := otel.Meter("elasticsearch-client")
73 requestCounter, _ := meter.Int64Counter("elasticsearch.client.requests",
74 metric.WithDescription("Number of requests to Elasticsearch"),
75 metric.WithUnit("{request}"),
76 )
77 requestDuration, _ := meter.Float64Histogram("elasticsearch.client.duration",
78 metric.WithDescription("Duration of Elasticsearch requests"),
79 metric.WithUnit("ms"),
80 )
81
82 // Create tracer
83 tracer := otel.Tracer("elasticsearch-client")
84
85 // Create an Elasticsearch client with observability interceptors
86 es, err := elasticsearch.New(
87 elasticsearch.WithAddresses(srv.URL()),
88 elasticsearch.WithTransportOptions(elastictransport.WithInterceptors(
89 LoggingInterceptor(),
90 MetricsInterceptor(requestCounter, requestDuration),
91 TracingInterceptor(tracer),
92 )),
93 )
94 if err != nil {
95 panic(err)
96 }
97
98 // Send some requests to demonstrate the observability
99 fmt.Println(">>> Sending requests to demonstrate observability interceptors")
100 fmt.Println()
101
102 for i := 1; i <= 3; i++ {
103 fmt.Printf("--- Request %d ---\n", i)
104 _, _ = es.Info()
105 fmt.Println()
106 time.Sleep(100 * time.Millisecond) // Small delay between requests
107 }
108
109 // Give time for metrics to flush
110 fmt.Println(">>> Waiting for metrics to flush...")
111 time.Sleep(2 * time.Second)
112}

Callers

nothing calls this directly

Calls 13

URLMethod · 0.95
NewServerFunction · 0.92
WithStatusCodeFunction · 0.92
WithResponseBodyFunction · 0.92
WithHeadersFunction · 0.92
initOTelFunction · 0.85
LoggingInterceptorFunction · 0.85
MetricsInterceptorFunction · 0.85
TracingInterceptorFunction · 0.85
PrintfMethod · 0.80
CloseMethod · 0.65
SetMethod · 0.45

Tested by

no test coverage detected