setup.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package opentelemetry
  2. import (
  3. "context"
  4. "go.opentelemetry.io/otel/attribute"
  5. "go.opentelemetry.io/otel/sdk/resource"
  6. semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
  7. extConfig "go-admin/config"
  8. )
  9. func Setup() {
  10. // Create resource.
  11. res, err := newResource()
  12. if err != nil {
  13. panic(err)
  14. }
  15. initMeter(res)
  16. initTracer(res)
  17. // Handle shutdown properly so nothing leaks.
  18. // defer func() {
  19. // if err := meterProvider.Shutdown(context.Background()); err != nil {
  20. // log.Println(err)
  21. // }
  22. // }()
  23. }
  24. func newResource() (res *resource.Resource, err error) {
  25. res = resource.Default()
  26. extres, _ := resource.New(
  27. context.TODO(),
  28. resource.WithHost(),
  29. resource.WithOS(),
  30. resource.WithProcess(),
  31. resource.WithContainer(),
  32. )
  33. res, err = resource.Merge(res, extres)
  34. com := extConfig.ExtConfig.Otel.Common
  35. serviceName := com.ServiceName
  36. serviceVersion := com.ServiceVersion
  37. if serviceName != "" && serviceVersion != "" {
  38. res, err = resource.Merge(res, resource.NewWithAttributes(
  39. semconv.SchemaURL,
  40. semconv.ServiceName(serviceName),
  41. semconv.ServiceVersion(serviceVersion),
  42. semconv.ProcessCommandLine("-DAPP_NAME=OBSERVE"), // 从这里固定commandline,用于applias解析;golang从不能从命令行直接写
  43. attribute.String("app.name", "OBSERVE"),
  44. ))
  45. }
  46. return
  47. }