| 1 | // Copyright 2026 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package otel exports spans and metrics to an OpenTelemetry |
| 6 | // collector using the OTLP HTTP/JSON protocol. |
| 7 | // |
| 8 | // Use [NewExporter] to create an exporter, then chain its |
| 9 | // [Exporter.ProcessEvent] method with other exporters: |
| 10 | // |
| 11 | // otelExporter := otel.NewExporter(ctx, |
| 12 | // otel.WithEndpoint("http://localhost:4318"), |
| 13 | // otel.WithServiceName("myservice"), |
| 14 | // ) |
| 15 | // event.SetExporter(otelExporter.ProcessEvent) |
| 16 | // |
| 17 | // The exporter batches telemetry and flushes periodically in a |
| 18 | // background goroutine. Call [Exporter.Flush] to force an |
| 19 | // immediate export. |
| 20 | package otel |
| 21 | |
| 22 | import ( |
| 23 | "bytes" |
| 24 | "context" |
| 25 | "encoding/json" |
| 26 | "fmt" |
| 27 | "log" |
| 28 | "net/http" |
| 29 | "os" |
| 30 | "runtime" |
| 31 | "strconv" |
| 32 | "sync" |
| 33 | "time" |
| 34 | |
| 35 | "golang.org/x/tools/internal/event" |
| 36 | "golang.org/x/tools/internal/event/core" |
| 37 | "golang.org/x/tools/internal/event/export" |
| 38 | "golang.org/x/tools/internal/event/export/metric" |
| 39 | "golang.org/x/tools/internal/event/label" |
| 40 | ) |
| 41 | |
| 42 | // Exporter exports spans and metrics to an OTLP HTTP endpoint. |
| 43 | type Exporter struct { |
| 44 | mu sync.Mutex |
| 45 | endpoint string |
| 46 | serviceName string |
| 47 | serviceVersion string |
| 48 | resource otlpResource |
| 49 | client *http.Client |
| 50 | flushPeriod time.Duration |
| 51 | spans []*export.Span |
| 52 | metrics map[string]metric.Data |
| 53 | } |
| 54 | |
| 55 | // NewExporter creates an exporter that sends spans to an OTLP endpoint. |
| 56 | // Spans are collected and exported periodically in a background goroutine. |
| 57 | // When the context is done, remaining spans are flushed. |
| 58 | func NewExporter(ctx context.Context, opts ...Option) *Exporter { |
| 59 | e := &Exporter{ |
| 60 | endpoint: DefaultEndpoint, |
| 61 | serviceName: DefaultServiceName, |
| 62 | client: &http.Client{Timeout: DefaultTimeout}, |
| 63 | flushPeriod: DefaultFlushPeriod, |
| 64 | } |
| 65 | |
| 66 | for _, opt := range opts { |
| 67 | opt(e) |
| 68 | } |
| 69 | |
| 70 | e.resource = e.buildResource() |
| 71 | |
| 72 | go func() { |
| 73 | ticker := time.NewTicker(e.flushPeriod) |
| 74 | defer ticker.Stop() |
| 75 | for { |
| 76 | select { |
| 77 | case <-ctx.Done(): |
| 78 | e.Flush() // final flush before exiting |
| 79 | return |
| 80 | case <-ticker.C: |
| 81 | e.Flush() |
| 82 | } |
| 83 | } |
| 84 | }() |
| 85 | |
| 86 | return e |
| 87 | } |
| 88 | |
| 89 | // ProcessEvent handles events and collects completed spans and metrics. |
| 90 | func (e *Exporter) ProcessEvent(ctx context.Context, ev core.Event, lm label.Map) context.Context { |
| 91 | e.mu.Lock() |
| 92 | defer e.mu.Unlock() |
| 93 | |
| 94 | if event.IsEnd(ev) { |
| 95 | if span := export.GetSpan(ctx); span != nil { |
| 96 | e.spans = append(e.spans, span) |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | if event.IsMetric(ev) { |
| 101 | if e.metrics == nil { |
| 102 | e.metrics = make(map[string]metric.Data) |
| 103 | } |
| 104 | if entries := metric.Entries.Get(lm); entries != nil { |
| 105 | for _, data := range entries.([]metric.Data) { |
| 106 | e.metrics[data.Handle()] = data |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | return ctx |
| 112 | } |
| 113 | |
| 114 | // Flush exports all collected spans and metrics to the OTLP endpoint. |
| 115 | func (e *Exporter) Flush() { |
| 116 | e.mu.Lock() |
| 117 | spans := e.spans |
| 118 | e.spans = nil |
| 119 | metrics := e.metrics |
| 120 | e.metrics = nil |
| 121 | e.mu.Unlock() |
| 122 | |
| 123 | // Export spans |
| 124 | if len(spans) > 0 { |
| 125 | otlpSpans := make([]otlpSpan, 0, len(spans)) |
| 126 | for _, span := range spans { |
| 127 | otlpSpans = append(otlpSpans, convertSpan(span)) |
| 128 | } |
| 129 | if err := e.exportTraces(otlpSpans); err != nil { |
| 130 | log.Printf("post spans: %v", err) |
| 131 | return |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | // Export metrics |
| 136 | if len(metrics) > 0 { |
| 137 | otlpMetrics := make([]otlpMetric, 0, len(metrics)) |
| 138 | for _, data := range metrics { |
| 139 | otlpMetrics = append(otlpMetrics, convertMetric(data)) |
| 140 | } |
| 141 | if err := e.exportMetrics(otlpMetrics); err != nil { |
| 142 | log.Printf("post metrics: %v", err) |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | // post sends a JSON payload to the OTLP endpoint. |
| 148 | func (e *Exporter) post(path string, payload any) error { |
| 149 | data, err := json.Marshal(payload) |
| 150 | if err != nil { |
| 151 | return err |
| 152 | } |
| 153 | |
| 154 | // The background context is appropriate here since post is called only |
| 155 | // from Flush, which is called only by the Exporter's background goroutine. |
| 156 | // Notably it may be called after cancellation of the client's context. |
| 157 | req, err := http.NewRequestWithContext(context.Background(), "POST", e.endpoint+path, bytes.NewReader(data)) |
| 158 | if err != nil { |
| 159 | return err |
| 160 | } |
| 161 | req.Header.Set("Content-Type", "application/json") |
| 162 | |
| 163 | resp, err := e.client.Do(req) |
| 164 | if err != nil { |
| 165 | return err |
| 166 | } |
| 167 | defer resp.Body.Close() |
| 168 | |
| 169 | if resp.StatusCode >= 400 { |
| 170 | return fmt.Errorf("OTLP export to %s failed with status %d", path, resp.StatusCode) |
| 171 | } |
| 172 | return nil |
| 173 | } |
| 174 | |
| 175 | func (e *Exporter) buildResource() otlpResource { |
| 176 | attrs := []otlpAttribute{ |
| 177 | {Key: "service.name", Value: otlpAttributeValue{StringValue: &e.serviceName}}, |
| 178 | {Key: "process.runtime.version", Value: otlpAttributeValue{StringValue: varOf(runtime.Version())}}, |
| 179 | {Key: "process.pid", Value: otlpAttributeValue{StringValue: varOf(strconv.Itoa(os.Getpid()))}}, |
| 180 | {Key: "host.arch", Value: otlpAttributeValue{StringValue: varOf(runtime.GOARCH)}}, |
| 181 | {Key: "os.type", Value: otlpAttributeValue{StringValue: varOf(runtime.GOOS)}}, |
| 182 | } |
| 183 | |
| 184 | if hostname, err := os.Hostname(); err == nil { |
| 185 | attrs = append(attrs, otlpAttribute{ |
| 186 | Key: "host.name", |
| 187 | Value: otlpAttributeValue{StringValue: &hostname}, |
| 188 | }) |
| 189 | } |
| 190 | |
| 191 | if e.serviceVersion != "" { |
| 192 | attrs = append(attrs, otlpAttribute{ |
| 193 | Key: "service.version", |
| 194 | Value: otlpAttributeValue{StringValue: &e.serviceVersion}, |
| 195 | }) |
| 196 | } |
| 197 | |
| 198 | return otlpResource{Attributes: attrs} |
| 199 | } |