A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://cloud.google.com/stackdriver/docs/instrumentation/setup/go below:

Go instrumentation sample | Google Cloud Observability

Skip to main content Go instrumentation sample

Stay organized with collections Save and categorize content based on your preferences.

This document describes how to modify a Go app to collect trace and metric data using the open source OpenTelemetry framework, and how to write structured JSON logs to standard out. This document also provides information about a sample app that you can install and run. The app is configured to generate metrics, traces, and logs.

To learn more about instrumentation, see the following documents:

Note: This document displays only selected portions of a working application. For example, the sample doesn't display the list of imported packages. However, the full application is available on GitHub. To view the full sample, click more_vert More, and then select View on GitHub. About context

OpenTelemetry's Context is a mechanism for carrying execution-scoped values across APIs within a process. An important use of context is to carry the current active span so it can be modified, or referenced as the parent of any new spans when they are created. To summarize:

The Go standard library's context.Context also carries scoped values across API boundaries. Typically, handler functions in a server receive an incoming Context and pass it through the call chain to any clients making outgoing requests.

Go's standard library context.Context is used as the implementation of OpenTelemetry Context in Go.

Before you begin
  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  4. To initialize the gcloud CLI, run the following command:

    gcloud init
  5. Create or select a Google Cloud project.

    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.
  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Logging, Cloud Monitoring, and Cloud Trace APIs:

    gcloud services enable logging.googleapis.com monitoring.googleapis.com cloudtrace.googleapis.com
  8. Install the Google Cloud CLI.

  9. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  10. To initialize the gcloud CLI, run the following command:

    gcloud init
  11. Create or select a Google Cloud project.

    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.
  12. Verify that billing is enabled for your Google Cloud project.

  13. Enable the Cloud Logging, Cloud Monitoring, and Cloud Trace APIs:

    gcloud services enable logging.googleapis.com monitoring.googleapis.com cloudtrace.googleapis.com
Instrument your app to collect traces, metrics, and logs

To instrument your app to collect trace and metric data, and to write structured JSON to standard out, perform the following steps as described in subsequent sections of this document:

  1. Configure the main function
  2. Configure OpenTelemetry
  3. Configure structured logging
  4. Add instrumentation to the HTTP server
  5. Link trace spans with logs and metrics
  6. Add instrumentation to the HTTP client
  7. Write structured logs
Configure the main function

To configure the app to write structured logs and to collect metrics and trace data by using OpenTelemetry, update the main function to configure the Go structured logging package, slog, and to configure OpenTelemetry.

The following code sample illustrates a main function that calls two helper functions, setupLogging() and setupOpenTelemetry(). These helper functions configure the logging package and OpenTelemetry.

To view the full sample, click more_vert More, and then select View on GitHub.

After you configure the logging package, to link your logs to your trace data, you must pass the Go Context to the logger. For more information, see the Write structured logs section of this document.

Configure OpenTelemetry

To collect and export traces and metrics by using the OTLP protocol, configure the global TracerProvider and MeterProvider instances. The following code sample illustrates the setupOpenTelemetry function, which is called from the main function:

The previous code sample configures the global TextMapPropagator to use the W3C Trace Context format for propagating trace context. This configuration ensures that spans have the correct parent-child relationship within a trace.

To ensure that all pending telemetry is flushed and that connections are closed gracefully, the setupOpenTelemetry function returns a function named shutdown, which performs those actions.

Configure structured logging

To include the trace information as part of the JSON-formatted logs written to standard output, configure the Go structured logging package, slog. The following code sample illustrates the setupLogging function, which is called from the main function:

The previous code calls the handlerWithSpanContext function, which extracts information from the Context instance and adds that information as attributes to a log. These attributes can then be used to correlate a log with a trace:

For more information about these fields, see the LogEntry structure.

Add instrumentation to the HTTP server

To add trace and metric instrumentation to the requests handled by the HTTP server, use OpenTelemetry. The following sample uses the otelhttp handler to propagate context, and for trace and metric instrumentation:

In the previous code, the otelhttp handler uses the global TracerProvider, MeterProvider, and TextMapPropagator instances. The setupOpenTelemetry function configures these instances.

Link trace spans with logs and metrics

To link server and client spans, and to associate metrics and logs, pass the Go Context instance to the HTTP request and when you write logs. The following example illustrates a route handler that extracts the Go Context instance and the passes that instance to the logger and to the callSingle function, which makes an outgoing HTTP request:

In the previous code, the function call r.Context() retrieves the Go Context from the HTTP request.

Add instrumentation to the HTTP client

To inject the trace context into outgoing HTTP requests and to add trace and metric instrumentation, call the otelhttp.Get function. In the following example, the callSingle function performs this action:

In the previous code, the otelhttp handler uses the global TracerProvider, MeterProvider, and TextMapPropagator instances. The setupOpenTelemetry function configures these instances.

Write structured logs

To write structured logs that link to a trace, use Go's structured logging package, slog, and pass the Go Context instance to the logger. The Go Context instance is required when you want to link a log to a span. For example, the following statement shows how to call the InfoContext method for slog, and it illustrates how to add the field subRequests to the JSON instance:

slog.InfoContext(r.Context(), "handle /multi request", slog.Int("subRequests", subRequests))
Run a sample app configured to collect telemetry

The example app uses vendor-neutral formats, including JSON for logs and OTLP for metrics and traces. To route the telemetry to Google Cloud, this sample uses the OpenTelemetry Collector configured with Google exporters. The load generator in the app issues requests to the app's routes.

Download and deploy the app Note: We recommend running the sample app by using Cloud Shell. However, if you want to run the sample app locally on Linux or Mac, then skip the first step in the following instructions.

To run the sample, do the following:

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Clone the repository:

    git clone https://github.com/GoogleCloudPlatform/golang-samples
    
  3. Go to the OpenTelemetry directory:

    cd golang-samples/opentelemetry/instrumentation
    
  4. Build and run the sample:

    docker compose up --abort-on-container-exit
    

    If you aren't running on Cloud Shell, then run the application with the GOOGLE_APPLICATION_CREDENTIALS environment variable pointing to a credentials file. Application Default Credentials provides a credentials file at $HOME/.config/gcloud/application_default_credentials.json.

    # Set environment variables
    export GOOGLE_CLOUD_PROJECT="PROJECT_ID"
    export GOOGLE_APPLICATION_CREDENTIALS="$HOME/.config/gcloud/application_default_credentials.json"
    export USERID="$(id -u)"
    
    # Run
    docker compose -f docker-compose.yaml -f docker-compose.creds.yaml up --abort-on-container-exit
    
View your metrics

The OpenTelemetry instrumentation in the sample app generates Prometheus metrics that you can view by using the Metrics Explorer:

To view the metrics generated by the sample app, do the following:

  1. In the Google Cloud console, go to the leaderboard Metrics explorer page:

    Go to Metrics explorer

    If you use the search bar to find this page, then select the result whose subheading is Monitoring.

  2. In the toolbar of the Google Cloud console, select your Google Cloud project. For App Hub configurations, select the App Hub host project or the app-enabled folder's management project.
  3. In the Metric element, expand the Select a metric menu, enter http_server in the filter bar, and then use the submenus to select a specific resource type and metric:
    1. In the Active resources menu, select Prometheus Target.
    2. In the Active metric categories menu, select Http.
    3. In the Active metrics menu, select a metric.
    4. Click Apply.
  4. Configure how the data is viewed.

    When the measurements for a metric are cumulative, Metrics Explorer automatically normalizes the measured data by the alignment period, which which results in the chart displaying a rate. For more information, see Kinds, types, and conversions.

    When integer or double values are measured, such as with the two counter metrics, Metrics Explorer automatically sums all time series. To view the data for the /multi and /single HTTP routes, set the first menu of the Aggregation entry to None.

    For more information about configuring a chart, see Select metrics when using Metrics Explorer.

View your traces

It might take several minutes before your trace data is available. For example, when trace data is received by your project, Google Cloud Observability might need to create a database to store that data. The creation of the database can take a few minutes and during that period, no trace data is available to view.

To view your trace data, do the following:

  1. In the Google Cloud console, go to the Trace explorer page:

    Go to Trace explorer

    You can also find this page by using the search bar.

  2. In the table section of the page, select a row with the span name /multi.
  3. In the Gantt chart on the Trace details panel, select the span labeled /multi.

    A panel opens that displays information about the HTTP request. These details include the method, status code, number of bytes, and the user agent of the caller.

  4. To view the logs associated with this trace, select the Logs & Events tab.

    The tab shows individual logs. To view the details of the log entry, expand the log entry. You can also click View Logs and view the log by using the Logs Explorer.

For more information about using the Cloud Trace explorer, see Find and explore traces.

View your logs

From the Logs Explorer, you can inspect your logs, and you can also view associated traces, when they exist.

  1. In the Google Cloud console, go to the Logs Explorer page:

    Go to Logs Explorer

    If you use the search bar to find this page, then select the result whose subheading is Logging.

  2. Locate a log with the description of handle /multi request.

    To view the details of the log, expand the log entry. In the jsonPayload field, there is an entry labeled subRequests. This entry was added by a statement in the handleMulti function.

  3. Click Traces on a log entry with the "handle /multi request" message, and then select View trace details.

    A Trace details panel opens and displays the selected trace.

    Your log data might be available several minutes before your trace data is available. If you encounter an error when viewing trace data either by searching for a trace by ID or by following the steps in this task, then wait a minute or two and retry the action.

For more information about using the Logs Explorer, see View logs by using the Logs Explorer.

What's next

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-08-15 UTC.

[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-15 UTC."],[],[]]


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4