metrics.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package opentelemetry
  2. import (
  3. "context"
  4. "time"
  5. extConfig "go-admin/config"
  6. "go.opentelemetry.io/otel"
  7. "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
  8. "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
  9. "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"
  10. "go.opentelemetry.io/otel/sdk/metric"
  11. "go.opentelemetry.io/otel/sdk/resource"
  12. )
  13. func initMeter(res *resource.Resource) (provider *metric.MeterProvider, err error) {
  14. otelConfig := extConfig.ExtConfig.Otel
  15. endpoint := otelConfig.Common.Endpoint
  16. grpcEndpoint := otelConfig.Common.GrpcEndpoint
  17. interval := otelConfig.Metrics.Interval
  18. exporter := new(metric.Exporter)
  19. if endpoint == "" && grpcEndpoint == "" {
  20. *exporter, err = stdoutmetric.New(stdoutmetric.WithPrettyPrint())
  21. } else if grpcEndpoint != "" {
  22. options := []otlpmetricgrpc.Option{
  23. otlpmetricgrpc.WithEndpoint(grpcEndpoint),
  24. otlpmetricgrpc.WithInsecure(),
  25. }
  26. *exporter, err = otlpmetricgrpc.New(context.TODO(), options...)
  27. } else {
  28. *exporter, err = otlpmetrichttp.New(context.TODO(), otlpmetrichttp.WithEndpoint(endpoint), otlpmetrichttp.WithInsecure())
  29. }
  30. if interval == 0 {
  31. interval = 60
  32. }
  33. if err != nil {
  34. return nil, err
  35. }
  36. provider = metric.NewMeterProvider(
  37. metric.WithResource(res),
  38. metric.WithReader(metric.NewPeriodicReader(*exporter, metric.WithInterval(time.Duration(interval)*time.Second))),
  39. )
  40. otel.SetMeterProvider(provider)
  41. return provider, nil
  42. }