Instruments the application with OpenTelemetry and exports OTLP for metrics and traces. It uses log/slog for logging, and writes logs to stdout. The application does not include any GCP dependencies, and instead only uses open standards for instrumentation. The OpenTelemetry collector is used to rou
(ctx context.Context, projectID string)
| 36 | // open standards for instrumentation. The OpenTelemetry collector is used to |
| 37 | // route telemetry to GCP. |
| 38 | // Afterwards, metrics, tracing, logging, and context propagation will be setup. |
| 39 | func SetupOpenTelemetry(ctx context.Context, projectID string) (shutdown func(context.Context) error, err error) { |
| 40 | setupLogging(projectID) |
| 41 | |
| 42 | var shutdownFuncs []func(context.Context) error |
| 43 | |
| 44 | // shutdown combines shutdown functions from multiple OpenTelemetry |
| 45 | // components into a single function. |
| 46 | shutdown = func(ctx context.Context) error { |
| 47 | var err error |
| 48 | for _, fn := range shutdownFuncs { |
| 49 | err = errors.Join(err, fn(ctx)) |
| 50 | } |
| 51 | shutdownFuncs = nil |
| 52 | |
| 53 | return err |
| 54 | } |
| 55 | |
| 56 | // Set up the OTLP trace exporter. |
| 57 | texporter, err := autoexport.NewSpanExporter(ctx) |
| 58 | if err != nil { |
| 59 | return nil, err |
| 60 | } |
| 61 | |
| 62 | // Identify your application using resource detection. |
| 63 | // Enforce a strict 5s timeout on resource detection to prevent Metadata Server |
| 64 | // hangs from blocking container startup and failing the Cloud Run probe. |
| 65 | detectCtx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| 66 | defer cancel() |
| 67 | res, err := resource.New(detectCtx, |
| 68 | // Use the GCP resource detector to detect information about the GKE Cluster. |
| 69 | resource.WithDetectors(gcp.NewDetector()), |
| 70 | resource.WithTelemetrySDK(), |
| 71 | ) |
| 72 | if err != nil { |
| 73 | log.Fatalf("resource.New: %v", err) |
| 74 | } |
| 75 | tp := trace.NewTracerProvider( |
| 76 | trace.WithBatcher(texporter), |
| 77 | trace.WithResource(res), |
| 78 | ) |
| 79 | shutdownFuncs = append(shutdownFuncs, tp.Shutdown) |
| 80 | otel.SetTracerProvider(tp) |
| 81 | |
| 82 | // Configure Context Propagation to use the default W3C traceparent format |
| 83 | // Set the global Propagators which is used by otelhttp to propagate |
| 84 | // context using the w3c traceparent and baggage formats. |
| 85 | otel.SetTextMapPropagator(autoprop.NewTextMapPropagator()) |
| 86 | |
| 87 | // Configure Metric Export to send metrics as OTLP |
| 88 | mreader, err := autoexport.NewMetricReader(ctx) |
| 89 | if err != nil { |
| 90 | err = errors.Join(err, shutdown(ctx)) |
| 91 | |
| 92 | return nil, err |
| 93 | } |
| 94 | mp := metric.NewMeterProvider( |
| 95 | metric.WithReader(mreader), |
nothing calls this directly
no test coverage detected