### Go OTel Trace and Metrics Instrumentation Source: https://context7.com/googlecloudplatform/opentelemetry-cloud-run/llms.txt Initializes OTLP gRPC trace and metric exporters to a local Collector sidecar. It registers a periodic metric reader, creates an Int64Counter, and starts an HTTP server. Each request generates spans, logs, and increments the counter. ```go // Trace exporter — sends to OTel Collector sidecar via gRPC (insecure, localhost:4317) traceExporter, err := otlptrace.New(ctx, otlptracegrpc.NewClient(otlptracegrpc.WithInsecure()), ) tp := sdktrace.NewTracerProvider( sdktrace.WithSampler(sdktrace.AlwaysSample()), sdktrace.WithSpanProcessor(sdktrace.NewBatchSpanProcessor(traceExporter)), ) def tp.Shutdown(ctx) otel.SetTracerProvider(tp) otel.SetTextMapPropagator(propagation.TraceContext{}) // Metrics exporter — sends to OTel Collector sidecar via gRPC exporter, err := otlpmetricgrpc.New(ctx, otlpmetricgrpc.WithInsecure()) provider := metric.NewMeterProvider( metric.WithReader(metric.NewPeriodicReader(exporter)), ) def provider.Shutdown(ctx) meter := provider.Meter("example.com/metrics") counter, err = meter.Int64Counter("sidecar-sample-counter") // HTTP handler: creates a span, logs with trace context, generates 10 child spans, increments counter func handler(w http.ResponseWriter, r *http.Request) { prop := otel.GetTextMapPropagator() ctx := prop.Extract(r.Context(), propagation.HeaderCarrier(r.Header)) tracer := otel.GetTracerProvider().Tracer("example.com/trace") ctx, span := tracer.Start(ctx, "foo") defer span.End() // Write trace-correlated log to shared volume (read by Collector filelog receiver) f, _ := os.OpenFile("/logging/sample-app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) defer f.Close() logger := log.New(f, fmt.Sprintf("sample-app [%s][spanId: %s]: ", span.SpanContext().TraceID(), span.SpanContext().SpanID()), log.LstdFlags) logger.Printf("Request: %s %s", r.Method, r.URL.Path) generateSpans(ctx, tracer, logger, 10) // generates 10 nested child spans counter.Add(ctx, 100) // increments metric fmt.Fprintln(w, "Logged request to /logging/sample-app.log") fmt.Fprintln(w, "Generated 10 spans!") fmt.Fprintln(w, "Updated sidecar-sample-counter metric!") } // Expected curl response: // Logged request to /logging/sample-app.log // Generated 10 spans! // Updated sidecar-sample-counter metric! ``` -------------------------------- ### Enable Google Cloud Services Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/csharp/README.md Enables necessary Google Cloud services for Cloud Run and telemetry using gcloud commands. Ensure you have the gcloud CLI installed and authenticated. ```bash gcloud services enable run.googleapis.com --quiet gcloud services enable artifactregistry.googleapis.com --quiet gcloud services enable telemetry.googleapis.com --quiet gcloud services enable monitoring.googleapis.com --quiet ``` -------------------------------- ### Cloud Run Multicontainer Service Definition Source: https://context7.com/googlecloudplatform/opentelemetry-cloud-run/llms.txt Defines a Cloud Run Service with two containers sharing an in-memory volume. The 'app' container depends on 'collector' being healthy before it starts. ```yaml apiVersion: serving.knative.dev/v1 kind: Service metadata: annotations: run.googleapis.com/launch-stage: ALPHA name: "opentelemetry-cloud-run-golang-sample" spec: template: metadata: annotations: run.googleapis.com/execution-environment: gen1 # Ensures collector starts before app run.googleapis.com/container-dependencies: '{"app":["collector"]}' spec: containers: - image: "us-east1-docker.pkg.dev//run-otel-example/sample-app" name: app ports: - containerPort: 8080 volumeMounts: - mountPath: /logging name: shared-logs - image: "us-east1-docker.pkg.dev//run-otel-example/collector" name: collector startupProbe: initialDelaySeconds: 60 httpGet: path: / port: 13133 # OTel Collector health check endpoint volumeMounts: - mountPath: /logging name: shared-logs volumes: - name: shared-logs emptyDir: medium: Memory sizeLimit: 512Mi ``` ```bash # Substitute image placeholders and deploy export GCP_PROJECT= sed -i s@%OTELCOL_IMAGE%@us-east1-docker.pkg.dev/${GCP_PROJECT}/run-otel-example/collector@g run-service.yaml sed -i s@%SAMPLE_APP_IMAGE%@us-east1-docker.pkg.dev/${GCP_PROJECT}/run-otel-example/sample-app@g run-service.yaml gcloud run services replace run-service.yaml gcloud run services set-iam-policy opentelemetry-cloud-run-sample policy.yaml ``` -------------------------------- ### Build and Push Sample App Image Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Build the Golang sample application into a Docker image and push it to the configured Artifact Registry repository. ```bash pushd app docker build -t us-east1-docker.pkg.dev/$GCP_PROJECT/run-otel-example/sample-app . docker push us-east1-docker.pkg.dev/$GCP_PROJECT/run-otel-example/sample-app popd ``` -------------------------------- ### Enable GCP APIs and Configure IAM Source: https://context7.com/googlecloudplatform/opentelemetry-cloud-run/llms.txt Enables necessary Google Cloud APIs and sets IAM roles for the Cloud Run service account. Ensure you replace with your actual project ID. ```bash gcloud config set project gcloud services enable run.googleapis.com --quiet gcloud services enable artifactregistry.googleapis.com --quiet gcloud services enable cloudtrace.googleapis.com --quiet gcloud services enable monitoring.googleapis.com --quiet gcloud services enable cloudbuild.googleapis.com --quiet # The default Compute Engine Service Account needs these roles for the Cloud Run service: # roles/monitoring.metricWriter # roles/cloudtrace.agent # roles/logging.logWriter ``` -------------------------------- ### Set Google Cloud Project Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Configure the gcloud CLI to use the desired Google Cloud project for the sample. ```console gcloud config set project ``` -------------------------------- ### Submit to Cloud Build Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Submit the application to Cloud Build for containerization and deployment. Ensure the Cloud Build API is enabled and a service account with appropriate roles is configured. ```console gcloud services enable cloudbuild.googleapis.com --quiet ``` ```console ../create-service-account.sh gcloud builds submit . --config=cloudbuild.yaml ``` -------------------------------- ### Enable Google Cloud Services Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Enable necessary Google Cloud APIs for Cloud Run, Artifact Registry, Cloud Trace, Monitoring, and Cloud Build. ```console gcloud services enable run.googleapis.com --quiet gcloud services enable artifactregistry.googleapis.com --quiet gcloud services enable cloudtrace.googleapis.com --quiet gcloud services enable monitoring.googleapis.com --quiet gcloud services enable cloudbuild.googleapis.com --quiet ``` -------------------------------- ### Create Cloud Run Service Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Deploy the Cloud Run service using the updated run-service.yaml configuration. ```bash gcloud run services replace run-service.yaml ``` -------------------------------- ### Create Service Account and Artifact Registry Source: https://context7.com/googlecloudplatform/opentelemetry-cloud-run/llms.txt This script creates a dedicated GCP service account for Cloud Build with necessary roles and provisions an Artifact Registry Docker repository. Run this script from the repository root. ```bash # Run from the repository root — creates service account and artifact registry ./create-service-account.sh # What it does: # 1. Creates SA: run-otel-example-sa@.iam.gserviceaccount.com # 2. Assigns roles: # - roles/iam.serviceAccountUser # - roles/storage.objectUser # - roles/logging.logWriter # - roles/artifactregistry.createOnPushWriter # - roles/run.admin # - roles/run.serviceAgent # 3. Creates Artifact Registry repo: run-otel-example (docker, us-east1) ``` -------------------------------- ### Create Artifact Registry Docker Repository Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Create a Docker repository in Artifact Registry to store container images for the sample application and collector. ```bash export GCP_PROJECT= gcloud artifacts repositories create run-otel-example \ --repository-format=docker \ --location=us-east1 ``` -------------------------------- ### Build and Push Collector Image Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Build the OpenTelemetry Collector Docker image, including the local configuration, and push it to Artifact Registry. ```bash pushd collector docker build -t us-east1-docker.pkg.dev/$GCP_PROJECT/run-otel-example/collector . docker push us-east1-docker.pkg.dev/$GCP_PROJECT/run-otel-example/collector popd ``` -------------------------------- ### Full OTel Collector Pipeline for Go Source: https://context7.com/googlecloudplatform/opentelemetry-cloud-run/llms.txt This configuration is for a full pipeline, receiving OTLP over gRPC and HTTP, processing logs with filelog receiver and regex trace correlation, batching signals, limiting memory, detecting GCP resource metadata, and exporting to Google Cloud for traces and logs, and Google Managed Prometheus for metrics. ```yaml receivers: otlp: protocols: grpc: endpoint: 0.0.0.0:4317 http: endpoint: 0.0.0.0:4318 filelog: include: [ /logging/*.log ] # shared in-memory volume from run-service.yaml start_at: beginning operators: - type: regex_parser # Extracts traceId/spanId from log lines for log-trace correlation regex: '^sample-app \[(?P\S*)\]\[spanId: (?P\S*)\]: .*' trace: trace_id: parse_from: attributes.trace_id span_id: parse_from: attributes.span_id processors: batch: send_batch_max_size: 200 send_batch_size: 200 timeout: 5s memory_limiter: check_interval: 1s limit_percentage: 65 spike_limit_percentage: 20 resourcedetection: detectors: [env, gcp] # auto-populates Cloud Run resource labels timeout: 2s override: false exporters: googlecloud: log: default_log_name: ltm-sample-app googlemanagedprometheus: # exports metrics to Google Managed Prometheus extensions: health_check: endpoint: 0.0.0.0:13133 # used as startup probe in run-service.yaml service: extensions: [health_check] pipelines: traces: receivers: [otlp] processors: [resourcedetection] exporters: [googlecloud] logs: receivers: [otlp, filelog] processors: [resourcedetection] exporters: [googlecloud] metrics: receivers: [otlp] processors: [resourcedetection] exporters: [googlemanagedprometheus] ``` -------------------------------- ### Configure Docker Authentication Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Authenticate the local Docker client with Google Cloud's Artifact Registry to enable pushing images. ```console gcloud auth configure-docker \ us-east1-docker.pkg.dev ``` -------------------------------- ### C# Zero-Code OTel Instrumentation with Google Cloud Logging Source: https://context7.com/googlecloudplatform/opentelemetry-cloud-run/llms.txt Configures OpenTelemetry Zero-Code auto-instrumentation for .NET applications and integrates with Google Cloud Console for structured, log-trace correlated output. Demonstrates structured JSON logging for custom payloads. ```csharp // Configure Google Cloud structured logging with log-trace correlation builder.Logging.AddGoogleCloudConsole(options => { options.IncludeScopes = true; // Set to your GCP project ID in appsettings.json: "TraceGoogleCloudProjectId": "" options.TraceGoogleCloudProjectId = builder.Configuration["TraceGoogleCloudProjectId"]; }); // HTTP endpoint auto-instrumented by OTel (no manual span code needed) app.MapGet("/rolldice/{player?}", (string? player, ILogger logger) => { var result = Random.Shared.Next(1, 7); logger.LogInformation("{player} is rolling the dice: {result}", player ?? "Anonymous", result); // Structured JSON payload logging — expands into jsonPayload in Cloud Logging logger.LogWithJsonPayload(LogLevel.Information, "Player info", new Person { Name = "John Doe", Age = 30, Courses = ["Math", "Science"] }); return result.ToString(); }); // LogWithJsonPayload extension — serializes object into Cloud Logging jsonPayload scope public static void LogWithJsonPayload(this ILogger logger, LogLevel logLevel, string message, T payloadObject) where T : class { var dictionary = JsonSerializer.Deserialize>( JsonSerializer.Serialize(payloadObject)); using (logger.BeginScope(dictionary!)) { logger.Log(logLevel, message); } } ``` ```console # Invoke the .NET service CLOUD_RUN_SERVICE_URL=$(gcloud run services describe opentelemetry-cloud-run-dotnet-sample \ --region=us-east1 --format="value(status.url)") ./loop_curl.sh 5 "${CLOUD_RUN_SERVICE_URL}/rolldice/foo" # 5 requests for player "foo" ./loop_curl.sh 10 "${CLOUD_RUN_SERVICE_URL}/rolldice/bar" # 10 requests for player "bar" ``` -------------------------------- ### Cloud Build Automation for Cloud Run Deployment Source: https://context7.com/googlecloudplatform/opentelemetry-cloud-run/llms.txt Automates the build and deploy pipeline for a multicontainer Cloud Run service. This includes building and pushing Docker images, deploying the service, and setting IAM policies. ```bash # From the golang/ or csharp/ directory ../create-service-account.sh # one-time setup gcloud builds submit . --config=cloudbuild.yaml # Check deployed service URL gcloud run services describe opentelemetry-cloud-run-golang-sample \ --region=us-east1 --format="value(status.url)" # Test the endpoint export SERVICE_URL=$(gcloud run services describe opentelemetry-cloud-run-golang-sample \ --region=us-east1 --format="value(status.url)") curl $SERVICE_URL # Output: # Logged request to /logging/sample-app.log # Generated 10 spans! # Updated sidecar-sample-counter metric! # Clean up gcloud run services delete opentelemetry-cloud-run-golang-sample --region us-east1 --quiet gcloud artifacts repositories delete run-otel-example --location=us-east1 --quiet ``` -------------------------------- ### Update run-service.yaml Placeholders Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Use sed to replace image placeholders in the run-service.yaml file with your built image URIs. ```bash sed -i s@%OTELCOL_IMAGE%@us-east1-docker.pkg.dev/${GCP_PROJECT}/run-otel-example/collector@g run-service.yaml sed -i s@%SAMPLE_APP_IMAGE%@us-east1-docker.pkg.dev/${GCP_PROJECT}/run-otel-example/sample-app@g run-service.yaml ``` -------------------------------- ### Submit Cloud Build Task Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/csharp/README.md Submits a Cloud Build task using the provided cloudbuild.yaml configuration file. This command assumes you are in the root of the repository and have a cloudbuild.yaml file present. ```bash ../../create-service-account.sh gcloud builds submit . --config=cloudbuild.yaml ``` -------------------------------- ### Enable Cloud Build API Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/csharp/README.md Enables the Cloud Build API, which is required for building container images on Google Cloud without local Docker support. This command should be run in your local terminal. ```bash gcloud services enable cloudbuild.googleapis.com --quiet ``` -------------------------------- ### Describe Cloud Run Service URL Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/csharp/README.md Retrieves the service URL for the deployed 'opentelemetry-cloud-run-dotnet-sample' Cloud Run service in the 'us-east1' region. This URL is needed to invoke the service. ```bash gcloud run services describe opentelemetry-cloud-run-dotnet-sample --region=us-east1 --format="value(status.url)" ``` -------------------------------- ### Trigger Sample App and View Telemetry Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Send a request to the Cloud Run service endpoint using curl to generate telemetry data. Save the service URL to the SERVICE_URL environment variable. ```bash export SERVICE_URL= curl $SERVICE_URL ``` -------------------------------- ### OTel Collector Config: Metrics Only to GMP Source: https://context7.com/googlecloudplatform/opentelemetry-cloud-run/llms.txt This configuration receives OTLP metrics and exports them to Google Managed Prometheus with automatic GCP resource detection. Use this when you need metrics-only collection. ```yaml receivers: otlp: protocols: grpc: endpoint: 0.0.0.0:4317 http: endpoint: 0.0.0.0:4318 processors: resourcedetection: detectors: [env, gcp] timeout: 2s override: false exporters: googlemanagedprometheus: # intentionally left blank — uses ADC credentials extensions: health_check: endpoint: 0.0.0.0:13133 service: extensions: [health_check] pipelines: metrics: receivers: [otlp] processors: [resourcedetection] exporters: [googlemanagedprometheus] ``` -------------------------------- ### Describe Cloud Run Service URL Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Retrieve the endpoint URL of the deployed Cloud Run service after a successful build. ```console gcloud run services describe opentelemetry-cloud-run-golang-sample --region=us-east1 --format="value(status.url)" ``` -------------------------------- ### OTel Collector Config: Logs Only via File + OTLP Source: https://context7.com/googlecloudplatform/opentelemetry-cloud-run/llms.txt A minimal Collector configuration that forwards logs from a shared log file and OTLP to Cloud Logging. Use this when you only need log collection without traces or metrics. ```yaml receivers: otlp: protocols: grpc: endpoint: 0.0.0.0:4317 http: endpoint: 0.0.0.0:4318 filelog: include: [/logging/*.log] start_at: beginning processors: resourcedetection: detectors: [env, gcp] timeout: 2s override: false exporters: googlecloud: log: default_log_name: my-sample-app extensions: health_check: endpoint: 0.0.0.0:13133 service: extensions: [health_check] pipelines: logs: receivers: [filelog, otlp] processors: [resourcedetection] exporters: [googlecloud] ``` -------------------------------- ### OTel Collector Config: Traces Only to Cloud Trace Source: https://context7.com/googlecloudplatform/opentelemetry-cloud-run/llms.txt This configuration receives OTLP traces and exports them directly to Cloud Trace via the `googlecloud` exporter with GCP resource auto-detection. ```yaml receivers: otlp: protocols: grpc: endpoint: 0.0.0.0:4317 http: endpoint: 0.0.0.0:4318 processors: resourcedetection: detectors: [env, gcp] timeout: 2s override: false exporters: googlecloud: # intentionally left blank — exports traces to Cloud Trace extensions: health_check: endpoint: 0.0.0.0:13133 service: extensions: [health_check] pipelines: traces: receivers: [otlp] processors: [resourcedetection] exporters: [googlecloud] ``` -------------------------------- ### Delete Cloud Run Service and Artifact Repository Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/csharp/README.md Run these commands to remove the deployed Cloud Run service and the associated Artifact Registry repository. Ensure you have the correct region specified. ```bash gcloud run services delete opentelemetry-cloud-run-dotnet-sample --region us-east1 --quiet ``` ```bash gcloud artifacts repositories delete run-otel-example \ --location=us-east1 \ --quiet ``` -------------------------------- ### Set Cloud Run Service IAM Policy Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Configure the Cloud Run service to accept unauthenticated HTTP access by setting the IAM policy. ```bash gcloud run services set-iam-policy opentelemetry-cloud-run-sample policy.yaml ``` -------------------------------- ### Invoke Cloud Run Service Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/csharp/README.md Invokes the deployed Cloud Run service multiple times using a utility script. This helps generate telemetry data for monitoring. Ensure 'loop_curl.sh' is executable. ```bash CLOUD_RUN_SERVICE_URL=$(gcloud run services describe opentelemetry-cloud-run-dotnet-sample --region=us-east1 --format="value(status.url)") # This will invoke call the service 5 times with argument "foo" ./loop_curl.sh 5 "${CLOUD_RUN_SERVICE_URL}/rolldice/foo" # This will invoke call the service 10 times with argument "bar" ./loop_curl.sh 10 "${CLOUD_RUN_SERVICE_URL}/rolldice/bar" ``` -------------------------------- ### Delete Cloud Run Service Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Clean up the deployed Cloud Run service to avoid ongoing charges. ```bash gcloud run services delete opentelemetry-cloud-run-golang-sample --region us-east1 --quiet ``` -------------------------------- ### Delete Artifacts Repository Source: https://github.com/googlecloudplatform/opentelemetry-cloud-run/blob/main/golang/README.md Remove the artifact repository used for storing container images. ```bash gcloud artifacts repositories delete run-otel-example \ --location=us-east1 \ --quiet ``` -------------------------------- ### Rename Reserved Metric Attributes (OTel Collector Config) Source: https://context7.com/googlecloudplatform/opentelemetry-cloud-run/llms.txt Use this configuration when your app emits metrics with reserved GMP label names. The transform processor renames them with an 'exported_' prefix to prevent API rejection. ```yaml processors: resourcedetection: detectors: [env, gcp] timeout: 2s override: false transform: metric_statements: - context: datapoint statements: - set(attributes["exported_location"], attributes["location"]) - delete_key(attributes, "location") - set(attributes["exported_cluster"], attributes["cluster"]) - delete_key(attributes, "cluster") - set(attributes["exported_namespace"], attributes["namespace"]) - delete_key(attributes, "namespace") - set(attributes["exported_job"], attributes["job"]) - delete_key(attributes, "job") - set(attributes["exported_instance"], attributes["instance"]) - delete_key(attributes, "instance") - set(attributes["exported_project_id"], attributes["project_id"]) - delete_key(attributes, "project_id") exporters: googlemanagedprometheus: service: pipelines: metrics: receivers: [otlp] processors: [resourcedetection, transform] exporters: [googlemanagedprometheus] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.