Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Questo documento descrive la struttura degli esempi di strumentazione forniti per i linguaggi Go, Java, Node.js e Python.
Questi esempi forniscono indicazioni su come instrumentare un'applicazione.
Potrebbero interessarti altri esempi che illustrano configurazioni diverse:
Correlare metriche e tracce utilizzando gli esemplari
descrive come configurare un'applicazione Go per generare esemplari.
Un esemplare è un punto dati di esempio allegato a un punto dati della metrica.
Puoi utilizzare gli esemplari per correlare i dati di traccia e delle metriche.
Gli esempi per Go, Java, Node.js e Python utilizzano il
protocollo OpenTelemetry per raccogliere dati di traccia e metriche.
Gli esempi configurano un framework di logging per scrivere
log strutturati e il
collettore OpenTelemetry è configurato per leggere dal
flusso stdout dell'applicazione. Per i consigli sui framework, vedi
Scegliere un approccio di strumentazione.
Le applicazioni vengono create e di cui viene eseguito il deployment utilizzando Docker. Non è necessario
utilizzare Docker quando instrumenti un'applicazione con OpenTelemetry.
Puoi eseguire gli esempi in Cloud Shell, sulle risorse Google Cloudo in un ambiente di sviluppo locale.
Approfondimento
Gli esempi utilizzano OpenTelemetry Collector come sidecar
per ricevere e arricchire i dati di telemetria dell'applicazione, che vengono poi inviati al tuo
progettoGoogle Cloud utilizzando un Google Cloud exporter. L'esportatore converte la telemetria in un formato compatibile con l'Cloud Trace API, l'API Cloud Monitoring o l'API Cloud Logging. Successivamente, inviano i dati trasformati al tuo
progettoGoogle Cloud emettendo un comando API.
Gli esempi mostrano come:
Configura OpenTelemetry per raccogliere metriche e tracce utilizzando OpenTelemetry Collector.
Se esamini gli esempi, noterai che la complessità di questo passaggio
dipende dalla lingua. Ad esempio, per Go, questo passaggio configura la
funzione main per chiamare una funzione che configura la raccolta di
metriche e tracce. Per Go, vengono aggiornati anche il server e il client HTTP.
Configura un framework di logging per scrivere log strutturati.
Ti consigliamo di scrivere log strutturati nelle tue applicazioni, in modo che
il payload del log venga formattato come oggetto JSON. Per questi log, puoi
creare query che cercano percorsi JSON specifici e puoi
indicizzare campi specifici nel payload del log.
Alcuni servizi, come Google Kubernetes Engine, hanno agenti integrati che eseguono lo scraping
dei log strutturati e li inviano al tuo progetto Google Cloud . Altri
servizi, come Compute Engine, richiedono l'installazione di un agente che
recupera e invia i log. Se vuoi saperne di più sugli agenti che installi,
consulta la panoramica di Ops Agent.
Non è necessario installare agenti per utilizzare questi esempi.
Configura i file Docker. Tutti gli esempi contengono i seguenti file YAML:
docker-compose.yaml: configura i servizi per l'applicazione, il collettore OpenTelemetry e un generatore di carico.
Ad esempio, il servizio per il raccoglitore OpenTelemetry, otelcol,
specifica un'immagine, un volume e variabili di ambiente.
L'endpoint per il collettore OpenTelemetry è impostato dalla
variabile di ambiente OTEL_EXPORTER_OTLP_ENDPOINT, specificata nel
servizio app.
otel-collector-config.yaml: configura i ricevitori, gli esportatori,
i processori e le pipeline.
Il servizio telemetry definisce le pipeline per i dati di traccia, metriche e log. Ogni voce della pipeline specifica un ricevitore, un processore e un esportatore. Lo stesso ricevitore, otlp, viene utilizzato per metriche e tracce.
La sezione exporters descrive come i dati raccolti vengono esportati in un progetto Google Cloud . Per tutta la telemetria, viene utilizzato un esportatore Google Cloud . L'esportatore converte la telemetria in un formato compatibile con l'Cloud Trace API, l'API Cloud Monitoring o l'API Cloud Logging. Successivamente, invia i dati trasformati al tuo
progettoGoogle Cloud emettendo un comando API.
docker-compose.creds.yaml: questo file monta facoltativamente un
file di credenzialiGoogle Cloud nel container otelcol. Questo file
è necessario quando un campione viene eseguito su una macchina locale in cui le
credenziali predefinite dell'applicazione (ADC) sono disponibili
solo come file.
Autorizzazioni obbligatorie
Se esegui gli esempi in Cloud Shell, sulle risorse Google Cloud
o in un ambiente di sviluppo locale, le autorizzazioni elencate
in questa sezione sono sufficienti. Per le applicazioni di produzione, in genere un account di servizio fornisce le credenziali per scrivere dati di log, metriche e traccia.
Per ottenere le autorizzazioni necessarie per consentire alle applicazioni di esempio di scrivere dati di log, metriche e tracce, chiedi all'amministratore di concederti i seguenti ruoli IAM sul progetto:
Per ottenere le autorizzazioni
necessarie per visualizzare i dati di log, metriche e tracce,
chiedi all'amministratore di concederti i seguenti ruoli IAM sul progetto:
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-08-12 UTC."],[],[],null,["# Instrumentation samples overview\n\nThis document describes the structure of the instrumentation samples provided\nfor the [Go](/stackdriver/docs/instrumentation/setup/go), [Java](/stackdriver/docs/instrumentation/setup/java),\n[Node.js](/stackdriver/docs/instrumentation/setup/nodejs), and [Python](/stackdriver/docs/instrumentation/setup/python) languages.\nThese samples provide guidance about how to instrument an application.\n\nYou might be interested in other samples that illustrate different\nconfigurations:\n\n- [Correlate metrics and traces by using exemplars](/stackdriver/docs/instrumentation/advanced-topics/exemplars)\n describes how to configure a Go application to generate exemplars.\n An *exemplar* is an example data point attached to a metric data point.\n You can use exemplars to correlate your trace and metric data.\n\n- [Use the Ops Agent and OpenTelemetry Protocol (OTLP)](/trace/docs/otlp)\n describes how you can configure the Ops Agent and an OTLP receiver to\n collect metrics and traces from an application.\n\n| **Note:** The samples display only selected portions of a working application. For example, the samples don't display the list of imported packages. However, the complete applications are available on GitHub. From a code snippet, you can open GitHub by using the *more_vert* **More** options.\n\nHow the samples work\n--------------------\n\nThe samples for Go, Java, Node.js, and Python use the\n[OpenTelemetry protocol](https://opentelemetry.io/docs/specs/otlp/) to collect trace and metric data.\nThe samples configure a logging framework to write\n[structured logs](/logging/docs/structured-logging) and the\nOpenTelemetry collector is configured to read from\nthe application's `stdout` stream. For framework recommendations, see\n[Choose an instrumentation approach](/stackdriver/docs/instrumentation/choose-approach).\n\nThe applications are built and deployed by using Docker. You don't have to\nuse Docker when you instrument an application with OpenTelemetry.\n\nYou can run the samples in the Cloud Shell, on Google Cloud\nresources, or on a local development environment.\n\nDeep dive\n---------\n\nThe samples use the [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/installation/) as a sidecar\nto receive and enrich the application's telemetry, which is then sent to your\nGoogle Cloud project by using a [Google Cloud exporter](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/exporter/googlecloudexporter/README.md). The exporter\nconverts the\ntelemetry into a format compatible with the Cloud Trace API, Cloud Monitoring API,\nor Cloud Logging API. Next, they send the transformed data to your\nGoogle Cloud project by issuing an API command.\n\nThe samples show how to do the following:\n\n1. Configure OpenTelemetry to collect metrics and traces by using the\n [OpenTelemetry collector](https://opentelemetry.io/docs/collector/).\n\n If you review the samples, you'll notice that the complexity of this step\n is language dependent. For example, for Go, this step configures the\n `main` function to call a function that configures the collection of\n metrics and traces. For Go, the HTTP server and client are also updated.\n2. Configure a logging framework to write [structured logs](/logging/docs/structured-logging).\n\n We recommend that your applications write structured logs, which results\n in the log payload being formatted as a JSON object. For these logs, you can\n construct queries that search specific JSON paths and you can\n index specific fields in the log payload.\n\n Some services, like Google Kubernetes Engine, have built-in agents that scrape\n structured logs and send those logs to your Google Cloud project. Other\n services, like Compute Engine, require that you install an agent, which\n scrapes and sends your logs. If you want to learn about agents you install,\n see [Ops Agent overview](/stackdriver/docs/solutions/agents/ops-agent).\n\n You don't need to install any agents to use these samples.\n3. Configure Docker files. All samples contain the following yaml files:\n\n - `docker-compose.yaml`: Configures the services for the application,\n the [OpenTelemetry collector](https://opentelemetry.io/docs/collector/), and a load generator.\n For example, the service for the OpenTelemetry collector, `otelcol`,\n specifies an image, a volume, and environment variables.\n The endpoint for the OpenTelemetry collector is set by the\n `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable, which is\n specified in the `app` service.\n\n - `otel-collector-config.yaml`: Configures the receivers, exporters,\n processors, and pipelines.\n\n The `telemetry` service defines pipelines for trace, metric, and log\n data. Each pipeline entry specifies a receiver, a processor, and an\n exporter. The same receiver, `otlp`, is used for metrics and traces.\n\n The `exporters` section describes how collected data is exported to\n a Google Cloud project. For all telemetry, a Google Cloud exporter is\n utilized. The exporter converts the telemetry into a format\n compatible with the Cloud Trace API, Cloud Monitoring API, or\n Cloud Logging API. Next, it sends the transformed data to your\n Google Cloud project by issuing an API command.\n - `docker-compose.creds.yaml`: This file optionally mounts a\n Google Cloud credentials file in the `otelcol` container. This file\n is needed when a sample is run on a local machine where the\n [Application Default Credentials (ADC)](/docs/authentication/application-default-credentials) are available\n only as a file.\n\nRequired permissions\n--------------------\n\nIf you run the samples in the Cloud Shell, on Google Cloud\nresources, or on a local development environment, then the permissions listed\nin this section are sufficient. For production applications, typically a\nservice account provides the credentials to write log, metric, and trace\ndata.\n\n-\n\n To get the permissions that\n you need to for the sample applications to write log, metric, and trace data,\n\n ask your administrator to grant you the\n following IAM roles on your project:\n\n - [Logs Writer](/iam/docs/roles-permissions/logging#logging.logWriter) (`roles/logging.logWriter`)\n - [Monitoring Metric Writer](/iam/docs/roles-permissions/monitoring#monitoring.metricWriter) (`roles/monitoring.metricWriter`)\n - [Cloud Trace Agent](/iam/docs/roles-permissions/cloudtrace#cloudtrace.agent) (`roles/cloudtrace.agent`)\n\n\n\u003c!-- --\u003e\n\n-\n\n To get the permissions that\n you need to view your log, metric, and trace data,\n\n ask your administrator to grant you the\n following IAM roles on your project:\n\n - [Logs Viewer](/iam/docs/roles-permissions/logging#logging.viewer) (`roles/logging.viewer`)\n - [Monitoring Viewer](/iam/docs/roles-permissions/monitoring#monitoring.viewer) (`roles/monitoring.viewer`)\n - [Cloud Trace User](/iam/docs/roles-permissions/cloudtrace#cloudtrace.user) (`roles/cloudtrace.user`)\n\n\n For more information about granting roles, see [Manage access to projects, folders, and organizations](/iam/docs/granting-changing-revoking-access).\n\n\n You might also be able to get\n the required permissions through [custom\n roles](/iam/docs/creating-custom-roles) or other [predefined\n roles](/iam/docs/roles-overview#predefined).\n\nRequired APIs\n-------------\n\nThe following provides information about the APIs required to send\ntelemetry data to a Google Cloud project: \n\n### Google Cloud console\n\n\nEnable the Cloud Logging, Cloud Monitoring, and Cloud Trace APIs.\n\n\n[Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=logging.googleapis.com,monitoring.googleapis.com,cloudtrace.googleapis.com)\n\n\u003cbr /\u003e\n\n### Google Cloud CLI\n\n\nEnable the Cloud Logging, Cloud Monitoring, and Cloud Trace APIs.\n\n\n[Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=logging.googleapis.com,monitoring.googleapis.com,cloudtrace.googleapis.com)\n\n\u003cbr /\u003e\n\nWhat's next\n-----------\n\n- [Go sample](/stackdriver/docs/instrumentation/setup/go).\n- [Java sample](/stackdriver/docs/instrumentation/setup/java).\n- [Node.js sample](/stackdriver/docs/instrumentation/setup/nodejs).\n- [Python sample](/stackdriver/docs/instrumentation/setup/python)."]]