From 868a5b6de946417f3b66c00145607c08a43f9756 Mon Sep 17 00:00:00 2001 From: Jack Berg Date: Wed, 17 Jan 2024 12:27:58 -0600 Subject: [PATCH 1/4] Update opentelemetry docs to prefer OTLP http/protobuf over grpc --- ...entelemetry-best-practices-compression.mdx | 2 +- .../opentelemetry-best-practices-metrics.mdx | 2 +- .../opentelemetry-collector-docker.mdx | 8 +- .../opentelemetry-collector-hivemq.mdx | 38 +- .../opentelemetry-collector-prometheus.mdx | 26 +- .../opentelemetry-collector-redis.mdx | 24 +- .../opentelemetry-collector-squid.mdx | 6 +- .../opentelemetry-collector-statsd.mdx | 8 +- .../opentelemetry-collector-basic.mdx | 9 +- .../opentelemetry-collector-infra-hosts.mdx | 25 +- .../opentelemetry-set-up-your-app.mdx | 13 +- .../get-started/opentelemetry-tutorial-go.mdx | 804 ------------------ .../opentelemetry-tutorial-java.mdx | 16 +- .../opentelemetry-tutorial-python.mdx | 74 +- 14 files changed, 135 insertions(+), 920 deletions(-) delete mode 100644 src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-compression.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-compression.mdx index 7a08c41af3e..7b88c1fc230 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-compression.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-compression.mdx @@ -17,7 +17,7 @@ To enable `zstd` in the collector, adapt the collector exporter config: ``` exporters: - otlp: + otlphttp: ... compression: zstd diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-metrics.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-metrics.mdx index ccca17a7bd4..bcdb88715f4 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-metrics.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-metrics.mdx @@ -52,7 +52,7 @@ Cumulative sums are handled differently depending on whether they're monotonic o #### Sum configuration examples [#config-sums] -To understand how to configure aggregation temporality, see these examples using the [Java](https://github.com/newrelic/newrelic-opentelemetry-examples/tree/main/java/sdk-nr-config) and [Go](https://github.com/newrelic/newrelic-opentelemetry-examples/tree/main/go) OpenTelemetry SDKs. +To understand how to configure aggregation temporality, see these examples using the [Java](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-java) and [Python](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-python) OpenTelemetry SDKs. ### Gauge metrics [#gauge] diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-docker.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-docker.mdx index a731d96c32e..9b3525de6cc 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-docker.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-docker.mdx @@ -45,7 +45,7 @@ Download and install the Opentelemetry collector following [Opentelemetry docs]( You will need to install [OpenTelemetry Collector Contrib Distro](https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib) or other distribution including, at least, the following components: * [Dockerstats receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/dockerstatsreceiver) -* [OTLP exporter](https://pkg.go.dev/go.opentelemetry.io/collector/exporter/otlpexporter) +* [OTLP/HTTP exporter](https://github.com/open-telemetry/opentelemetry-collector/tree/main/exporter/otlphttpexporter) * [Resource processor](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/resourceprocessor/README.md) * [Resource detection processor](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/resourcedetectionprocessor/README.md) @@ -116,8 +116,8 @@ processors: override: false exporters: - otlp: - endpoint: https://otlp.nr-data.net:443 + otlphttp: + endpoint: https://otlp.nr-data.net headers: api-key: NEW_RELIC_LICENSE_KEY @@ -131,7 +131,7 @@ service: - resourcedetection - resourcedetection/cloud - resource - exporters: [otlp] + exporters: [otlphttp] ``` For further configuration options, please review: diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-hivemq.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-hivemq.mdx index d40e1ea4569..d2be8e2c843 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-hivemq.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-hivemq.mdx @@ -28,7 +28,7 @@ If you haven't already done so, sign up for a free [New Relic account](https://n ## Review the prerequisites [#prerequisites] [Configure the prometheus extension](https://github.com/hivemq/hivemq-prometheus-extension/blob/master/README.adoc) in your HiveMQ message platform. - + ## Install the Opentelemetry collector [#install-opentelemetry-collector] @@ -62,8 +62,8 @@ receivers: metrics_path: HIVEMQ_PROMETHEUS_METRICS_PATH exporters: - otlp: - endpoint: https://otlp.nr-data.net:4317 + otlphttp: + endpoint: https://otlp.nr-data.net headers: api-key: NEW_RELIC_LICENSE_KEY processors: @@ -79,7 +79,7 @@ service: metrics: receivers: [prometheus] processors: [batch, memory_limiter] - exporters: [otlp] + exporters: [otlphttp] ``` You may check [Opentelemetry Collector docs](https://opentelemetry.io/docs/collector/configuration/) and [Prometheus configuration docs](https://prometheus.io/docs/prometheus/latest/configuration/configuration/) for additional configuration details. @@ -103,14 +103,14 @@ You may use the [metrics explorer](/docs/query-your-data/explore-query-data/brow ## Metric data details [#hivemq-metrics] -The table below lists examples of the kinds of metrics we collect. +The table below lists examples of the kinds of metrics we collect. * Not all metrics may be available (and you may find additional metrics) depending on your HiveMQ setup, and not all metrics are available in the HiveMQ Community Edition. * API REST module only exposes metrics when enabled. -* Certain HiveMQ extensions report specific metrics. +* Certain HiveMQ extensions report specific metrics. * For a full list of HiveMQ metrics, see [HiveMQ documentation on available metrics](https://www.hivemq.com/docs/hivemq/latest/user-guide/monitoring.html#available-metrics). - + Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/user-guide/monitoring.html#available-metrics) for additional information. @@ -133,7 +133,7 @@ Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/u - + `com_hivemq_cache_internal_export_states_averageLoadPenalty` @@ -754,7 +754,7 @@ Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/u - + `com_hivemq_backup_executor_completed_total` @@ -3075,7 +3075,7 @@ Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/u - + `com_hivemq_internal_after_join_cleanup_attributes_removal_in_progress_count` @@ -8756,7 +8756,7 @@ Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/u - + `com_hivemq_messages_client_pending_qos_0_count` @@ -9867,7 +9867,7 @@ Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/u - + `com_hivemq_rest_api_authentication_failed` @@ -9948,7 +9948,7 @@ Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/u - + `com_hivemq_cluster_internal_barrier_in_flight_threads_count` @@ -10869,7 +10869,7 @@ Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/u - + `com_hivemq_extension_consumer_messages_async_timed_out_total_count` @@ -11030,7 +11030,7 @@ Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/u - + `com_hivemq_jvm_buffer_pool_direct_capacity` @@ -11481,7 +11481,7 @@ Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/u - + `com_hivemq_networking_bytes_read_current` @@ -11602,7 +11602,7 @@ Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/u - + `com_hivemq_overload_protection_clients_average_credits` @@ -11723,7 +11723,7 @@ Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/u - + `com_hivemq_system_max_file_descriptor` @@ -12294,7 +12294,7 @@ Check [HiveMQ metrics documentation](https://www.hivemq.com/docs/hivemq/latest/u - + `com_hivemq_control_center_tls_handshake_failed` diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-prometheus.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-prometheus.mdx index b85644f8796..70adaf35a09 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-prometheus.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-prometheus.mdx @@ -19,7 +19,7 @@ Complete the steps below to collect Prometheus metrics. - ## Check for these prerequisites + ## Check for these prerequisites If you haven't already: @@ -27,8 +27,8 @@ If you haven't already: * In your target app, make sure you're exposing the Prometheus metrics endpoint so it is accessible to the Prometheus receiver component in the OpenTelemetry collector. * The Prometheus metrics endpoint could be enabled by default or you may need do do additional configuration to enable it. * Some software may require a [third-party Prometheus exporter](https://prometheus.io/docs/instrumenting/exporters/#third-party-exporters) to expose metrics. -* Install the OpenTelemetry collector by following the steps in the [OpenTelemetry docs](https://opentelemetry.io/docs/collector/getting-started/). -* You can use any distribution so long as they have these two components: [OTLP exporter](https://pkg.go.dev/go.opentelemetry.io/collector/exporter/otlpexporter) and [Prometheus receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/prometheusreceiver) +* Install the OpenTelemetry collector by following the steps in the [OpenTelemetry docs](https://opentelemetry.io/docs/collector/getting-started/). +* You can use any distribution so long as they have these two components: [OTLP/HTTP exporter](https://github.com/open-telemetry/opentelemetry-collector/tree/main/exporter/otlphttpexporter) and [Prometheus receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/prometheusreceiver) @@ -38,7 +38,7 @@ Update or create a new file called `config.yaml` and replace the following keys * Prometheus scrape config: * `PROMETHEUS_JOBNAME` - * `PROMETHEUS_HOSTNAME` + * `PROMETHEUS_HOSTNAME` * `PROMETHEUS_ENDPOINT_PORT` * `PROMETHEUS_ENDPOINT_PATH` (optional, default is /metrics) * [New Relic License key](/docs/apis/intro-apis/new-relic-api-keys/#license-key): @@ -57,8 +57,8 @@ receivers: metrics_path: PROMETHEUS_ENDPOINT_PATH exporters: - otlp: - endpoint: https://otlp.nr-data.net:4317 + otlphttp: + endpoint: https://otlp.nr-data.net headers: api-key: NEW_RELIC_LICENSE_KEY processors: @@ -69,7 +69,7 @@ service: metrics: receivers: [prometheus] processors: [batch, memory_limiter] - exporters: [otlp] + exporters: [otlphttp] ``` For further configuration options, please review: @@ -80,7 +80,7 @@ For further configuration options, please review: - ## Run the collector + ## Run the collector Run the Opentelemetry collector. The way to run it may vary depending on the chosen installation method. For example: @@ -95,10 +95,10 @@ For further configuration options, please review: You may use the [metrics explorer](/docs/query-your-data/explore-query-data/browse-data/introduction-data-explorer) to check the metrics being ingested. All metrics reported by the OTEL Prometheus receiver are detected by running the following query. ```sql -SELECT count(*) -FROM Metric -WHERE instrumentation.provider='opentelemetry' and otel.library.name='otelcol/prometheusreceiver' -FACET metricName +SELECT count(*) +FROM Metric +WHERE instrumentation.provider='opentelemetry' and otel.library.name='otelcol/prometheusreceiver' +FACET metricName ``` @@ -112,4 +112,4 @@ FACET metricName ```shell otelcol-contrib --config ./config.yaml --feature-gates=-pkg.translator.prometheus.NormalizeName - ``` \ No newline at end of file + ``` diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-redis.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-redis.mdx index ce961d80b56..6d1a52da6f3 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-redis.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-redis.mdx @@ -23,13 +23,13 @@ After going through the installation steps, you'll view this metric data in pre- ## Prerequisites [#prereq] -In order to start collecting Redis metrics, you need to sign up for a free New Relic account. +In order to start collecting Redis metrics, you need to sign up for a free New Relic account. Once you've signed up, make sure you've set up: -* The [redis receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/redisreceiver) component, as the collector requires access to Redis through an endpoint. Minimum version recommended is v0.83.0. +* The [redis receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/redisreceiver) component, as the collector requires access to Redis through an endpoint. Minimum version recommended is v0.83.0. * The OpenTelemetry collector following [OpenTelemetry docs](https://opentelemetry.io/docs/collector/getting-started/) @@ -42,13 +42,13 @@ Once you've signed up, make sure you've set up: You will need to install [OpenTelemetry Collector Contrib Distro](https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib). If you're using another distribution, confirm that your chosen distribution has the following components: * [Redis receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/redisreceiver) -* [OTLP exporter](https://pkg.go.dev/go.opentelemetry.io/collector/exporter/otlpexporter) +* [OTLP/HTTP exporter](https://github.com/open-telemetry/opentelemetry-collector/tree/main/exporter/otlphttpexporter) * [Attribute processor](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/attributesprocessor/README.md) * [Resource processor](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/resourceprocessor/README.md) * [Resource detection processor](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/resourcedetectionprocessor/README.md) -If your distribution does not have these components, then the config file in the next step does **not** apply. +If your distribution does not have these components, then the config file in the next step does **not** apply. @@ -68,7 +68,7 @@ receivers: enabled: true processors: - # This is needed since redis receiver is not currently adding any means to understand to which redis server the metrics are referring to + # This is needed since redis receiver is not currently adding any means to understand to which redis server the metrics are referring to attributes/redis_metrics: include: match_type: regexp @@ -96,8 +96,8 @@ processors: override: false exporters: - otlp: - endpoint: https://otlp.nr-data.net:443 + otlphttp: + endpoint: https://otlp.nr-data.net headers: api-key: @@ -112,11 +112,11 @@ service: - resourcedetection/cloud - resource - attributes/redis_metrics - exporters: [otlp] + exporters: [otlphttp] ``` * Replace the `NEW_RELIC_LICENSE_KEY` in the file with your own values. For more info, see the [New Relic License key](/docs/apis/intro-apis/new-relic-api-keys/#license-key). -* Since no identificator is attached by the OTel receiver to redis metrics, an attribute processor is needed to decorate metrics with `server.address` and `server.port` metadata. The attributes `server.address` and `server.port` are needed to be able to query and facet data differentiating between Redis servers and to create New Relic entities. +* Since no identifier is attached by the OTel receiver to redis metrics, an attribute processor is needed to decorate metrics with `server.address` and `server.port` metadata. The attributes `server.address` and `server.port` are needed to be able to query and facet data differentiating between Redis servers and to create New Relic entities. * Moreover, separate pipelines with different instances of `resource/redis_metrics` are needed in case multiple Redis servers are monitored from a single otel collector to decorate each instance with the corresponding metadata. To look at other configuration options, see: @@ -127,7 +127,7 @@ To look at other configuration options, see: - ### Run the collector + ### Run the collector Run the OpenTelemetry collector (the way to run it may vary depending on the chosen installation method). Example: @@ -137,7 +137,7 @@ Run the OpenTelemetry collector (the way to run it may vary depending on the cho - ### Explore your data + ### Explore your data Telemetry data originating from the OpenTelemetry Redis receiver, if properly decorated, generates redis entities. [Entities](/docs/new-relic-solutions/new-relic-one/core-concepts/what-entity-new-relic/) are anything that reports data to New Relic and is identified by an unique entity ID. @@ -147,7 +147,7 @@ Check this [document](/docs/new-relic-solutions/new-relic-one/core-concepts/new- - ### Query your data with metrics explorer + ### Query your data with metrics explorer You may use the [metrics explorer](/docs/query-your-data/explore-query-data/browse-data/introduction-data-explorer) to check the metrics being ingested. All metrics reported by the redis receiver start by the `"redis."` prefix. diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-squid.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-squid.mdx index 38d39c84274..9340faecf70 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-squid.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-squid.mdx @@ -83,8 +83,8 @@ receivers: action: drop exporters: - otlp: - endpoint: https://otlp.nr-data.net:4317 + otlphttp: + endpoint: https://otlp.nr-data.net headers: api-key: NEW_RELIC_LICENSE_KEY processors: @@ -100,7 +100,7 @@ service: metrics: receivers: [prometheus] processors: [batch, memory_limiter] - exporters: [otlp] + exporters: [otlphttp] ``` You may check [Opentelemetry Collector docs](https://opentelemetry.io/docs/collector/configuration/) and [Prometheus configuration docs](https://prometheus.io/docs/prometheus/latest/configuration/configuration/) for additional configuration details. diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-statsd.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-statsd.mdx index 3db9755400c..50e6d83512a 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-statsd.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/collector-configuration-examples/opentelemetry-collector-statsd.mdx @@ -28,7 +28,7 @@ Download and install the OpenTelemetry collector following the [OpenTelemetry do You will need to install [OpenTelemetry Collector Contrib Distro](https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib) or other distribution including, at least, these components: * [StatsD receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/statsdreceiver) -* [OTLP exporter](https://pkg.go.dev/go.opentelemetry.io/collector/exporter/otlpexporter) +* [OTLP/HTTP exporter](https://github.com/open-telemetry/opentelemetry-collector/tree/main/exporter/otlphttpexporter) ## Step 4: Configure OpenTelemetry collector [#configure-opentelemetry-collector] @@ -43,8 +43,8 @@ receivers: is_monotonic_counter: true exporters: - otlp: - endpoint: https://otlp.nr-data.net:443 + otlphttp: + endpoint: https://otlp.nr-data.net headers: api-key: NEW_RELIC_LICENSE_KEY @@ -54,7 +54,7 @@ service: pipelines: metrics: receivers: [statsd] - exporters: [otlp] + exporters: [otlphttp] ``` For further configuration options, please review: diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-basic.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-basic.mdx index 9680b9599ca..a1c31dcfae3 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-basic.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-basic.mdx @@ -27,7 +27,7 @@ The collector setup is part of the larger process of setting up OpenTelemetry wi batch: exporters: - otlp: + otlphttp: endpoint: ${OTEL_EXPORTER_OTLP_ENDPOINT} headers: api-key: ${NEW_RELIC_LICENSE_KEY} @@ -37,15 +37,15 @@ The collector setup is part of the larger process of setting up OpenTelemetry wi traces: receivers: [otlp] processors: [batch] - exporters: [otlp] + exporters: [otlphttp] metrics: receivers: [otlp] processors: [batch] - exporters: [otlp] + exporters: [otlphttp] logs: receivers: [otlp] processors: [batch] - exporters: [otlp] + exporters: [otlphttp] ``` 2. Run the OpenTelemetry Collector after you make the following changes: @@ -60,6 +60,7 @@ The collector setup is part of the larger process of setting up OpenTelemetry wi -e OTEL_EXPORTER_OTLP_ENDPOINT \ -e NEW_RELIC_LICENSE_KEY \ -p 4317:4317 \ + -p 4318:4318 \ -v "${PWD}/otel-config.yaml":/otel-config.yaml \ --name otelcol \ otel/opentelemetry-collector \ diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-infra-hosts.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-infra-hosts.mdx index b58795f9d10..7e5ab9d9441 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-infra-hosts.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-infra-hosts.mdx @@ -65,7 +65,8 @@ receivers: otlp: protocols: grpc: - + http: + hostmetrics: collection_interval: 20s scrapers: @@ -108,7 +109,7 @@ receivers: - /var/log/yum.log processors: - + transform/truncate: trace_statements: - context: span @@ -125,9 +126,9 @@ processors: check_interval: 1s limit_mib: 1000 spike_limit_mib: 200 - + batch: - + resourcedetection: detectors: [env, system] system: @@ -135,7 +136,7 @@ processors: resource_attributes: host.id: enabled: true - + resourcedetection/cloud: detectors: ["gcp", "ec2", "azure"] timeout: 2s @@ -149,7 +150,7 @@ processors: action: insert exporters: - otlp: + otlphttp: endpoint: OTLP_ENDPOINT_HERE headers: api-key: YOUR_KEY_HERE @@ -157,21 +158,21 @@ logging: service: pipelines: - + metrics: receivers: [hostmetrics] processors: [memory_limiter, resourcedetection, resourcedetection/cloud, batch] - exporters: [logging, otlp] - + exporters: [logging, otlphttp] + traces: receivers: [otlp] processors: [memory_limiter, transform/truncate, resourcedetection, resourcedetection/cloud, batch] - exporters: [logging, otlp] - + exporters: [logging, otlphttp] + logs: receivers: [otlp, filelog] processors: [memory_limiter, transform/truncate, resourcedetection, resourcedetection/cloud, batch] - exporters: [logging, otlp] + exporters: [logging, otlphttp] extensions: [health_check] ``` diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-set-up-your-app.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-set-up-your-app.mdx index 0644c961265..c6df4b02b17 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-set-up-your-app.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-set-up-your-app.mdx @@ -276,7 +276,16 @@ Whether you export directly from your app or from a collector, you'll need to: id="note-ports" title="Why three ports?" > - OTLP standards designate gRPC traffic to port `4317`, and HTTP traffic to port `4318`. The New Relic US FedRamp Native OTLP endpoint adheres to those specifications. It also allows gRPC traffic on port `443`. + OTLP standards designate gRPC traffic to port `4317`, and HTTP traffic to port `4318`. The New Relic US FedRamp Native OTLP endpoint adheres to those specifications. It also allows both gRPC and HTTP traffic on port `443`. For simplicity, you can omit the port since the `https` scheme automatically selects port `443`. + + + OTLP has [three different versions](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#specify-protocol) of the protocol: `grpc`, `http/protobuf`, and `http/json`. Support for the different versions varies by language. + + While New Relic supports all versions, if given the choice we recommend using `http/protobuf`. This is the default recommendation from the specification, and has proved to be more robust than `grpc` without any apparent reduction in performance. - - Try out any of these Go tutorials to see what the New Relic platform can do with your OTLP data. We have two tutorials you can choose from, each one using the same demo app. The app will calculate the nth number in the Fibonacci sequence and generate traces and metrics. - - By working through these tutorials, you can learn skills to help you set up your own app with OpenTelemetry and New Relic. - - - - Screenshot showing response time, throughput, and error rate - -
- After you finish any of these tutorials, you can view span metrics in charts like these. -
-
- - -While each tutorial uses the same demo app, they have different approaches to help you become acquainted with OpenTelemetry and New Relic. Try out the options that are interesting to you: - - * [Tutorial 1: Run the pre-instrumented demo app:](#pre-instrum) This is the fastest way to send some demo data to New Relic and see how it is displayed in the UI. In this tutorial, the demo app has pre-loaded instrumentation and SDK configurations that follow our [best practices](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-overview/) to generate and export traces and metrics. You can inspect our code and apply relevant sections to your own apps. - * [Tutorial 2: Set up the demo app manually:](#manual-instrum) In this track, you'll roll up your sleeves and tinker with the engine of the car. This is the approach to take if you want to have the most control over what telemetry is reported and want to see details about how it's done. You'll manually insert instrumentation into our demo app to capture telemetry and you'll configure the SDK to export that data to New Relic. - -The [OpenTelemetry Go Automatic Instrumentation](https://github.com/open-telemetry/opentelemetry-go-instrumentation) is currently being developed, so it is not included in the tutorial at this time. - - -You have two choices for exporting data from your application to New Relic via OTLP: -* Directly from your app -* Via an OpenTelemetry collector - -This guide covers the first option. If you wish to export your data via a collector, check out this [collector documentation](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-basic/) for details. - -## Requirements [#requirements] - -Before you get started, make sure you have the following: - -* A New Relic account: Sign up for a [free account](https://newrelic.com/signup) if you don't already have one. -* [Go 1.16 or newer](https://go.dev/doc/install) - -## Tutorial 1: Run the pre-instrumented demo app [#pre-instrum] - -This is a great option if you want us to do the instrumentation so you can quickly see what's it's like to send data to New Relic and view it in our UI. - -1. In your terminal, run the following to clone the demo app and navigate to the Getting Started Guides' `go/Instrumented` directory. - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/go/Instrumented - ``` -2. Set these environment variables to send data to your New Relic account: - * Make sure to use your . - * If your New Relic data center region is EU and not US, set the endpoint to: `https://otlp.eu01.nr-data.net:4317` - - * OTEL_EXPORTER_OTLP_HEADERS=api-key=INSERT_YOUR_NEW_RELIC_LICENSE_KEY - * OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:4317 -3. Set this environment variable to name the service; this is how you will identify your service in your New Relic account: - * OTEL_SERVICE_NAME=getting-started-python -3. In the same `getting-started-guides/python/Instrumented/` directory, create and activate a virtual environment, install the required libraries, and run the app: - * macOS: - ``` - python3 -m venv venv - source venv/bin/activate - pip install -r requirements.txt - python3 app.py - ``` - - * PowerShell: - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - pip install -r requirements.txt - python app.py - ``` -4. Open a new terminal tab, switch to the `getting-started-guides/python/Instrumented` directory, and run the following command to generate some traffic to the application: - * macOS: - ``` - ./load-generator.sh - ``` - * PowerShell: - ``` - .\load-generator.ps1 - ``` - - - Alternatively, you can reach the endpoint in the browser at this URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Replace `INSERT_A_VALUE` with a value from 1 to 90. To generate an error, insert an integer outside the valid range. - - -5. Go to **[one.newrelic.com](https://one.newrelic.com/all-capabilities) > APM & services**. -6. Click your new entity (service) called `getting-started-python` and explore the UI. For more tips about what to look for in the UI, see [View your data in New Relic](#view-data). -7. When you're finished looking at your data in the UI, shut down the application by pressing `CONTROL+C` in both terminal sessions. - -## Tutorial 2: Monitor the demo app with the OpenTelemetry Python agent [#python-agent] - -Here's a different tutorial that also uses the same demo app, but in this case, you'll use the OpenTelemetry Python agent to automatically monitor the demo app. You don't need to modify the Python source code. By using the agent, you can quickly start exporting sample data to New Relic. - -Note, however, that you will need to add custom instrumentation to capture deeper levels of information about the app, such as logs and custom metrics. - -The auto-instrumentation agent is a series PyPI package that dynamically injects bytecode to capture telemetry from popular libraries and frameworks. You can also use it to capture data such as inbound requests, outbound HTTP calls, and database calls. It can be attached to any Python 3 application. - - - See the [official OpenTelemetry Python agent documentation](https://opentelemetry.io/docs/instrumentation/python/automatic/) for additional configuration options. - - -To monitor our demo app with the OpenTelemetry Python agent: - -1. Execute these two commands to download the demo application repository and change to the following directory: - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` -2. Go to our [environment variables reference section](#ref-env-vars) below to see which variables you need to export and then return to these steps. - -3. Then, in the same `getting-started-guides/python/Uninstrumented/` directory, create and activate a virtual environment: - * macOS: - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * PowerShell: - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` -4. You are now ready to install the required libraries: - ``` - pip install flask - pip install opentelemetry-instrumentation-flask - pip install opentelemetry-exporter-otlp - pip install opentelemetry-distro - ``` - -5. Continue in `getting-started-guides/python/Uninstrumented/` to launch the agent with the app: - * macOS: - ``` - opentelemetry-instrument python3 app.py - ``` - * PowerShell: - ``` - opentelemetry-instrument python app.py - ``` -6. Generate traffic to the application by opening a new terminal in the `getting-started-guides/python/Uninstrumented` directory and running the load generator: - * macOS: - ``` - ./load-generator.sh - ``` - * PowerShell: - ``` - .\load-generator.ps1 - ``` - - Alternatively, you can reach the endpoint in the browser at this URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Replace `INSERT_A_VALUE` with a value from 1 to 90. To generate an error, insert an integer outside the valid range. - - -7. Now that you've sent some data to New Relic, see our [instructions on viewing the data in the UI](#view-data). - -8. When you're finished looking at your data in the UI, shut down the application by pressing `CONTROL+C` in both terminal sessions. - - -## Tutorial 3: Set up the demo app manually [#manual-instrum] - -The previous section helped you explore automatic instrumentation with the OpenTelemetry Python agent. If you prefer to have more control over the telemetry you gather, you can try out this tutorial to learn how to add custom instrumentation. Then, you'll see how to configure the OpenTelemetry SDK to export the data to New Relic, using our recommended best practices. - -Here are the steps you'll complete for this manual setup: - -* [A. Download the demo application](#download) -* [B. Install required libraries](#libraries) -* [C. Configure the SDK](#config-sdk) -* [D. Add instrumentation libraries: traces](#library-traces) -* [E. Add instrumentation libraries: metrics](#library-metrics) -* [F. Add instrumentation libraries: logs](#library-logs) -* [G. Add Flask instrumentation](#flask-instrum) -* [H. Custom trace instrumentation: Create a custom span](#cust-span) -* [I. Custom trace instrumentation: Record an exception](#span-exception) -* [J. Custom metric instrumentation: Add a custom metric counter](#cust-metrics) -* [K. Custom log instrumentation](#cust-log) -* [L. Exercise the app to generate some traffic](#exercise-app) - -### A. Download the demo application [#download] - -Run the following to download our demo app: - -``` -git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git -``` - -### B. Install required libraries [#libraries] - -To add the required libraries: - -1. Go to the application directory for the uninstrumented app as the starting point for this tutorial. By the end of this tutorial, the code should look like the one in the `Instrumented` directory. - ``` - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` -2. Create and activate a virtual environment in the `Uninstrumented` directory: - * macOS: - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * PowerShell: - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` -3. Install the following: - ``` - pip install opentelemetry-api - pip install opentelemetry-sdk - pip install flask - pip install opentelemetry-instrumentation-logging - pip install opentelemetry-instrumentation-flask - pip install opentelemetry-exporter-otlp - pip install opentelemetry-distro - ``` - -### C. Configure the SDK [#config-sdk] - -1. In `app.py`, add the highlighted lines below to the **top of the file**. Change the value for the custom attribute `environment` as needed. - -```python lineHighlight=1-10 -########################## -# OpenTelemetry Settings # -########################## -from opentelemetry.sdk.resources import Resource -import uuid - -OTEL_RESOURCE_ATTRIBUTES = { - "service.instance.id": str(uuid.uuid1()), - "environment": "local" -} - -from flask import Flask, jsonify, request - -app = Flask(__name__) -``` - -2. Go to our [environment variables reference section](#ref-env-vars) below to see which variables you need to export, and then move forward to the next step to add instrumentation libraries. - -### D. Add instrumentation libraries: traces [#library-traces] - -In `app.py`, insert the following after the `OpenTelemetry Settings` you added: - -```python -########## -# Traces # -########## -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter -from opentelemetry.trace.status import Status, StatusCode - -# Initialize tracing and an exporter that can send data to an OTLP endpoint -# SELECT * FROM Span WHERE instrumentation.provider='opentelemetry' -trace.set_tracer_provider(TracerProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES))) -trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) -``` - -### E. Add instrumentation libraries: metrics [#library-metrics] - -In `app.py` add the following after the `Traces` section you added in Step D: - -```python -########### -# Metrics # -########### -from opentelemetry import metrics -from opentelemetry.sdk.metrics import MeterProvider -from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter - -# Initialize metering and an exporter that can send data to an OTLP endpoint -# SELECT count(`http.server.active_requests`) FROM Metric FACET `service.name` TIMESERIES -metrics.set_meter_provider(MeterProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES), metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())])) -metrics.get_meter_provider() -fib_counter = metrics.get_meter("opentelemetry.instrumentation.custom").create_counter("fibonacci.invocations", unit="1", description="Measures the number of times the fibonacci method is invoked.") -``` - -### F. Add instrumentation libraries: logs [#library-logs] - -In `app.py`, add the following after the `Metrics` section. This will import the logging module and set the `basicConfig` logging level to `DEBUG`: - - ```python - ######## - # Logs # - OpenTelemetry Logs are still in the experimental state, so function names may change in the future - ######## - import logging - logging.basicConfig(level=logging.DEBUG) - - from opentelemetry import _logs - from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler - from opentelemetry.sdk._logs.export import BatchLogRecordProcessor - from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter - - # Initialize logging and an exporter that can send data to an OTLP endpoint by attaching OTLP handler to root logger - # SELECT * FROM Log WHERE instrumentation.provider='opentelemetry' - _logs.set_logger_provider(LoggerProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES))) - logging.getLogger().addHandler(LoggingHandler(logger_provider=_logs.get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter())))) - ``` - - -### G. Add Flask instrumentation [#flask-instrum] - -In `app.py` add the highlighted lines below, after the `Logs` section. This helps with linking spans for distributed tracing and logs-in-context: - -```python lineHighlight=1-3,5,8 - -##################### -# Flask Application # -##################### -from flask import Flask, jsonify, request -from opentelemetry.instrumentation.flask import FlaskInstrumentor - -app = Flask(__name__) -FlaskInstrumentor().instrument_app(app) -``` - -### H. Custom trace instrumentation: Create a custom span [#cust-span] - -You can create whatever spans you want, and it is up to you to annotate your spans with attributes on specific operations. The attributes you set will provide additional context about the specific operation you are tracking, such as results or operation properties. - -In `app.py`, insert the highlighted lines below to start a new span called `/fibonacci` that does the following: - * Captures data about the execution of this method - * Sets an attribute that stores the value of n from the user's request - - ```python lineHighlight=3,8,16 - - @app.route("/fibonacci") - - @trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") - def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - return jsonify(n=x, result=array[x]) - - except AssertionError: - return jsonify({"message": error_message}) - - app.run(host='0.0.0.0', port=8080) - ``` - -### I. Custom trace instrumentation: Record an exception [#span-exception] - -You may want to record exceptions as they happen. We recommend you do this in conjunction with setting the span status. - -1. To set the span's status code to `ERROR` when an exception occurs, we also need to import the `Status` and `StatusCode` modules from the `opentelemetry.trace.status package`. Add the highlighted line below to the `Traces` section with the other traces libraries: - -```python lineHighlight=8 -########## -# Traces # -########## -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter -from opentelemetry.trace.status import Status, StatusCode -``` - -2. Next, insert the highlighted lines below to record the exception, which will show up as a span event in New Relic, and set the span status to `ERROR`: - -```python lineHighlight=19,20 -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### J. Custom metric instrumentation: Add a custom metric counter [#cust-metrics] - -Metrics are a telemetry data type that are really helpful because they combine individual measurements into aggregations, and produce data that is constant as a function of system load. You can use this data in conjunction with spans to help spot trends and provide application runtime telemetry. You can also annotate any metric with attributes to help describe what subdivision of the measurements the metric represents. - -The OpenTelemetry metrics API defines a number of instruments, which record measurements that are aggregated by the metrics SDK and exported out of process. There are two types of instruments: - -* Synchronous: These instruments record measurements as they occur -* Asynchronous: These instruments register a callback, which is invoked only once per collection and do not have associated context - -1. In `app.py`, add the highlighted line below in the `Metrics` section to create a counter: - -```python lineHighlight=13 -########### -# Metrics # -########### -from opentelemetry import metrics -from opentelemetry.sdk.metrics import MeterProvider -from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter - -# Initialize metering and an exporter that can send data to an OTLP endpoint -# SELECT count(`http.server.active_requests`) FROM Metric FACET `service.name` TIMESERIES -metrics.set_meter_provider(MeterProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES), metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())])) -metrics.get_meter_provider() -fib_counter = metrics.get_meter("opentelemetry.instrumentation.custom").create_counter("fibonacci.invocations", unit="1", description="Measures the number of times the fibonacci method is invoked.") -``` - -2. Next, add the highlighted lines below to use the counter you just created to measure: - * The number of times this function runs successfully - * The number times it fails to run - -Note that the counter will reset to 0 every time you restart your app. - -```python lineHighlight=16,22 -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - fib_counter.add(1, {"fibonacci.valid.n": "true"}) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - fib_counter.add(1, {"fibonacci.valid.n": "false"}) - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### K. Custom log instrumentation [#cust-log] - -The status of the logs signal in OpenTelemetry Python is currently [experimental](https://github.com/open-telemetry/opentelemetry-python#project-status). - -In `app.py`, add the highlighted lines below to: -* Record an `INFO` level log for the input and output values -* Record an `ERROR` level log when the input value is outside of the valid range - -```python lineHighlight=17,24 - -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - fib_counter.add(1, {"fibonacci.valid.n": "true"}) - logging.info("Compute fibonacci(" + str(x) + ") = " + str(array[x])) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - fib_counter.add(1, {"fibonacci.valid.n": "false"}) - logging.error("Failed to compute fibonacci(" + str(x) + ")") - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### L. Exercise the app to generate some traffic [#exercise-app] - -You're ready to send some data to New Relic! - -1. In the terminal, confirm that you're in the `getting-started-guides/python/Uninstrumented` directory, then run the application: - * MacOS: - ``` - python3 app.py - ``` - * PowerShell: - ``` - python app.py - ``` - -2. Generate traffic to the application by opening a new terminal tab in the `getting-started-guides/python/Uninstrumented` directory and running the load generator: - * MacOS: - ``` - ./load-generator.sh - ``` - * PowerShell: - ``` - .\load-generator.ps1 - ``` - - - Alternatively, you can reach the endpoint in the browser at this URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Replace `INSERT_A_VALUE` with a value from 1 to 90. To generate an error, insert an integer outside the valid range. - - -3. Now that you've sent some data to New Relic, see our [instructions on viewing the data in the UI](#view-data). - -## View your demo data in New Relic [#view-data] - -No matter which tutorial you completed, you can follow the tips below for finding your data in the New Relic UI. - -Note that if you followed [Tutorial 2: Monitor the demo app with the OpenTelemetry Python agent:](#python-agent), you will not see the custom data (such as the custom metrics and logs), as you need to manually add custom instrumentation to capture more granular data. - -1. Go to **[one.newrelic.com](https://one.newrelic.com/all-capabilities) > APM & services**. -2. Click your new entity (service) called `getting-started-python` (or whatever name you provided). -3. Check out the details in the sections for each data type. - - - If you are using Microsoft Windows and do not see data in your New Relic account, check that you have allowed traffic through the firewall. - - -### Traces [#traces] - -Once you've reached the `getting-started-python` entity in New Relic: - -1. In the left pane's **Monitor** section, click **Distributed tracing**, and then click the `/fibonacci` trace group. - Screenshot showing how to find your trace group -2. From there, find a trace with an error and click to open it: - Screenshot showing an error in distributed tracing -3. Once you have the trace open, click `Show in-process spans`, and then click on the resulting span, which will open up a details panel to the right. To see the exception you recorded when a user input is invalid, click on `View span events`: - Screenshot of in-process spans - -If you completed the manual instrumentation tutorial, here's how the exception you recorded as a span will look in New Relic: - -Screenshot showing an exception as a span event - -To view additional details that you set, such as the span attribute, span name, and status code, click on the **Attributes** tab. This pane is also where you can view additional metadata that is automatically collected by the instrumentation libraries you used in this guide, as well as metadata that is attached by New Relic: - -Screenshot of the attributes tab - -For more details about viewing your data, see [OpenTelemetry in the New Relic UI](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page) - -### Metrics [#metrics] - -Once you've reached the `getting-started-python` entity in New Relic, you can see a list of all collected metrics, such as your custom counter attributes. - -#### Metrics explorer [#metrics-explorer] - -This is a tool that allows you to see a list of your metrics. - -1. In the left pane, select **Data > Metrics explorer**, and then select `fibonacci.invocations`. - - Screenshot showing metrics explorer -2. Under **Dimensions**, view the attributes you collected along with your custom metric, and then click on **fibonacci.valid.n**. - - Screenshot showing the total number of invocations of fibonacci function - -Learn more in our documentation about the [metrics explorer view](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-metrics-explorer-page). - -### Logs [#logs] - -Here is where to access your logs: - -Screenshot showing the main logs page - -You will also see logs in your terminal: - -Screenshot showing logs in a terminal - -Back in your logs view, select a log, and you will see a pane open up with the log message and additional attributes that were collected, such as the associated span and trace ids, as well as metadata injected by New Relic: - -Screenshot showing log details with trace - -You can navigate to the correlated distributed trace by clicking this little blue icon: - -Screenshot showing how to find correlated trace - -This will open a pane that displays the correlated trace, where you can view more details about the trace. For more about this page, see [OpenTelemetry in the UI: Distributed tracing page](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page/) and [Understand and use the distributed tracing UI](/docs/distributed-tracing/ui-data/understand-use-distributed-tracing-ui/): - -Screenshot showing the trace waterfall from the logs section - -You can also find the correlated log from the distributed traces view. When you select a trace that has a corresponding log, you will see that indicated as a tab, and you can view the log directly from the trace without having to switch views: - -Screenshot showing how to see log details from a trace span - -Learn more about the logs view [here](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-logs-page). - -## Reference: Environment variables [#ref-env-vars] - -This is a list of the environment variables you should export if you're doing tutorial 2 or 3. After you finish exporting the variables, return to the tutorials using the links that follow the variable list: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- OTEL_EXPORTER_OTLP_HEADERS=api-key=YOUR_LICENSE_KEY - - * Headers: This determines which New Relic account your data will be sent to. Replace `YOUR_LICENSE_KEY` with your . -
- OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:4317 (For the US) - - * This is the endpoint your application telemetry will be exported to. Export data to New Relic's OTLP endpoint. If you're in the EU, use this endpoint: OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.eu01.nr-data.net:4317 -
- OTEL_SERVICE_NAME=getting-started-python - - * This is the name that associates your application telemetry with an entity in New Relic. In this tutorial we're calling it `getting-started-python`, but you could call it anything you want. -
- OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_OWN_ID_HERE - - * Replace `INSERT_YOUR_OWN_ID_HERE` with a unique instance id. For example, you could use `1234`. For more details, see OpenTelemetry's [Resource Semantic Conventions](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service). -
- OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT=4095 - - * Setting a limit on the maximum attribute value length will prevent span data from getting dropped if it exceeds the [New Relic limit](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-attributes/). -
- OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=DELTA - - * New Relic supports metrics in delta temporality instead of the default of cumulative. -
- OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=EXPONENTIAL_BUCKET_HISTOGRAM - - * (Recommended) Histogram aggregation: Use exponential histogram instead of default explicit bucket histogram for better data compression. -
- OTEL_LOGS_EXPORTER=otlp - - * Enable log export over OTLP. Log export is disabled by default. -
- OTEL_EXPORTER_OTLP_COMPRESSION=gzip - - * (Recommended) Setting gzip compression allows you to maximize the amount of data you can send per request. Our maximum allowed payload size is 1MB (10^6 bytes). Gzip compression has good performance and lowers data egress. -
- OTEL_EXPERIMENTAL_EXPORTER_OTLP_RETRY_ENABLED=true - - * (Recommended) Enable experimental export retry to help cope with the unreliability of the internet. -
- OTEL_EXPERIMENTAL_RESOURCE_DISABLED_KEYS=process.command_line - - * (Recommended) This disables the `process.command_line` resource attribute which often exceeds the New Relic maximum attribute length limit and may contain sensitive information. -
-
-
- -After you've exported the environment variables listed in the collapser above, return to the tutorial and complete the setup: -* [Tutorial 2: Monitor the demo app with the OpenTelemetry Python agent](#python-agent) -* [Tutorial 3: Set up the demo app manually](#manual-instrum) - -## What's next? [#what-next] - -Now that you've experimented with OpenTelemetry instrumentation and SDK configuration, you can apply what you've learned to set up your own app or service with OpenTelemetry and New Relic. For more, see [Set up your own app or service with OpenTelemetry](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-set-up-your-app). \ No newline at end of file diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-java.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-java.mdx index 5127d7bbff0..289f15112f6 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-java.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-java.mdx @@ -112,10 +112,11 @@ This is a great option if you want us to do the instrumentation so you can quick ``` 2. Set these two environment variables to send data to your New Relic account: * Make sure to use your . - * If your New Relic data center region is EU and not US, set the endpoint to: `https://otlp.eu01.nr-data.net:4317` + * If your New Relic data center region is EU and not US, set the endpoint to: `https://otlp.eu01.nr-data.net` * `OTEL_EXPORTER_OTLP_HEADERS=api-key=INSERT_YOUR_NEW_RELIC_LICENSE_KEY` - * `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:4317` + * `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:` + * `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` 3. Set the first environment variable below to name the service, then set the second for the service instance ID, which activates certain platform features. Finally, enable logs since logging is off by default: * `OTEL_SERVICE_NAME=getting-started-java` * `OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_ID_HERE` @@ -1023,12 +1024,19 @@ This is a list of the environment variables you should export if you're doing tu - `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:4317` (For the US) - `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.eu01.nr-data.net:4317` (For the EU) + `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:` (For the US) + `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.eu01.nr-data.net:` (For the EU) * This is the endpoint your application telemetry will be exported to. Export data to New Relic's OTLP endpoint. + + + `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` + + * The specifies that OTLP `http/protobuf` should be used, which is preferred by New Relic. + + `OTEL_SERVICE_NAME=getting-started-java` diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-python.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-python.mdx index 69c3329f67d..85ace4f1dca 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-python.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-python.mdx @@ -91,12 +91,12 @@ This is a great option if you want us to do the instrumentation so you can quick ``` 2. Set these environment variables to send data to your New Relic account: * Make sure to use your . - * If your New Relic data center region is EU and not US, set the endpoint to: `https://otlp.eu01.nr-data.net:4317` + * If your New Relic data center region is EU and not US, set the endpoint to: `https://otlp.eu01.nr-data.net` * OTEL_EXPORTER_OTLP_HEADERS=api-key=INSERT_YOUR_NEW_RELIC_LICENSE_KEY - * OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:4317 -3. Set this environment variable to name the service; this is how you will identify your service in your New Relic account: - * OTEL_SERVICE_NAME=getting-started-python + * OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net +3. Set this environment variable to name the service; this is how you will identify your service in your New Relic account: + * OTEL_SERVICE_NAME=getting-started-python 3. In the same `getting-started-guides/python/Instrumented/` directory, create and activate a virtual environment, install the required libraries, and run the app: * macOS: ``` @@ -105,7 +105,7 @@ This is a great option if you want us to do the instrumentation so you can quick pip install -r requirements.txt python3 app.py ``` - + * PowerShell: ``` python -m venv venv @@ -133,9 +133,9 @@ This is a great option if you want us to do the instrumentation so you can quick ## Tutorial 2: Monitor the demo app with the OpenTelemetry Python agent [#python-agent] -Here's a different tutorial that also uses the same demo app, but in this case, you'll use the OpenTelemetry Python agent to automatically monitor the demo app. You don't need to modify the Python source code. By using the agent, you can quickly start exporting sample data to New Relic. +Here's a different tutorial that also uses the same demo app, but in this case, you'll use the OpenTelemetry Python agent to automatically monitor the demo app. You don't need to modify the Python source code. By using the agent, you can quickly start exporting sample data to New Relic. -Note, however, that you will need to add custom instrumentation to capture deeper levels of information about the app, such as logs and custom metrics. +Note, however, that you will need to add custom instrumentation to capture deeper levels of information about the app, such as logs and custom metrics. The auto-instrumentation agent is a series PyPI package that dynamically injects bytecode to capture telemetry from popular libraries and frameworks. You can also use it to capture data such as inbound requests, outbound HTTP calls, and database calls. It can be attached to any Python 3 application. @@ -150,7 +150,7 @@ To monitor our demo app with the OpenTelemetry Python agent: git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented ``` -2. Go to our [environment variables reference section](#ref-env-vars) below to see which variables you need to export and then return to these steps. +2. Go to our [environment variables reference section](#ref-env-vars) below to see which variables you need to export and then return to these steps. 3. Then, in the same `getting-started-guides/python/Uninstrumented/` directory, create and activate a virtual environment: * macOS: @@ -158,7 +158,7 @@ To monitor our demo app with the OpenTelemetry Python agent: python3 -m venv venv source venv/bin/activate ``` - + * PowerShell: ``` python -m venv venv @@ -240,7 +240,7 @@ To add the required libraries: python3 -m venv venv source venv/bin/activate ``` - + * PowerShell: ``` python -m venv venv @@ -259,7 +259,7 @@ To add the required libraries: ### C. Configure the SDK [#config-sdk] -1. In `app.py`, add the highlighted lines below to the **top of the file**. Change the value for the custom attribute `environment` as needed. +1. In `app.py`, add the highlighted lines below to the **top of the file**. Change the value for the custom attribute `environment` as needed. ```python lineHighlight=1-10 ########################## @@ -278,7 +278,7 @@ from flask import Flask, jsonify, request app = Flask(__name__) ``` -2. Go to our [environment variables reference section](#ref-env-vars) below to see which variables you need to export, and then move forward to the next step to add instrumentation libraries. +2. Go to our [environment variables reference section](#ref-env-vars) below to see which variables you need to export, and then move forward to the next step to add instrumentation libraries. ### D. Add instrumentation libraries: traces [#library-traces] @@ -291,7 +291,7 @@ In `app.py`, insert the following after the `OpenTelemetry Settings` you added: from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.trace.status import Status, StatusCode # Initialize tracing and an exporter that can send data to an OTLP endpoint @@ -311,7 +311,7 @@ In `app.py` add the following after the `Traces` section you added in Step D: from opentelemetry import metrics from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter # Initialize metering and an exporter that can send data to an OTLP endpoint # SELECT count(`http.server.active_requests`) FROM Metric FACET `service.name` TIMESERIES @@ -324,7 +324,7 @@ fib_counter = metrics.get_meter("opentelemetry.instrumentation.custom").create_c In `app.py`, add the following after the `Metrics` section. This will import the logging module and set the `basicConfig` logging level to `DEBUG`: -```python +```python ######## # Logs # - OpenTelemetry Logs are still in the experimental state, so function names may change in the future ######## @@ -334,7 +334,7 @@ logging.basicConfig(level=logging.DEBUG) from opentelemetry import _logs from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler from opentelemetry.sdk._logs.export import BatchLogRecordProcessor -from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter +from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter # Initialize logging and an exporter that can send data to an OTLP endpoint by attaching OTLP handler to root logger # SELECT * FROM Log WHERE instrumentation.provider='opentelemetry' @@ -376,7 +376,7 @@ In `app.py`, insert the highlighted lines below to start a new span called `/fib x = int(args.get("n")) error_message = "n must be 1 <= n <= 90." trace.get_current_span().set_attribute("fibonacci.n", x) - + try: assert 1 <= x <= 90 array = [0, 1] @@ -388,15 +388,15 @@ In `app.py`, insert the highlighted lines below to start a new span called `/fib except AssertionError: return jsonify({"message": error_message}) - + app.run(host='0.0.0.0', port=8080) ``` ### I. Custom trace instrumentation: Record an exception [#span-exception] -You may want to record exceptions as they happen. We recommend you do this in conjunction with setting the span status. +You may want to record exceptions as they happen. We recommend you do this in conjunction with setting the span status. -1. To set the span's status code to `ERROR` when an exception occurs, we also need to import the `Status` and `StatusCode` modules from the `opentelemetry.trace.status package`. Add the highlighted line below to the `Traces` section with the other traces libraries: +1. To set the span's status code to `ERROR` when an exception occurs, we also need to import the `Status` and `StatusCode` modules from the `opentelemetry.trace.status package`. Add the highlighted line below to the `Traces` section with the other traces libraries: ```python lineHighlight=8 ########## @@ -405,7 +405,7 @@ You may want to record exceptions as they happen. We recommend you do this in co from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.trace.status import Status, StatusCode ``` @@ -419,7 +419,7 @@ def fibonacci(): x = int(args.get("n")) error_message = "n must be 1 <= n <= 90." trace.get_current_span().set_attribute("fibonacci.n", x) - + try: assert 1 <= x <= 90 array = [0, 1] @@ -433,7 +433,7 @@ def fibonacci(): trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) return jsonify({"message": error_message}) - + app.run(host='0.0.0.0', port=8080) ``` @@ -455,7 +455,7 @@ The OpenTelemetry metrics API defines a number of instruments, which record meas from opentelemetry import metrics from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter # Initialize metering and an exporter that can send data to an OTLP endpoint # SELECT count(`http.server.active_requests`) FROM Metric FACET `service.name` TIMESERIES @@ -468,7 +468,7 @@ fib_counter = metrics.get_meter("opentelemetry.instrumentation.custom").create_c * The number of times this function runs successfully * The number times it fails to run -Note that the counter will reset to 0 every time you restart your app. +Note that the counter will reset to 0 every time you restart your app. ```python lineHighlight=16,22 @app.route("/fibonacci") @@ -478,7 +478,7 @@ def fibonacci(): x = int(args.get("n")) error_message = "n must be 1 <= n <= 90." trace.get_current_span().set_attribute("fibonacci.n", x) - + try: assert 1 <= x <= 90 array = [0, 1] @@ -494,7 +494,7 @@ def fibonacci(): trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) fib_counter.add(1, {"fibonacci.valid.n": "false"}) return jsonify({"message": error_message}) - + app.run(host='0.0.0.0', port=8080) ``` @@ -503,8 +503,8 @@ app.run(host='0.0.0.0', port=8080) The status of the logs signal in OpenTelemetry Python is currently [experimental](https://github.com/open-telemetry/opentelemetry-python#project-status). In `app.py`, add the highlighted lines below to: -* Record an `INFO` level log for the input and output values -* Record an `ERROR` level log when the input value is outside of the valid range +* Record an `INFO` level log for the input and output values +* Record an `ERROR` level log when the input value is outside of the valid range ```python lineHighlight=17,24 @@ -515,7 +515,7 @@ def fibonacci(): x = int(args.get("n")) error_message = "n must be 1 <= n <= 90." trace.get_current_span().set_attribute("fibonacci.n", x) - + try: assert 1 <= x <= 90 array = [0, 1] @@ -533,13 +533,13 @@ def fibonacci(): fib_counter.add(1, {"fibonacci.valid.n": "false"}) logging.error("Failed to compute fibonacci(" + str(x) + ")") return jsonify({"message": error_message}) - + app.run(host='0.0.0.0', port=8080) ``` ### L. Exercise the app to generate some traffic [#exercise-app] -You're ready to send some data to New Relic! +You're ready to send some data to New Relic! 1. In the terminal, confirm that you're in the `getting-started-guides/python/Uninstrumented` directory, then run the application: * MacOS: @@ -569,16 +569,16 @@ You're ready to send some data to New Relic! ## View your demo data in New Relic [#view-data] -No matter which tutorial you completed, you can follow the tips below for finding your data in the New Relic UI. +No matter which tutorial you completed, you can follow the tips below for finding your data in the New Relic UI. -Note that if you followed [Tutorial 2: Monitor the demo app with the OpenTelemetry Python agent:](#python-agent), you will not see the custom data (such as the custom metrics and logs), as you need to manually add custom instrumentation to capture more granular data. +Note that if you followed [Tutorial 2: Monitor the demo app with the OpenTelemetry Python agent:](#python-agent), you will not see the custom data (such as the custom metrics and logs), as you need to manually add custom instrumentation to capture more granular data. 1. Go to **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services**. 2. Click your new entity (service) called `getting-started-python` (or whatever name you provided). 3. Check out the details in the sections for each data type. - If you are using Microsoft Windows and do not see data in your New Relic account, check that you have allowed traffic through the firewall. + If you are using Microsoft Windows and do not see data in your New Relic account, check that you have allowed traffic through the firewall. ### Traces [#traces] @@ -720,9 +720,9 @@ This is a list of the environment variables you should export if you're doing tu - OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:4317 (For the US) + OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net (For the US) - * This is the endpoint your application telemetry will be exported to. Export data to New Relic's OTLP endpoint. If you're in the EU, use this endpoint: OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.eu01.nr-data.net:4317 + * This is the endpoint your application telemetry will be exported to. Export data to New Relic's OTLP endpoint. If you're in the EU, use this endpoint: OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.eu01.nr-data.net From 903b3a8a5b5abbde14a0162da41982d1f9544c31 Mon Sep 17 00:00:00 2001 From: jack-berg <34418638+jack-berg@users.noreply.github.com> Date: Thu, 18 Jan 2024 15:15:13 -0600 Subject: [PATCH 2/4] Apply suggestions from code review Co-authored-by: Kayla Reopelle (she/her) <87386821+kaylareopelle@users.noreply.github.com> --- .../get-started/opentelemetry-tutorial-java.mdx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-java.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-java.mdx index c523a2acdb2..70a563d9754 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-java.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-java.mdx @@ -115,7 +115,7 @@ This is a great option if you want us to do the instrumentation so you can quick * If your New Relic data center region is EU and not US, set the endpoint to: `https://otlp.eu01.nr-data.net` * `OTEL_EXPORTER_OTLP_HEADERS=api-key=INSERT_YOUR_NEW_RELIC_LICENSE_KEY` - * `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:` + * `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net` * `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` 3. Set the first environment variable below to name the service, then set the second for the service instance ID, which activates certain platform features. Finally, enable logs since logging is off by default: * `OTEL_SERVICE_NAME=getting-started-java` @@ -1024,8 +1024,8 @@ This is a list of the environment variables you should export if you're doing tu - `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:` (For the US) - `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.eu01.nr-data.net:` (For the EU) + `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net` (For the US) + `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.eu01.nr-data.net` (For the EU) * This is the endpoint your application telemetry will be exported to. Export data to New Relic's OTLP endpoint. From 50770de500e5238830066e234c6951701a9ba629 Mon Sep 17 00:00:00 2001 From: Rob Siebens Date: Thu, 18 Jan 2024 16:26:58 -0800 Subject: [PATCH 3/4] fix(OTel): Run i18n-utility to remove orphans --- ...onfigure-android-gradle-android-studio.mdx | 142 --- ...all-android-apps-gradle-android-studio.mdx | 163 ---- .../get-started/opentelemetry-tutorial-go.mdx | 863 ------------------ ...onfigure-android-gradle-android-studio.mdx | 142 --- ...all-android-apps-gradle-android-studio.mdx | 163 ---- .../get-started/opentelemetry-tutorial-go.mdx | 863 ------------------ 6 files changed, 2336 deletions(-) delete mode 100644 src/i18n/content/jp/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-android-gradle-android-studio.mdx delete mode 100644 src/i18n/content/jp/docs/mobile-monitoring/new-relic-mobile-android/install-configure/install-android-apps-gradle-android-studio.mdx delete mode 100644 src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx delete mode 100644 src/i18n/content/kr/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-android-gradle-android-studio.mdx delete mode 100644 src/i18n/content/kr/docs/mobile-monitoring/new-relic-mobile-android/install-configure/install-android-apps-gradle-android-studio.mdx delete mode 100644 src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx diff --git a/src/i18n/content/jp/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-android-gradle-android-studio.mdx b/src/i18n/content/jp/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-android-gradle-android-studio.mdx deleted file mode 100644 index a6429e6dd49..00000000000 --- a/src/i18n/content/jp/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-android-gradle-android-studio.mdx +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: GradleおよびAndroid Studioを使用してAndroidアプリを設定する -tags: - - Mobile monitoring - - New Relic Mobile Android - - Install configure -metaDescription: null -freshnessValidatedDate: '2023-07-27T00:00:00.000Z' -translationType: human ---- - -[Androidエージェントをインストール](/docs/mobile-monitoring/new-relic-mobile-android/get-started/introduction-new-relic-mobile-android/#installation)すると、モバイルアプリを設定することでパフォーマンスや安定性、ユーザーエンゲージメントを高めることができます。GradleとAndroid Studioを使用している場合は、以下の手順に従ってください。 - -## GradleおよびAndroid Studioを使用して設定 [#configuration] - -GradleとAndroid StudioでAndroidアプリを設定するこれらの手順は、Androidのガイド付き[UIインストール](https://onenr.io/02R5GVpaxQb)の「DSLコードを追加」手順にも表示されます。 - -1. プラグインが適用される前に、プロジェクトの最上位の`build.gradle`ファイルで次のコードをマージまたは追加します。 - - - - プロジェクトレベルの設定は、プロジェクト内のすべてのアプリのエージェント設定に使用されます。これには、プロジェクトトークンの設定、機能の有効化または無効化、アラートの閾値設定が含まれます。この例では、AGENT_VERSIONはエージェントのバージョン番号を表しています。[エージェントリリースノート](/docs/release-notes/mobile-release-notes/android-release-notes)を参照し、最新版を使用してください。 - - ``` - buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath "com.newrelic.agent.android:agent-gradle-plugin:AGENT_VERSION" - } - } - ``` - - - - 特定のアプリの設定を行う場合は、アプリレベルの設定を使用します。この例では、AGENT_VERSIONはエージェントのバージョン番号を表しています。[エージェントリリースノート](/docs/release-notes/mobile-release-notes/android-release-notes)を参照し、最新版を使用してください。 - - ``` - repositories { - mavenCentral() - } - - apply plugin: 'android' - apply plugin: 'newrelic' - - dependencies { - implementation 'com.newrelic.agent.android:android-agent:AGENT_VERSION' - } - ``` - - - -2. **(オプション)**ProGuardまたはDexGuardの場合: - - a. プロジェクトのルートディレクトリ(`/projectname/app`)に、以下の行を含む`newrelic.properties`ファイルを追加します。 - - ``` - com.newrelic.application_token=GENERATED_TOKEN - ``` - - b. [Androidアプリ用のProGuardまたはDexGuardの設定](/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-proguard-or-dexguard-android-apps)手順を完了します。次に、このページに戻り、次の手順に進みます。 - - -3. アプリケーションのアクセス権限を設定します。`AndroidManifest.xml`ファイルに以下の行を追加して、Androidアプリが`INTERNET`および`ACCESS_NETWORK_STATE`権限を要求するようにします。 - - ``` - - - ``` - -4. Androidエージェントを起動します。**Default Activity**(**Manifest**に定義されているもの)に`NewRelic`クラスをインポートします。 - - ``` - import com.newrelic.agent.android.NewRelic; - ``` - - - 想定外の動作や不安定な動作が生じる可能性があるため、他のクラスでのモバイルモニタリングエージェントの起動はサポートされていません。 - - -5. モバイルモニタリングを初期化します。`onCreate()`メソッドに、次のコールを追加します。 - - ``` - NewRelic.withApplicationToken("GENERATED_TOKEN").start(this.getApplication()); - ``` - -6. **(オプション)**[ログ記録レベル](/docs/mobile-monitoring/new-relic-mobile-android/api-guides/android-agent-configuration-feature-flags#logging)を変更します。 - -7. アプリケーションを構築して実行します。プロジェクトをクリーンにし、エミュレーターまたはデバイスでアプリケーションを実行しトラフィックを発生させます。 - -8. 数分すると、[**概要**ページ](/docs/mobile-monitoring/mobile-monitoring-ui/mobile-app-pages/mobile-apps-overview-page)からAndroidアプリケーションのデータを表示します。**[one.newrelic.com](https://one.newrelic.com/all-capabilities) > Mobile >(アプリを選択)**の順に移動します。 - -Androidのインストレーションに問題がある場合や、モバイルモニタリングUIにデータが表示されない場合は、[トラブルシューティング手順](/docs/mobile-monitoring/new-relic-mobile-android/troubleshoot/no-data-appears-android)に従ってください。 - - - -AndroidアプリのMultidexサポートを有効にして、64K参照制限を回避する方法をお読みください。 - -## Multidexサポートを有効にする [#4x-multidex] - -Android 5.0(APIレベル21)より前のAndroidバージョン用のNew Relicモバイルモニタリングでは、アプリコードの実行にDalvikランタイムを使用します。デフォルトで、DalvikはアプリをAPK当たり単一の`classes.dex`バイトコードファイルに制限します。この制限を回避するには、[Multidexサポートを有効化](https://developer.android.com/studio/build/multidex.html)**しなければなりません**。こうすることで、アプリのプライマリDEXファイルとなり、追加のDEXファイルとそれらファイル内のコードへのアクセスを管理する[Multidexサポートライブラリ](https://developer.android.com/tools/support-library/features.html#multidex)を使えるようになります。 - -Multidexアプリケーション用に各DEXファイルを構築する際、ビルドツールはアプリケーションが正常に起動できるよう、プライマリDEXファイルにどのクラスが必要か決めるため複雑な意思決定を行います。起動中に必要となるクラスがプライマリDEXファイルに用意されてない場合、アプリケーションは`java.lang.NoClassDefFoundError`エラーでクラッシュします。 - -`java.lang.NoClassDefFoundError`エラーが表示された場合は、プライマリDEXファイルで[必要に応じてこれらの追加クラスを手動で指定する](https://developer.android.com/studio/build/multidex.html#keep)必要があります。 - -1. プロジェクトの`/app`フォルダー内に`proguard.multidex.config`ファイルを作成します。パッケージ名が反映するように、`mypackage`を更新します。 - - ``` - #################### - # keep class names # - #################### - - #Keep New Relic in the main dex - -keep class com.newrelic.** { *; } - -keep class com.mypackage.activities.** { *; } - ``` - -2. アプリレベルの`build.gradle`ファイルに、以下のコードをマージします。 - - ``` - android { - defaultConfig{ - … - multiDexKeepProguard file("proguard.multidex.config") - } - } - ``` - -詳細については、プライマリDEXファイルに必要なクラス宣言に関する、[Android開発者用ドキュメント](https://developer.android.com/studio/build/multidex.html#keep)を参照してください。 - -## New Relic Gradleプラグインの設定 [#gradle_plugin_config] - -Gradle構築の間のAndroidエージェントプラグインの動作の設定方法の詳細は、[New Relic Gradleプラグイン拡張ガイド](/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-new-relic-gradle-plugin)をご覧ください。 \ No newline at end of file diff --git a/src/i18n/content/jp/docs/mobile-monitoring/new-relic-mobile-android/install-configure/install-android-apps-gradle-android-studio.mdx b/src/i18n/content/jp/docs/mobile-monitoring/new-relic-mobile-android/install-configure/install-android-apps-gradle-android-studio.mdx deleted file mode 100644 index 6bbccb6d94f..00000000000 --- a/src/i18n/content/jp/docs/mobile-monitoring/new-relic-mobile-android/install-configure/install-android-apps-gradle-android-studio.mdx +++ /dev/null @@ -1,163 +0,0 @@ ---- -title: Androidエージェント(Gradle/Android Studio)を手動でインストールする -tags: - - Mobile monitoring - - New Relic Mobile Android - - Install configure -metaDescription: 'New accounts: Get Android app monitoring in New Relic at newrelic.com/signup. Existing accounts: Add mobile monitoring to your Android apps from the UI.' -freshnessValidatedDate: never -translationType: human ---- - -Androidモニタリングの設定には、[ガイド付きインストール](https://onenr.io/0kjnEoryzRo)を使用することをお勧めします。ただし、エージェントを手動でインストールする必要がある場合は、以下の手順に従って、GradleとAndroid Studioを使用して、New Relic Androidエージェントをインストールします。 - - - -## Androidアプリをインストールする [#installation] - -モバイルモニタリングのインストレーションプロセスの一環として、New Relicは[アプリケーショントークン](/docs/mobile-apps/viewing-your-application-token)を自動生成します。これはNew Relic でモニタリングする各モバイルアプリを認証するための40文字の16進数の文字列です。 - -1. **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > Mobile**に移動します。 -2. 該当する場合:[**Mobile アプリ**インデックス](/docs/mobile-monitoring/mobile-monitoring-ui/mobile-app-pages/mobile-apps-index)から、**Add a new app**を選択します。 -3. **始めに**ページから、モバイルモニタリング用のプラットフォームとして**Android**を選択します。 -4. モバイルアプリの名前を入力して、**Continue**を選択します。 - -GradleとAndroid Studioを使用した[モバイルモニタリングの設定](#configuration)手順を続けます。 - -または - -* 新しいモバイルアプリの設定プロセスを後で完了する:**[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > Mobile**の順に移動して、モバイルアプリ名の横にある**See instructions**を選択します。 -* 既存のAndroidインストールをアップグレードする:**[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > Mobile >(アプリを選択)> Settings > Installation**の順に移動します。 - -## GradleおよびAndroid Studioを使用して設定 [#configuration] - -GradleとAndroid Studioを使用したAndroidアプリの設定手順は、New Relicの**Get started**ページにも掲載されています。 - -1. **Gradle & Android Studio**タブにあるNew Relicのモバイルモニタリングコードを`build.gradle`ファイルにマージします。 - - - - この例では、AGENT_VERSIONがエージェントのバージョン番号を表しています。[エージェントリリースノート](/docs/release-notes/mobile-release-notes/android-release-notes)を参照し、最新版を使用してください。 - - ``` - buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath "com.newrelic.agent.android:agent-gradle-plugin:AGENT_VERSION" - } - } - ``` - - - - この例では、AGENT_VERSIONがエージェントのバージョン番号を表しています。[エージェントリリースノート](/docs/release-notes/mobile-release-notes/android-release-notes)を参照し、最新版を使用してください。 - - ``` - repositories { - mavenCentral() - } - - apply plugin: 'android' - apply plugin: 'newrelic' - - dependencies { - implementation 'com.newrelic.agent.android:android-agent:AGENT_VERSION' - } - ``` - - - - -2. **(オプション)**ProGuardまたはDexGuardの場合: - - a. プロジェクトのルートディレクトリ(`projectname/app`)に、以下の行を含む`newrelic.properties`ファイルを追加します。 - - ```properties - com.newrelic.application_token=GENERATED_TOKEN - ``` - - b. [Androidアプリ用のProGuardまたはDexGuardの設定](/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-proguard-or-dexguard-android-apps)手順を完了します。次に、このページに戻り、次の手順に進みます。 - - -3. アプリの権限を設定する:`AndroidManifest.xml`ファイルに以下の行を追加することで、Androidアプリが`INTERNET`および`ACCESS_NETWORK_STATE`許可を要求するようにします。 - - ``` - - - ``` - -4. New Relicのモバイルモニタリングエージェントを起動するには:**デフォルトアクティビティ**(**マニフェスト**で定義)で、`NewRelic`クラスをインポートします。 - - ``` - import com.newrelic.agent.android.NewRelic; - ``` - - - 想定外の動作や不安定な動作が生じる可能性があるため、他のクラスでのモバイルモニタリングエージェントの起動はサポートされていません。 - - -5. モバイルモニタリングを初期化するには:`onCreate()`メソッドで、次の呼び出しを追加します。 - - ```java - NewRelic.withApplicationToken("GENERATED_TOKEN").start(this.getApplication()); - ``` - -6. オプション:[ログ記録レベル](/docs/mobile-monitoring/new-relic-mobile-android/api-guides/android-agent-configuration-feature-flags#logging)を変更します。 - -7. アプリケーションをビルドして実行するには:プロジェクトをクリーンにし、エミュレーターまたはデバイスでアプリを実行し、トラフィックを生成します。 - -8. 数分してから、[**概要**ページ](/docs/mobile-monitoring/mobile-monitoring-ui/mobile-app-pages/mobile-apps-overview-page)からAndroidアプリのデータを表示します。**[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > Mobile >(アプリを選択)**の順に移動します。 - -Androidのインストレーションに問題がある場合や、モバイルモニタリングUIにデータが表示されない場合は、[トラブルシューティング手順](/docs/mobile-monitoring/new-relic-mobile-android/troubleshoot/no-data-appears-android)に従ってください。 - - - -## Androidインストレーションの更新 [#upgrading] - -Androidエージェントを最新に保つため、New Relicの[AndroidエージェントSDKをアップグレード](/docs/mobile-monitoring/new-relic-mobile-android/install-configure/upgrading-new-relic-mobiles-android-sdk)する手順に従ってください。モバイルアプリに最新のAndroidバージョンをインストールする:**[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > Mobile >(アプリを選択)> Settings > Installation**の順に移動します。 - -## Android 4.x:Multidexサポート [#4x-multidex] - -Android 5.0(APIレベル21)より前のAndroidバージョン用のNew Relicモバイルモニタリングでは、アプリコードの実行にDalvikランタイムを使用します。デフォルトで、DalvikはアプリをAPK当たり単一の`classes.dex`バイトコードファイルに制限します。この制限を回避するには、[Multidexサポートを有効化](https://developer.android.com/studio/build/multidex.html)**しなければなりません**。こうすることで、アプリのプライマリDEXファイルとなり、追加のDEXファイルとそれらファイル内のコードへのアクセスを管理する[Multidexサポートライブラリ](https://developer.android.com/tools/support-library/features.html#multidex)を使えるようになります。 - -Multidexアプリケーション用に各DEXファイルを構築する際、ビルドツールはアプリケーションが正常に起動できるよう、プライマリDEXファイルにどのクラスが必要か決めるため複雑な意思決定を行います。起動中に必要となるクラスがプライマリDEXファイルに用意されてない場合、アプリケーションは`java.lang.NoClassDefFoundError`エラーでクラッシュします。 - -`java.lang.NoClassDefFoundError`エラーが表示された場合は、プライマリDEXファイルで[必要に応じてこれらの追加クラスを手動で指定する](https://developer.android.com/studio/build/multidex.html#keep)必要があります。 - -1. プロジェクトの`/app`フォルダー内に`proguard.multidex.config`ファイルを作成します。パッケージ名が反映するように、`mypackage`を更新します。 - - ``` - #################### - # keep class names # - #################### - - #Keep New Relic in the main dex - -keep class com.newrelic.** { *; } - -keep class com.mypackage.activities.** { *; } - ``` - -2. アプリケーションレベルの`build.gradle`ファイルに、以下のコードをマージします。 - -``` -android { - defaultConfig{ - … - multiDexKeepProguard file("proguard.multidex.config") - } -} -``` - -詳細については、プライマリDEXファイルに必要なクラス宣言に関する、[Android開発者用ドキュメント](https://developer.android.com/studio/build/multidex.html#keep)を参照してください。 - -## New Relic Gradleプラグインの設定 [#gradle_plugin_config] - -Gradle構築の間のモバイルモニタリングエージェントプラグインの動作の設定方法の詳細は、[New Relic Gradleプラグイン](/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-new-relic-gradle-plugin)拡張ガイドを参照してください。 \ No newline at end of file diff --git a/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx b/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx deleted file mode 100644 index c1ca295822c..00000000000 --- a/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx +++ /dev/null @@ -1,863 +0,0 @@ ---- -title: 'OpenTelemetry チュートリアル: サンプル Go アプリをインストゥルメントする' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: 'To test out OpenTelemetry on a sample Go app instead of your own app, consider these two tutorials.' -freshnessValidatedDate: never -translationType: machine ---- - -import openttelemetryPythonIntroImage from 'images/opentelemetry_screenshot-crop_python-intro.webp' - -import opentelemetryPythonFindTraceGroup from 'images/opentelemetry_screenshot-crop_find-trace-group.webp' - -import opentelemetryPythonDistributedTracingError from 'images/opentelemetry_screenshot-crop_python-distributed-tracing-error.webp' - -import opentelemetryPythonInProcessSpans from 'images/opentelemetry_screenshot-crop_python-in-process-spans.webp' - -import opentelemetryPythonExceptiononSpanEvent from 'images/opentelemetry_screenshot-crop_python-exception-on-span-event.webp' - -import opentelemetryPytyhonAttributesTab from 'images/opentelemetry_screenshot-crop_python-attributes-tab.webp' - -import opentelemetryPythonMetricsExplorerMain from 'images/opentelemetry_screenshot-crop_python-metrics-explorer-main.webp' - -import opentelemetryPythonMetricsExplorerDimensions from 'images/opentelemetry_screenshot-crop_python-metrics-explorer-dimensions.webp' - -import opentelemetryPythonMainLogsPage from 'images/opentelemetry_screenshot-full_python-main-logs-page.webp' - -import opentelemetryPythonLogsinTerminal from 'images/opentelemetry_screenshot-full_python-logs-in-terminal.webp' - -import opentelemetryPythonLogDetailsWithTrace from 'images/opentelemetry_screenshot-full_python-log-details-with-trace.webp' - -import opentelemetryPythonTraceRelatedtoLog from 'images/opentelemetry_screenshot-full_python-trace-related-to-log.webp' - -import opentelemetryPythonTraceWaterfallFromLog from 'images/opentelemetry_screenshot-full_python-trace-waterfall-from-log.webp' - -import opentelemetryPythonLogCapturedinTraceSpan from 'images/opentelemetry_screenshot-full_python-log-captured-in-trace-span.webp' - - - - これらの Go チュートリアルのいずれかを試して、New Relic プラットフォームが OTLP データで何ができるかを確認してください。選択できる 2 つのチュートリアルがあり、それぞれ同じデモ アプリを使用しています。アプリはフィボナッチ数列の n 番目の数値を計算し、トレースとメトリクスを生成します。 - - これらのチュートリアルに取り組むことで、OpenTelemetry と New Relic を使用して独自のアプリをセットアップするのに役立つスキルを習得できます。 - - - - Screenshot showing response time, throughput, and error rate - -
- これらのチュートリアルのいずれかを完了すると、次のようなグラフでスパン メトリックを表示できるようになります。 -
-
-
- -各チュートリアルは同じデモ アプリを使用しますが、OpenTelemetry と New Relic に慣れるのに役立つさまざまなアプローチがあります。興味のあるオプションを試してみてください。 - -* [チュートリアル 1: 事前にインストルメント化されたデモ アプリを実行する:](#pre-instrum)これは、デモ データを New Relic に送信し、UI でどのように表示されるかを確認する最も速い方法です。このチュートリアルでは、デモ アプリには、トレースとメトリクスを生成およびエクスポートするための[ベスト プラクティス](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-overview/)に従って、事前に読み込まれたインストルメンテーションと SDK 構成が含まれています。コードを調べて、関連するセクションを独自のアプリに適用できます。 -* [チュートリアル 2: デモ アプリを手動でセットアップする:](#manual-instrum)このトラックでは、袖をまくり上げて車のエンジンをいじります。これは、レポートされるテレメトリを最大限に制御し、その方法の詳細を確認したい場合にとるべきアプローチです。インストルメンテーションをデモアプリに手動で挿入してテレメトリをキャプチャし、そのデータを New Relic にエクスポートするように SDK を設定します。 - -[OpenTelemetry Go 自動計測器は](https://github.com/open-telemetry/opentelemetry-go-instrumentation)現在開発中であるため、現時点ではチュートリアルには含まれていません。 - - - アプリケーションから OTLP 経由で New Relic にデータをエクスポートするには、2 つの選択肢があります。 - - * アプリから直接 - * OpenTelemetry コレクター経由 - - このガイドでは、最初のオプションについて説明します。コレクター経由でデータをエクスポートする場合は、この[コレクターのドキュメント](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-basic/)で詳細を確認してください。 - - -## 要件 [#requirements] - -開始する前に、次のものが揃っていることを確認してください。 - -* New Relic アカウント:[無料アカウント](https://newrelic.com/signup)をまだお持ちでない場合は、サインアップしてください。 -* [Go 1.16 以降](https://go.dev/doc/install) - -## チュートリアル 1: 事前にインストルメント化されたデモ アプリを実行する [#pre-instrum] - -New Relic にデータを送信し、UI で表示するのがどのようなものかをすばやく確認できるように、インストルメンテーションを行う場合は、これが最適なオプションです。 - -1. ターミナルで次のコマンドを実行してデモ アプリのクローンを作成し、Getting Started Guides の`go/Instrumented`ディレクトリに移動します。 - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/go/Instrumented - ``` - -2. New Relic アカウントにデータを送信するには、次の環境変数を設定します。 - - * 必ず使用してください . - - * New Relic データセンターのリージョンが EU で US ではない場合、エンドポイントを次のように設定します。 `https://otlp.eu01.nr-data.net:4317` - - * OTEL_EXPORTER_OTLP_HEADERS=api-key=INSERT_YOUR_NEW_RELIC_LICENSE_KEY - * OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.nr-data.net:4317](https://otlp.nr-data.net:4317) - -3. この環境変数を設定してサービスに名前を付けます。これは、New Relic アカウントでサービスを識別する方法です。 - - * OTEL_SERVICE_NAME=入門-Python - -4. 同じ `getting-started-guides/python/Instrumented/` ディレクトリで、仮想環境を作成してアクティブ化し、必要なライブラリをインストールして、アプリを実行します。 - - * マックOS: - - ``` - python3 -m venv venv - source venv/bin/activate - pip install -r requirements.txt - python3 app.py - ``` - - * パワーシェル: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - pip install -r requirements.txt - python app.py - ``` - -5. 新しいターミナル タブを開き、 `getting-started-guides/python/Instrumented`ディレクトリに切り替え、次のコマンドを実行してアプリケーションへのトラフィックを生成します: - - * マックOS: - - ``` - ./load-generator.sh - ``` - - * パワーシェル: - - ``` - .\load-generator.ps1 - ``` - - - または、ブラウザの次の URL でエンドポイントにアクセスできます: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` 。`INSERT_A_VALUE`を 1 から 90 の値に置き換えます。エラーを生成するには、有効範囲外の整数を挿入します。 - - -6. **[one.newrelic.com](https://one.newrelic.com/all-capabilities) > APM & services**に移動します。 - -7. `getting-started-python`という新しいエンティティ (サービス) をクリックして、UI を調べます。UI で何を探すべきかについてのその他のヒントについて[は、New Relic でデータを表示する](#view-data)を参照してください。 - -8. UI でデータを確認し終わったら、両方のターミナル セッションで `CONTROL+C` を押してアプリケーションをシャットダウンします。 - -## チュートリアル 2: OpenTelemetry Python エージェントを使用してデモ アプリを監視する [#python-agent] - -これは、同じデモ アプリを使用する別のチュートリアルですが、この場合は、OpenTelemetry Python エージェントを使用して、デモ アプリを自動的に監視します。Python ソース コードを変更する必要はありません。エージェントを使用すると、New Relic へのサンプル データのエクスポートをすぐに開始できます。 - -ただし、ログやカスタム メトリクスなど、アプリに関するより深いレベルの情報を取得するには、カスタム インストルメンテーションを追加する必要があることに注意してください。 - -自動インストルメンテーション エージェントは、バイトコードを動的に挿入して、一般的なライブラリやフレームワークからテレメトリをキャプチャする一連の PyPI パッケージです。これを使用して、受信リクエスト、送信 HTTP 呼び出し、データベース呼び出しなどのデータをキャプチャすることもできます。任意の Python 3 アプリケーションに接続できます。 - - - 追加の構成オプションについては [、OpenTelemetry Python エージェントの公式ドキュメントを](https://opentelemetry.io/docs/instrumentation/python/automatic/) 参照してください。 - - -OpenTelemetry Python エージェントを使用してデモ アプリを監視するには: - -1. これら 2 つのコマンドを実行して、デモ アプリケーション リポジトリをダウンロードし、次のディレクトリに移動します。 - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` - -2. 以下の[環境変数の参照セクション](#ref-env-vars)に移動して、エクスポートする必要がある変数を確認してから、これらの手順に戻ります。 - -3. 次に、同じ `getting-started-guides/python/Uninstrumented/` ディレクトリに仮想環境を作成してアクティブ化します。 - - * マックOS: - - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * パワーシェル: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` - -4. これで、必要なライブラリをインストールする準備が整いました。 - - ``` - pip install flask - pip install opentelemetry-instrumentation-flask - pip install opentelemetry-exporter-otlp - pip install opentelemetry-distro - ``` - -5. `getting-started-guides/python/Uninstrumented/`に進み、アプリでエージェントを起動します。 - - * マックOS: - - ``` - opentelemetry-instrument python3 app.py - ``` - - * パワーシェル: - - ``` - opentelemetry-instrument python app.py - ``` - -6. `getting-started-guides/python/Uninstrumented`ディレクトリで新しいターミナルを開き、ロード ジェネレーターを実行して、アプリケーションへのトラフィックを生成します。 - - * マックOS: - - ``` - ./load-generator.sh - ``` - - * パワーシェル: - - ``` - .\load-generator.ps1 - ``` - - - または、ブラウザの次の URL でエンドポイントにアクセスできます: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` 。`INSERT_A_VALUE`を 1 から 90 の値に置き換えます。エラーを生成するには、有効範囲外の整数を挿入します。 - - -7. New Relic にデータを[送信したので、UI でデータを表示する手順を](#view-data)参照してください。 - -8. UI でデータを確認し終わったら、両方のターミナル セッションで `CONTROL+C` を押してアプリケーションをシャットダウンします。 - -## チュートリアル 3: デモ アプリを手動でセットアップする [#manual-instrum] - -前のセクションは、OpenTelemetry Python エージェントを使用した自動インストルメンテーションを調べるのに役立ちました。収集するテレメトリをより詳細に制御したい場合は、このチュートリアルを試して、カスタム インストルメンテーションを追加する方法を学ぶことができます。次に、推奨されるベスト プラクティスを使用して、OpenTelemetry SDK を設定してデータを New Relic にエクスポートする方法を説明します。 - -この手動セットアップで完了する手順は次のとおりです。 - -* [A. デモ アプリケーションをダウンロードする](#download) -* [B. 必要なライブラリをインストールする](#libraries) -* [C. SDKを構成する](#config-sdk) -* [D. インストルメンテーション ライブラリの追加: トレース](#library-traces) -* [E. インストルメンテーション ライブラリの追加: メトリック](#library-metrics) -* [F. インストルメンテーション ライブラリの追加: ログ](#library-logs) -* [G. Flask インストルメンテーションを追加する](#flask-instrum) -* [H. カスタム トレース インストルメンテーション: カスタム スパンを作成する](#cust-span) -* [I. カスタム トレース インストルメンテーション: 例外を記録する](#span-exception) -* [J. カスタム メトリック インストルメンテーション: カスタム メトリック カウンターを追加する](#cust-metrics) -* [K. カスタム ログ インストルメンテーション](#cust-log) -* [L. アプリを実行してトラフィックを生成する](#exercise-app) - -### A. デモ アプリケーションをダウンロードする [#download] - -以下を実行してデモ アプリをダウンロードします。 - -``` -git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git -``` - -### B. 必要なライブラリをインストールする [#libraries] - -必要なライブラリを追加するには: - -1. このチュートリアルの開始点として、インストルメント化されていないアプリのアプリケーション ディレクトリに移動します。このチュートリアルが終わるまでに、コードは `Instrumented` ディレクトリにあるもののようになっているはずです。 - - ``` - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` - -2. `Uninstrumented` ディレクトリに仮想環境を作成してアクティブ化します。 - - * マックOS: - - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * パワーシェル: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` - -3. 以下をインストールします。 - - ``` - pip install opentelemetry-api - pip install opentelemetry-sdk - pip install flask - pip install opentelemetry-instrumentation-logging - pip install opentelemetry-instrumentation-flask - pip install opentelemetry-exporter-otlp - pip install opentelemetry-distro - ``` - -### C. SDKを構成する [#config-sdk] - -1. `app.py`で、以下の強調表示された行を **ファイルの先頭**に追加します。必要に応じて、カスタム属性 `environment` の値を変更します。 - -```python lineHighlight=1-10 -########################## -# OpenTelemetry Settings # -########################## -from opentelemetry.sdk.resources import Resource -import uuid - -OTEL_RESOURCE_ATTRIBUTES = { - "service.instance.id": str(uuid.uuid1()), - "environment": "local" -} - -from flask import Flask, jsonify, request - -app = Flask(__name__) -``` - -2. 以下の [環境変数リファレンス セクション](#ref-env-vars) に移動して、エクスポートする必要がある変数を確認してから、インストルメンテーション ライブラリを追加する次の手順に進みます。 - -### D. インストルメンテーション ライブラリの追加: トレース [#library-traces] - -`app.py`で、追加した `OpenTelemetry Settings` の後に以下を挿入します。 - -```python -########## -# Traces # -########## -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter -from opentelemetry.trace.status import Status, StatusCode - -# Initialize tracing and an exporter that can send data to an OTLP endpoint -# SELECT * FROM Span WHERE instrumentation.provider='opentelemetry' -trace.set_tracer_provider(TracerProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES))) -trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) -``` - -### E. インストルメンテーション ライブラリの追加: メトリック [#library-metrics] - -`app.py` で、ステップ D で追加した `Traces` セクションの後に次の行を追加します。 - -```python -########### -# Metrics # -########### -from opentelemetry import metrics -from opentelemetry.sdk.metrics import MeterProvider -from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter - -# Initialize metering and an exporter that can send data to an OTLP endpoint -# SELECT count(`http.server.active_requests`) FROM Metric FACET `service.name` TIMESERIES -metrics.set_meter_provider(MeterProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES), metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())])) -metrics.get_meter_provider() -fib_counter = metrics.get_meter("opentelemetry.instrumentation.custom").create_counter("fibonacci.invocations", unit="1", description="Measures the number of times the fibonacci method is invoked.") -``` - -### F. インストルメンテーション ライブラリの追加: ログ [#library-logs] - -`app.py`の `Metrics` セクションの後に以下を追加します。これにより、ログ モジュールがインポートされ、 `basicConfig` ログ レベルが `DEBUG`に設定されます。 - -```python -######## -# Logs # - OpenTelemetry Logs are still in the experimental state, so function names may change in the future -######## -import logging -logging.basicConfig(level=logging.DEBUG) - -from opentelemetry import _logs -from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler -from opentelemetry.sdk._logs.export import BatchLogRecordProcessor -from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter - -# Initialize logging and an exporter that can send data to an OTLP endpoint by attaching OTLP handler to root logger -# SELECT * FROM Log WHERE instrumentation.provider='opentelemetry' -_logs.set_logger_provider(LoggerProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES))) -logging.getLogger().addHandler(LoggingHandler(logger_provider=_logs.get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter())))) -``` - -### G. Flask インストルメンテーションを追加する [#flask-instrum] - -`app.py` の `Logs` セクションの後に、以下の強調表示された行を追加します。これは、分散トレースとログインコンテキストのスパンをリンクするのに役立ちます。 - -```python lineHighlight=1-3,5,8 - -##################### -# Flask Application # -##################### -from flask import Flask, jsonify, request -from opentelemetry.instrumentation.flask import FlaskInstrumentor - -app = Flask(__name__) -FlaskInstrumentor().instrument_app(app) -``` - -### H. カスタム トレース インストルメンテーション: カスタム スパンを作成する [#cust-span] - -必要なスパンを作成できます。特定の操作に関する属性でスパンに注釈を付けるのはあなた次第です。設定した属性は、結果や操作のプロパティなど、追跡している特定の操作に関する追加のコンテキストを提供します。 - -`app.py`に、以下の強調表示された行を挿入して、次の処理を行う `/fibonacci` という新しいスパンを開始します。 - -* このメソッドの実行に関するデータをキャプチャします - -* ユーザーのリクエストから n の値を格納する属性を設定します - - ```python lineHighlight=3,8,16 - - @app.route("/fibonacci") - - @trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") - def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - return jsonify(n=x, result=array[x]) - - except AssertionError: - return jsonify({"message": error_message}) - - app.run(host='0.0.0.0', port=8080) - ``` - -### I. カスタム トレース インストルメンテーション: 例外を記録する [#span-exception] - -例外が発生したときに、例外を記録したい場合があります。スパンステータスの設定と併せてこれを行うことをお勧めします。 - -1. 例外が発生したときにスパンのステータス コードを `ERROR` に設定するには、 `Status` モジュールと `StatusCode` モジュールを `opentelemetry.trace.status package`からインポートする必要もあります。以下の強調表示された行を、他のトレース ライブラリを含む `Traces` セクションに追加します。 - -```python lineHighlight=8 -########## -# Traces # -########## -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter -from opentelemetry.trace.status import Status, StatusCode -``` - -2. 次に、以下の強調表示された行を挿入して例外を記録します。この例外は New Relic でスパン イベントとして表示され、スパンのステータスを `ERROR`に設定します。 - -```python lineHighlight=19,20 -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### J. カスタム メトリック インストルメンテーション: カスタム メトリック カウンターを追加する [#cust-metrics] - -メトリックは、個々の測定値を集計に結合し、システム負荷の関数として一定のデータを生成するため、非常に役立つテレメトリ データ タイプです。このデータをスパンと組み合わせて使用すると、傾向を特定し、アプリケーションのランタイム テレメトリを提供できます。また、メトリクスが表す測定値の下位区分を説明するのに役立つ属性でメトリクスに注釈を付けることもできます。 - -OpenTelemetry メトリクス API は、メトリクス SDK によって集計され、アウト オブ プロセスでエクスポートされる測定値を記録する多数の計測器を定義します。器具には次の 2 種類があります。 - -* 同期: これらの計測器は、発生時に測定値を記録します。 -* 非同期: これらの計測器はコールバックを登録します。これはコレクションごとに 1 回だけ呼び出され、関連付けられたコンテキストはありません。 - -1. `app.py`の `Metrics` セクションに以下の強調表示された行を追加してカウンターを作成します。 - -```python lineHighlight=13 -########### -# Metrics # -########### -from opentelemetry import metrics -from opentelemetry.sdk.metrics import MeterProvider -from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter - -# Initialize metering and an exporter that can send data to an OTLP endpoint -# SELECT count(`http.server.active_requests`) FROM Metric FACET `service.name` TIMESERIES -metrics.set_meter_provider(MeterProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES), metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())])) -metrics.get_meter_provider() -fib_counter = metrics.get_meter("opentelemetry.instrumentation.custom").create_counter("fibonacci.invocations", unit="1", description="Measures the number of times the fibonacci method is invoked.") -``` - -2. 次に、作成したカウンターを使用して測定するために、以下の強調表示された行を追加します。 - -* この関数が正常に実行された回数 -* 実行に失敗した回数 - -アプリを再起動するたびにカウンターが 0 にリセットされることに注意してください。 - -```python lineHighlight=16,22 -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - fib_counter.add(1, {"fibonacci.valid.n": "true"}) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - fib_counter.add(1, {"fibonacci.valid.n": "false"}) - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### K. カスタム ログ インストルメンテーション [#cust-log] - -OpenTelemetry Python のログ信号のステータスは、現在 [実験段階](https://github.com/open-telemetry/opentelemetry-python#project-status)です。 - -`app.py`で、以下の強調表示された行を次の行に追加します。 - -* 入力値と出力値の `INFO` レベルのログを記録します。 -* 入力値が有効範囲外の場合、 `ERROR` レベルのログを記録します。 - -```python lineHighlight=17,24 - -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - fib_counter.add(1, {"fibonacci.valid.n": "true"}) - logging.info("Compute fibonacci(" + str(x) + ") = " + str(array[x])) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - fib_counter.add(1, {"fibonacci.valid.n": "false"}) - logging.error("Failed to compute fibonacci(" + str(x) + ")") - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### L. アプリを実行してトラフィックを生成する [#exercise-app] - -New Relic にデータを送信する準備ができました! - -1. ターミナルで、 `getting-started-guides/python/Uninstrumented` ディレクトリにいることを確認し、アプリケーションを実行します。 - - * マックOS: - - ``` - python3 app.py - ``` - - * パワーシェル: - - ``` - python app.py - ``` - -2. `getting-started-guides/python/Uninstrumented` ディレクトリで新しいターミナル タブを開き、ロード ジェネレーターを実行して、アプリケーションへのトラフィックを生成します。 - - * マックOS: - - ``` - ./load-generator.sh - ``` - - * パワーシェル: - - ``` - .\load-generator.ps1 - ``` - - - または、ブラウザの次の URL でエンドポイントにアクセスできます: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` 。`INSERT_A_VALUE`を 1 から 90 の値に置き換えます。エラーを生成するには、有効範囲外の整数を挿入します。 - - -3. New Relic にデータを[送信したので、UI でデータを表示する手順を](#view-data)参照してください。 - -## New Relic でデモ データを表示する [#view-data] - -どのチュートリアルを完了しても、New Relic UI でデータを見つけるための以下のヒントに従うことができます。 - -[「チュートリアル 2: OpenTelemetry Python エージェントを使用してデモ アプリを監視する:」](#python-agent)に従った場合は、より詳細なデータをキャプチャするにはカスタム インストルメンテーションを手動で追加する必要があるため、カスタム データ (カスタム メトリクスやログなど) が表示されないことに注意してください。 - -1. **[one.newrelic.com](https://one.newrelic.com/all-capabilities) > APM & services**に移動します。 -2. `getting-started-python`という名前の新しいエンティティ (サービス) (または任意の名前) をクリックします。 -3. 各データ型のセクションで詳細を確認してください。 - - - Microsoft Windows を使用していて、New Relic アカウントにデータが表示されない場合は、ファイアウォールを通過するトラフィックを許可しているかどうかを確認してください。 - - -### トレース [#traces] - -New Relic で`getting-started-python`エンティティに到達したら: - -1. 左側のペインの**Monitor** \[モニター]セクションで、 **Distributed tracing** \[分散トレース]をクリックし、 `/fibonacci`トレース グループをクリックします。 - - Screenshot showing how to find your trace group - -2. そこから、エラーのあるトレースを見つけてクリックして開きます。 - - Screenshot showing an error in distributed tracing - -3. トレースを開いたら、 `Show in-process spans`をクリックし、結果のスパンをクリックすると、右側に詳細パネルが開きます。ユーザー入力が無効な場合に記録した例外を確認するには、 `View span events`をクリックします。 - - Screenshot of in-process spans - -手動インストルメンテーション チュートリアルを完了した場合、スパンとして記録した例外が New Relic でどのように表示されるかを以下に示します。 - -Screenshot showing an exception as a span event - -スパン属性、スパン名、ステータス コードなど、設定した追加の詳細を表示するには、\[**属性**] タブをクリックします。このペインでは、このガイドで使用したインストルメンテーション ライブラリによって自動的に収集される追加のメタデータと、New Relic によって添付されたメタデータを表示することもできます。 - -Screenshot of the attributes tab - -データの表示の詳細について[は、New Relic UI の OpenTelemetry を](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page)参照してください。 - -### 指標 [#metrics] - -New Relic の `getting-started-python` エンティティに到達すると、カスタム カウンター属性など、収集されたすべてのメトリクスのリストが表示されます。 - -#### メトリクスエクスプローラー [#metrics-explorer] - -これは、メトリックのリストを表示できるツールです。 - -1. 左側のペインで、\[**データ] > \[メトリクス エクスプローラー]**を選択し、\[ `fibonacci.invocations` ] を選択します。 - - Screenshot showing metrics explorer - -2. \[**ディメンション**] で、収集した属性とカスタム メトリックを表示し、 **fibonacci.valid.n**をクリックします。 - - Screenshot showing the total number of invocations of fibonacci function - -詳しくは、 [メトリクス エクスプローラー ビュー](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-metrics-explorer-page)に関するドキュメントをご覧ください。 - -### ログ [#logs] - -ログにアクセスする場所は次のとおりです。 - -Screenshot showing the main logs page - -ターミナルにもログが表示されます。 - -Screenshot showing logs in a terminal - -ログ ビューに戻り、ログを選択すると、ログ メッセージと、関連するスパンやトレース ID などの収集された追加の属性、および New Relic によって挿入されたメタデータが表示されたペインが開きます。 - -Screenshot showing log details with trace - -この小さな青いアイコンをクリックすると、相関分散トレースに移動できます。 - -Screenshot showing how to find correlated trace - -これにより、相関トレースを表示するペインが開き、トレースに関する詳細を表示できます。このページの詳細について[は、UI の OpenTelemetry: 分散トレース ページ](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page/)および[分散トレース UI の理解と使用](/docs/distributed-tracing/ui-data/understand-use-distributed-tracing-ui/)を参照してください。 - -Screenshot showing the trace waterfall from the logs section - -分散トレース ビューから相関ログを見つけることもできます。対応するログを持つトレースを選択すると、それがタブとして示され、ビューを切り替えることなくトレースから直接ログを表示できます。 - -Screenshot showing how to see log details from a trace span - -ログ ビューの詳細については、 [こちら](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-logs-page)をご覧ください。 - -## 参考:環境変数 [#ref-env-vars] - -これは、チュートリアル 2 または 3 を実行している場合にエクスポートする必要がある環境変数のリストです。変数のエクスポートが完了したら、変数リストに続くリンクを使用してチュートリアルに戻ります。 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- OTEL_EXPORTER_OTLP_HEADERS=api-key=YOUR_LICENSE_KEY - - * ヘッダー: これにより、データが送信される New Relic アカウントが決まります。`YOUR_LICENSE_KEY`をあなたの - - - - . -
- OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.nr-data.net:4317](https://otlp.nr-data.net:4317)(米国向け) - - * これは、アプリケーション テレメトリがエクスポートされるエンドポイントです。データを New Relic の OTLP エンドポイントにエクスポートします。EU にいる場合は、次のエンドポイントを使用してください: OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.eu01.nr-data.net:4317](https://otlp.eu01.nr-data.net:4317) -
- OTEL_SERVICE_NAME=入門-Python - - * これは、アプリケーション テレメトリを New Relic のエンティティに関連付ける名前です。このチュートリアルでは`getting-started-python`と呼んでいますが、任意の名前にすることができます。 -
- OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_OWN_ID_HERE - - * `INSERT_YOUR_OWN_ID_HERE`を一意のインスタンス ID に置き換えます。たとえば、 `1234`を使用できます。詳細については、OpenTelemetry の[Resource Semantic Conventions](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service)を参照してください。 -
- OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT=4095 - - * 属性値の最大長に制限を設定すると、 [New Relic の制限](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-attributes/)を超えた場合にスパン データがドロップされるのを防ぐことができます。 -
- OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=DELTA - - * New Relic は、デフォルトの累積ではなく、デルタ一時性のメトリクスをサポートします。 -
- OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=EXPONENTIAL_BUCKET_HISTOGRAM - - * (推奨) ヒストグラム集約: データ圧縮を向上させるために、既定の明示的なバケット ヒストグラムの代わりに指数ヒストグラムを使用します。 -
- OTEL_LOGS_EXPORTER=otlp - - * OTLP 経由のログ エクスポートを有効にします。ログのエクスポートはデフォルトで無効になっています。 -
- OTEL_EXPORTER_OTLP_COMPRESSION=gzip - - * (推奨) gzip 圧縮を設定すると、リクエストごとに送信できるデータ量を最大化できます。最大許容ペイロード サイズは 1MB (10^6 バイト) です。Gzip 圧縮はパフォーマンスが高く、データ出力が低くなります。 -
- OTEL_EXPERIMENTAL_EXPORTER_OTLP_RETRY_ENABLED=真 - - * (推奨) 実験的なエクスポートの再試行を有効にして、インターネットの信頼性の低さに対処します。 -
- OTEL_EXPERIMENTAL_RESOURCE_DISABLED_KEYS=process.command_line - - * (推奨) これにより、多くの場合、New Relic の最大属性長制限を超え、機密情報が含まれている可能性がある`process.command_line`リソース属性が無効になります。 -
-
-
- -上の折りたたみツールにリストされている環境変数をエクスポートした後、チュートリアルに戻ってセットアップを完了します。 - -* [チュートリアル 2: OpenTelemetry Python エージェントを使用してデモ アプリを監視する](#python-agent) -* [チュートリアル 3: デモ アプリを手動でセットアップする](#manual-instrum) - -## 次は何ですか? [#what-next] - -OpenTelemetry インストルメンテーションと SDK 構成を試したので、学んだことを適用して、OpenTelemetry と New Relic を使用して独自のアプリまたはサービスをセットアップできます。詳細については[、OpenTelemetry を使用して独自のアプリまたはサービスをセットアップする](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-set-up-your-app)を参照してください。 \ No newline at end of file diff --git a/src/i18n/content/kr/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-android-gradle-android-studio.mdx b/src/i18n/content/kr/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-android-gradle-android-studio.mdx deleted file mode 100644 index 9e0ed3d8c7f..00000000000 --- a/src/i18n/content/kr/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-android-gradle-android-studio.mdx +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Gradle 및 Android Studio로 Android 앱 구성 -tags: - - Mobile monitoring - - New Relic Mobile Android - - Install configure -metaDescription: null -freshnessValidatedDate: '2023-07-27T00:00:00.000Z' -translationType: human ---- - -[Android 에이전트를 설치하면](/docs/mobile-monitoring/new-relic-mobile-android/get-started/introduction-new-relic-mobile-android/#installation) 성능, 안정성 및 사용자 참여를 개선하도록 모바일 앱을 구성할 수 있습니다. Gradle 및 Android Studio를 사용하는 경우 아래 단계를 따릅니다. - -## Gradle 및 Android Studio로 구성 [#configuration] - -Gradle 및 Android Studio로 Android 앱을 구성하는 절차는 Android [UI 안내 설치](https://onenr.io/02R5GVpaxQb)의 "DSL 코드 추가" 단계에도 표시됩니다. - -1. 플러그인이 적용되기 전에 프로젝트의 최상위 레벨 `build.gradle` 파일에서 다음 코드를 병합하거나 추가합니다. - - - - 프로젝트 레벨 구성은 프로젝트의 모든 앱에 대한 에이전트를 구성하는 데 사용됩니다. 여기에는 프로젝트 토큰 설정, 기능 활성화 또는 비활성화, 알림 임계값 설정이 포함됩니다. 이 예에서, AGENT_VERSION은 에이전트 버전 번호를 나타냅니다. [에이전트 릴리스 정보](/docs/release-notes/mobile-release-notes/android-release-notes)에서 최신 버전이 사용되고 있는지 확인합니다. - - ``` - buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath "com.newrelic.agent.android:agent-gradle-plugin:AGENT_VERSION" - } - } - ``` - - - - 특정 앱에 대한 설정을 구성하려면 앱 레벨 구성을 사용합니다. 이 예에서, AGENT_VERSION은 에이전트 버전 번호를 나타냅니다. [에이전트 릴리스 정보](/docs/release-notes/mobile-release-notes/android-release-notes)에서 최신 버전이 사용되고 있는지 확인합니다. - - ``` - repositories { - mavenCentral() - } - - apply plugin: 'android' - apply plugin: 'newrelic' - - dependencies { - implementation 'com.newrelic.agent.android:android-agent:AGENT_VERSION' - } - ``` - - - -2. **(선택 사항)** ProGuard 또는 DexGuard의 경우: - - a. 프로젝트의 루트 디렉터리(`/projectname/app`)에서 다음 줄과 함께 `newrelic.properties` 파일을 추가합니다. - - ``` - com.newrelic.application_token=GENERATED_TOKEN - ``` - - b. [Android 앱을 위한 ProGuard 또는 DexGuard 구성](/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-proguard-or-dexguard-android-apps)에서 명시된 구성 단계를 완료합니다. 그런 다음 이 페이지로 돌아와 다음 단계로 이동합니다. - - -3. 앱 권한을 설정합니다. `AndroidManifest.xml` 파일에 다음 행을 추가하여 Android 앱이 `INTERNET` 및 `ACCESS_NETWORK_STATE` 권한을 요청하도록 합니다. - - ``` - - - ``` - -4. Android 에이전트를 시작합니다. **Default Activity** (**Manifest**에 정의된 대로)에서 `NewRelic` 클래스를 가져옵니다. - - ``` - import com.newrelic.agent.android.NewRelic; - ``` - - - 예기치 않거나 불안정한 동작이 발생할 수 있으므로 다른 클래스에서 모바일 모니터링 에이전트를 시작하는 것은 지원되지 않습니다. - - -5. 모바일 모니터링을 초기화합니다. `onCreate()` 메서드에서 다음 호출을 추가합니다. - - ``` - NewRelic.withApplicationToken("GENERATED_TOKEN").start(this.getApplication()); - ``` - -6. **(선택 사항)** [로깅 레벨](/docs/mobile-monitoring/new-relic-mobile-android/api-guides/android-agent-configuration-feature-flags#logging)을 변경합니다. - -7. 애플리케이션을 빌드하고 실행합니다. 프로젝트를 삭제한 후 에뮬레이터 또는 디바이스에서 앱을 실행하여 트래픽을 생성합니다. - -8. 몇 분 정도 기다린 다음 [**Summary** 페이지](/docs/mobile-monitoring/mobile-monitoring-ui/mobile-app-pages/mobile-apps-overview-page)에서 Android 앱에 대한 데이터를 확인합니다. **[one.newrelic.com](https://one.newrelic.com/all-capabilities) > Mobile > (select an app)**으로 이동합니다. - -Android 설치에 문제가 있거나 모바일 모니터링 UI에 데이터가 표시되지 않는 경우 [문제 진단 절차](/docs/mobile-monitoring/new-relic-mobile-android/troubleshoot/no-data-appears-android)를 따르십시오. - - - -Android 앱에 대한 multidex 지원을 활성화하여 64K 레퍼런스 제한을 피하는 방법은 아래 설명을 확인하시기 바랍니다. - -## Multidex 지원 활성화 [#4x-multidex] - -Android 5.0(API 레벨 21) 이전의 Android 버전의 경우 뉴렐릭의 모바일 모니터링은 Dalvik 런타임을 사용해 앱 코드를 실행합니다. 기본적으로 Dalvik은 앱을 APK당 단일 `classes.dex` 바이트코드 파일로 제한합니다. 이 제한을 해결하려면 [멀티덱스 지원을 활성화](https://developer.android.com/studio/build/multidex.html) **해야 합니다**.그런 다음 [멀티덱스 지원 라이브러리](https://developer.android.com/tools/support-library/features.html#multidex)를 사용할 수 있습니다. 이 라이브러리는 앱의 기본 DEX 파일의 일부가 되며 추가적인 DEX 파일과 파일에 포함된 코드에 대한 액세스를 관리합니다. - -멀티덱스 앱을 위해 각 DEX 파일을 빌드할 때, 빌드 툴은 복잡한 의사 결정을 수행하여 앱이 성공적으로 시작될 수 있도록 기본 DEX 파일에 필요한 클래스를 결정합니다. 시작 중에 필요한 클래스가 기본 DEX 파일에 제공되지 않으면 `java.lang.NoClassDefFoundError` 오류가 발생하며 앱이 충돌합니다. - -`java.lang.NoClassDefFoundError` 오류가 표시되면 기본 DEX 파일에서 [필요에 따라 이러한 추가 클래스를 수동으로 지정](https://developer.android.com/studio/build/multidex.html#keep)해야 합니다. - -1. 프로젝트의 `/app` 폴더 내에 `proguard.multidex.config` 파일을 생성합니다. 패키지 이름을 반영하도록 `mypackage`를 업데이트합니다. - - ``` - #################### - # keep class names # - #################### - - #Keep New Relic in the main dex - -keep class com.newrelic.** { *; } - -keep class com.mypackage.activities.** { *; } - ``` - -2. 다음 코드를 앱 레벨 `build.gradle` 파일에 병합합니다. - - ``` - android { - defaultConfig{ - … - multiDexKeepProguard file("proguard.multidex.config") - } - } - ``` - -보다 자세한 내용은 기본 DEX 파일에 필요한 클래스 선언에 대한 [Android 개발자 문서](https://developer.android.com/studio/build/multidex.html#keep)를 참조하십시오. - -## New Relic Gradle 플러그인 구성 [#gradle_plugin_config] - -Gradle 빌드 중에 Android 에이전트 플러그인의 동작을 구성하는 방법에 대한 자세한 내용은 [뉴렐릭 Gradle 플러그인](/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-new-relic-gradle-plugin) 확장 가이드를 참조하십시오. \ No newline at end of file diff --git a/src/i18n/content/kr/docs/mobile-monitoring/new-relic-mobile-android/install-configure/install-android-apps-gradle-android-studio.mdx b/src/i18n/content/kr/docs/mobile-monitoring/new-relic-mobile-android/install-configure/install-android-apps-gradle-android-studio.mdx deleted file mode 100644 index 8f416774236..00000000000 --- a/src/i18n/content/kr/docs/mobile-monitoring/new-relic-mobile-android/install-configure/install-android-apps-gradle-android-studio.mdx +++ /dev/null @@ -1,163 +0,0 @@ ---- -title: Android 에이전트 수동 설치(Gradle/Android Studio) -tags: - - Mobile monitoring - - New Relic Mobile Android - - Install configure -metaDescription: 'New accounts: Get Android app monitoring in New Relic at newrelic.com/signup. Existing accounts: Add mobile monitoring to your Android apps from the UI.' -freshnessValidatedDate: never -translationType: human ---- - -Android 모니터링을 설정하려면 [안내 설치](https://onenr.io/0kjnEoryzRo)를 사용하는 것이 좋습니다. 그러나 에이전트를 수동으로 설치해야 하는 경우, 아래 단계에 따라 Gradle 및 Android Studio를 사용하여 뉴렐릭 Android 에이전트를 설치하시기 바랍니다. - - - -## Android 앱 설치 [#installation] - -모바일 모니터링을 위한 설치 프로세스의 일부로 뉴렐릭은 [애플리케이션 토큰](/docs/mobile-apps/viewing-your-application-token)을 자동으로생성합니다. 이 토큰은 뉴렐릭에서 모니터링되는 각 모바일 앱을 인증하기 위한 40자의 16진수 문자열입니다. - -1. **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > Mobile** 로 이동합니다. -2. 해당되는 경우: [**모바일 앱** 인덱스](/docs/mobile-monitoring/mobile-monitoring-ui/mobile-app-pages/mobile-apps-index)에서 **Add a new app**을 선택합니다. -3. **Get started** 페이지에서 모바일 모니터링을 위한 플랫폼으로 **Android**를 선택합니다. -4. 모바일 앱의 이름을 입력하고 **Continue**를 선택합니다. - -Gradle 및 Android Studio를 통해 [모바일 모니터링을 구성하는](#configuration) 단계를 계속 진행합니다. - -또는: - -* 나중에 새 모바일 앱에 대한 구성 프로세스를 완료하려면: **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > Mobile**로 이동한 다음 모바일 앱 이름 옆에 있는 **See instructions**를 선택합니다. -* 기존 Android 설치를 업그레이드하려면: **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > Mobile > (select an app) > Settings > Installation**으로 이동합니다. - -## Gradle 및 Android Studio로 구성 [#configuration] - -Gradle 및 Android Studio로 Android 앱을 구성하는 절차는 뉴렐릭의 **Get started** 페이지에도 표시됩니다. - -1. **Gradle 및 Android Studio** 탭에서 뉴렐릭의 모바일 모니터링 코드를 `build.gradle` 파일에 병합합니다. - - - - 이 예에서, AGENT_VERSION은 에이전트 버전 번호를 나타냅니다. [에이전트 릴리스 정보](/docs/release-notes/mobile-release-notes/android-release-notes)를 확인하여 최신 버전을 사용하십시오. - - ``` - buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath "com.newrelic.agent.android:agent-gradle-plugin:AGENT_VERSION" - } - } - ``` - - - - 이 예에서, AGENT_VERSION은 에이전트 버전 번호를 나타냅니다. [에이전트 릴리스 정보](/docs/release-notes/mobile-release-notes/android-release-notes)를 확인하여 최신 버전을 사용하십시오. - - ``` - repositories { - mavenCentral() - } - - apply plugin: 'android' - apply plugin: 'newrelic' - - dependencies { - implementation 'com.newrelic.agent.android:android-agent:AGENT_VERSION' - } - ``` - - - - -2. **(선택 사항)** ProGuard 또는 DexGuard의 경우: - - a. 프로젝트의 루트 디렉터리(`projectname/app`)에서 다음 줄과 함께 `newrelic.properties` 파일을 추가합니다. - - ```properties - com.newrelic.application_token=GENERATED_TOKEN - ``` - - b. [Android 앱을 위한 ProGuard 또는 DexGuard 구성](/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-proguard-or-dexguard-android-apps)에서 명시된 구성 단계를 완료합니다. 그런 다음 이 페이지로 돌아와 다음 단계로 이동합니다. - - -3. 앱 권한 설정: `AndroidManifest.xml` 파일에 다음 행을 추가하여 Android 앱이 `INTERNET` 및 `ACCESS_NETWORK_STATE` 권한을 요청하도록 합니다. - - ``` - - - ``` - -4. 뉴렐릭의 모바일 모니터링 에이전트를 시작하려면: **Default Activity**(**Manifest**에 정의된 대로)에서 `NewRelic` 클래스를 가져옵니다. - - ``` - import com.newrelic.agent.android.NewRelic; - ``` - - - 예기치 않거나 불안정한 동작이 발생할 수 있으므로 다른 클래스에서 모바일 모니터링 에이전트를 시작하는 것은 지원되지 않습니다. - - -5. 모바일 모니터링을 초기화하려면: `onCreate()` 메서드에서 다음 호출을 추가합니다. - - ```java - NewRelic.withApplicationToken("GENERATED_TOKEN").start(this.getApplication()); - ``` - -6. 선택 사항: [로깅 수준](/docs/mobile-monitoring/new-relic-mobile-android/api-guides/android-agent-configuration-feature-flags#logging)을 변경합니다. - -7. 애플리케이션 빌드 및 실행하려면: 프로젝트를 삭제한 후 에뮬레이터 또는 디바이스에서 앱을 실행하여 트래픽을 생성합니다. - -8. 몇 분 정도 기다린 다음 [**Summary** 페이지](/docs/mobile-monitoring/mobile-monitoring-ui/mobile-app-pages/mobile-apps-overview-page)에서 Android 앱에 대한 데이터를 확인합니다. **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > Mobile > (select an app)**으로 이동합니다. - -Android 설치에 문제가 있거나 모바일 모니터링 UI에 데이터가 표시되지 않는 경우 [문제 진단 절차](/docs/mobile-monitoring/new-relic-mobile-android/troubleshoot/no-data-appears-android)를 따르십시오. - - - -## Android 설치 업데이트 [#upgrading] - -Android 에이전트를 최신 상태로 유지하려면 절차에 따라 뉴렐릭용 [Android 에이전트 SDK를 업그레이드합니다](/docs/mobile-monitoring/new-relic-mobile-android/install-configure/upgrading-new-relic-mobiles-android-sdk). 모바일 앱용 최신 Android 버전 설치: **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > Mobile > (select an app) > Settings > Installation**으로 이동합니다. - -## Android 4.x: 멀티덱스(multidex) 지원 [#4x-multidex] - -Android 5.0(API 레벨 21) 이전의 Android 버전의 경우 뉴렐릭의 모바일 모니터링은 Dalvik 런타임을 사용해 앱 코드를 실행합니다. 기본적으로 Dalvik은 앱을 APK당 단일 `classes.dex` 바이트코드 파일로 제한합니다. 이 제한을 해결하려면 [멀티덱스 지원을 활성화](https://developer.android.com/studio/build/multidex.html) **해야 합니다**.그런 다음 [멀티덱스 지원 라이브러리](https://developer.android.com/tools/support-library/features.html#multidex)를 사용할 수 있습니다. 이 라이브러리는 앱의 기본 DEX 파일의 일부가 되며 추가적인 DEX 파일과 파일에 포함된 코드에 대한 액세스를 관리합니다. - -멀티덱스 앱을 위해 각 DEX 파일을 빌드할 때, 빌드 툴은 복잡한 의사 결정을 수행하여 앱이 성공적으로 시작될 수 있도록 기본 DEX 파일에 필요한 클래스를 결정합니다. 시작 중에 필요한 클래스가 기본 DEX 파일에 제공되지 않으면 `java.lang.NoClassDefFoundError` 오류가 발생하며 앱이 충돌합니다. - -`java.lang.NoClassDefFoundError` 오류가 표시되면 기본 DEX 파일에서 [필요에 따라 이러한 추가 클래스를 수동으로 지정](https://developer.android.com/studio/build/multidex.html#keep)해야 합니다. - -1. 프로젝트의 `/app` 폴더 내에 `proguard.multidex.config` 파일을 생성합니다. 패키지 이름을 반영하도록 `mypackage`를 업데이트합니다. - - ``` - #################### - # keep class names # - #################### - - #Keep New Relic in the main dex - -keep class com.newrelic.** { *; } - -keep class com.mypackage.activities.** { *; } - ``` - -2. 다음 코드를 앱 레벨 `build.gradle` 파일에 병합합니다. - -``` -android { - defaultConfig{ - … - multiDexKeepProguard file("proguard.multidex.config") - } -} -``` - -보다 자세한 내용은 기본 DEX 파일에 필요한 클래스 선언에 대한 [Android 개발자 문서](https://developer.android.com/studio/build/multidex.html#keep)를 참조하십시오. - -## New Relic Gradle 플러그인 구성 [#gradle_plugin_config] - -Gradle 빌드 중에 모바일 모니터링 에이전트 플러그인의 동작을 구성하는 방법에 대한 자세한 내용은 [뉴렐릭 Gradle 플러그인](/docs/mobile-monitoring/new-relic-mobile-android/install-configure/configure-new-relic-gradle-plugin) 확장 가이드를 참조하십시오. \ No newline at end of file diff --git a/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx b/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx deleted file mode 100644 index 2f61a207663..00000000000 --- a/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx +++ /dev/null @@ -1,863 +0,0 @@ ---- -title: 'OpenTelemetry 튜토리얼: 샘플 Go 앱 계측' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: 'To test out OpenTelemetry on a sample Go app instead of your own app, consider these two tutorials.' -freshnessValidatedDate: never -translationType: machine ---- - -import openttelemetryPythonIntroImage from 'images/opentelemetry_screenshot-crop_python-intro.webp' - -import opentelemetryPythonFindTraceGroup from 'images/opentelemetry_screenshot-crop_find-trace-group.webp' - -import opentelemetryPythonDistributedTracingError from 'images/opentelemetry_screenshot-crop_python-distributed-tracing-error.webp' - -import opentelemetryPythonInProcessSpans from 'images/opentelemetry_screenshot-crop_python-in-process-spans.webp' - -import opentelemetryPythonExceptiononSpanEvent from 'images/opentelemetry_screenshot-crop_python-exception-on-span-event.webp' - -import opentelemetryPytyhonAttributesTab from 'images/opentelemetry_screenshot-crop_python-attributes-tab.webp' - -import opentelemetryPythonMetricsExplorerMain from 'images/opentelemetry_screenshot-crop_python-metrics-explorer-main.webp' - -import opentelemetryPythonMetricsExplorerDimensions from 'images/opentelemetry_screenshot-crop_python-metrics-explorer-dimensions.webp' - -import opentelemetryPythonMainLogsPage from 'images/opentelemetry_screenshot-full_python-main-logs-page.webp' - -import opentelemetryPythonLogsinTerminal from 'images/opentelemetry_screenshot-full_python-logs-in-terminal.webp' - -import opentelemetryPythonLogDetailsWithTrace from 'images/opentelemetry_screenshot-full_python-log-details-with-trace.webp' - -import opentelemetryPythonTraceRelatedtoLog from 'images/opentelemetry_screenshot-full_python-trace-related-to-log.webp' - -import opentelemetryPythonTraceWaterfallFromLog from 'images/opentelemetry_screenshot-full_python-trace-waterfall-from-log.webp' - -import opentelemetryPythonLogCapturedinTraceSpan from 'images/opentelemetry_screenshot-full_python-log-captured-in-trace-span.webp' - - - - New Relic 플랫폼이 OTLP 데이터로 무엇을 할 수 있는지 알아보려면 Go 튜토리얼을 시도해 보세요. 선택할 수 있는 두 개의 튜토리얼이 있으며 각 튜토리얼은 동일한 데모 앱을 사용합니다. 앱은 피보나치 수열의 n번째 숫자를 계산하고 추적 및 측정항목을 생성합니다. - - 이 자습서를 통해 작업하면 OpenTelemetry 및 New Relic을 사용하여 자신의 앱을 설정하는 데 도움이 되는 기술을 배울 수 있습니다. - - - - Screenshot showing response time, throughput, and error rate - -
- 이러한 자습서를 마치면 다음과 같은 차트에서 스팬 메트릭을 볼 수 있습니다. -
-
-
- -각 자습서는 동일한 데모 앱을 사용하지만 OpenTelemetry 및 New Relic에 익숙해지는 데 도움이 되는 접근 방식이 다릅니다. 관심 있는 옵션을 시도해 보십시오. - -* [튜토리얼 1: 사전 계측된 데모 앱 실행:](#pre-instrum) 이는 일부 데모 데이터를 New Relic으로 보내고 UI에 어떻게 표시되는지 확인하는 가장 빠른 방법입니다. 이 자습서의 데모 앱에는 추적 및 지표를 생성하고 내보내는 [모범 사례를](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-overview/) 따르는 계측 및 SDK 구성이 사전 로드되어 있습니다. 우리 코드를 검사하고 관련 섹션을 자신의 앱에 적용할 수 있습니다. -* [튜토리얼 2: 데모 앱 수동 설정:](#manual-instrum) 이 트랙에서는 소매를 걷어붙이고 자동차 엔진을 만지작거리게 됩니다. 이는 보고되는 원격 분석을 최대한 제어하고 수행 방법에 대한 세부 정보를 확인하려는 경우 취하는 접근 방식입니다. 원격 측정을 캡처하기 위해 데모 앱에 계측을 수동으로 삽입하고 해당 데이터를 New Relic으로 내보내도록 SDK를 구성합니다. - -[OpenTelemetry Go 자동 계측은](https://github.com/open-telemetry/opentelemetry-go-instrumentation) 현재 개발 중이므로 지금은 자습서에 포함되어 있지 않습니다. - - - OTLP를 통해 애플리케이션에서 New Relic으로 데이터를 내보내는 데는 두 가지 선택이 있습니다. - - * 앱에서 직접 - * OpenTelemetry 수집기를 통해 - - 이 가이드에서는 첫 번째 옵션을 다룹니다. 수집기를 통해 데이터를 내보내려면 이 [수집기 설명서](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-basic/) 에서 자세한 내용을 확인하세요. - - -## 요구 사항 [#requirements] - -시작하기 전에 다음이 있는지 확인하십시오. - -* New Relic 계정: 아직 계정이 없다면 [무료 계정](https://newrelic.com/signup) 에 가입하세요. -* [1.16 이상으로 이동](https://go.dev/doc/install) - -## 튜토리얼 1: 사전 계측된 데모 앱 실행 [#pre-instrum] - -New Relic에 데이터를 보내고 UI에서 보는 것이 어떤 것인지 빠르게 확인할 수 있도록 계측 작업을 수행하려는 경우에 유용한 옵션입니다. - -1. 터미널에서 다음을 실행하여 데모 앱을 복제하고 시작 안내서의 `go/Instrumented` 디렉토리로 이동합니다. - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/go/Instrumented - ``` - -2. New Relic 계정으로 데이터를 보내도록 다음 환경 변수를 설정합니다. - - * 당신의 . - - * New Relic 데이터 센터 지역이 US가 아닌 EU인 경우 끝점을 다음으로 설정합니다. `https://otlp.eu01.nr-data.net:4317` - - * OTEL_EXPORTER_OTLP_HEADERS=api-key=INSERT_YOUR_NEW_RELIC_LICENSE_KEY - * OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.nr-data.net:4317](https://otlp.nr-data.net:4317) - -3. 이 환경 변수를 설정하여 서비스 이름을 지정하십시오. 다음은 New Relic 계정에서 서비스를 식별하는 방법입니다. - - * OTEL_SERVICE_NAME=시작-파이썬 - -4. 동일한 `getting-started-guides/python/Instrumented/` 디렉토리에서 가상 환경을 생성 및 활성화하고 필요한 라이브러리를 설치한 후 앱을 실행합니다. - - * 맥 OS: - - ``` - python3 -m venv venv - source venv/bin/activate - pip install -r requirements.txt - python3 app.py - ``` - - * 파워셸: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - pip install -r requirements.txt - python app.py - ``` - -5. 새 터미널 탭을 열고 `getting-started-guides/python/Instrumented` 디렉터리로 전환한 후 다음 명령을 실행하여 애플리케이션에 대한 일부 트래픽을 생성합니다. - - * 맥 OS: - - ``` - ./load-generator.sh - ``` - - * 파워셸: - - ``` - .\load-generator.ps1 - ``` - - - 또는 다음 URL에서 브라우저의 엔드포인트에 도달할 수 있습니다: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` . `INSERT_A_VALUE` 을 1에서 90 사이의 값으로 바꿉니다. 오류를 생성하려면 유효한 범위 밖의 정수를 삽입하십시오. - - -6. **[one.newrelic.com](https://one.newrelic.com/all-capabilities) > APM & services** 로 이동합니다. - -7. `getting-started-python` 라는 새 항목(서비스)을 클릭하고 UI를 탐색합니다. UI에서 무엇을 찾아야 하는지에 대한 추가 팁은 [New Relic에서 데이터 보기](#view-data) 를 참조하십시오. - -8. UI에서 데이터 확인을 마치면 두 터미널 세션에서 `CONTROL+C` 눌러 애플리케이션을 종료합니다. - -## 자습서 2: OpenTelemetry Python 에이전트를 사용하여 데모 앱 모니터링 [#python-agent] - -다음은 동일한 데모 앱을 사용하는 다른 자습서이지만 이 경우 OpenTelemetry Python 에이전트를 사용하여 데모 앱을 자동으로 모니터링합니다. Python 소스 코드를 수정할 필요가 없습니다. 에이전트를 사용하면 샘플 데이터를 New Relic으로 빠르게 내보낼 수 있습니다. - -그러나 로그 및 사용자 정의 메트릭과 같은 앱에 대한 더 깊은 수준의 정보를 캡처하려면 사용자 정의 계측을 추가해야 합니다. - -자동 계측 에이전트는 널리 사용되는 라이브러리 및 프레임워크에서 원격 분석을 캡처하기 위해 바이트 코드를 동적으로 주입하는 시리즈 PyPI 패키지입니다. 인바운드 요청, 아웃바운드 HTTP 호출 및 데이터베이스 호출과 같은 데이터를 캡처하는 데 사용할 수도 있습니다. 모든 Python 3 응용 프로그램에 연결할 수 있습니다. - - - 추가 구성 옵션은 [공식 OpenTelemetry Python 에이전트 설명서를](https://opentelemetry.io/docs/instrumentation/python/automatic/) 참조하세요. - - -OpenTelemetry Python 에이전트로 데모 앱을 모니터링하려면: - -1. 이 두 명령을 실행하여 데모 애플리케이션 리포지토리를 다운로드하고 다음 디렉터리로 변경합니다. - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` - -2. 아래의 [환경 변수 참조 섹션](#ref-env-vars) 으로 이동하여 내보내야 하는 변수를 확인한 다음 이 단계로 돌아갑니다. - -3. 그런 다음 동일한 `getting-started-guides/python/Uninstrumented/` 디렉토리에서 가상 환경을 만들고 활성화합니다. - - * 맥 OS: - - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * 파워셸: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` - -4. 이제 필요한 라이브러리를 설치할 준비가 되었습니다. - - ``` - pip install flask - pip install opentelemetry-instrumentation-flask - pip install opentelemetry-exporter-otlp - pip install opentelemetry-distro - ``` - -5. 앱으로 에이전트를 시작하려면 `getting-started-guides/python/Uninstrumented/` 에서 계속합니다. - - * 맥 OS: - - ``` - opentelemetry-instrument python3 app.py - ``` - - * 파워셸: - - ``` - opentelemetry-instrument python app.py - ``` - -6. `getting-started-guides/python/Uninstrumented` 디렉터리에서 새 터미널을 열고 부하 생성기를 실행하여 애플리케이션에 대한 트래픽을 생성합니다. - - * 맥 OS: - - ``` - ./load-generator.sh - ``` - - * 파워셸: - - ``` - .\load-generator.ps1 - ``` - - - 또는 다음 URL에서 브라우저의 엔드포인트에 도달할 수 있습니다: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` . `INSERT_A_VALUE` 을 1에서 90 사이의 값으로 바꿉니다. 오류를 생성하려면 유효한 범위 밖의 정수를 삽입하십시오. - - -7. 일부 데이터를 New Relic에 전송했으므로 이제 [UI에서 데이터 보기에 대한 지침을](#view-data) 참조하십시오. - -8. UI에서 데이터 확인을 마치면 두 터미널 세션에서 `CONTROL+C` 눌러 애플리케이션을 종료합니다. - -## 자습서 3: 수동으로 데모 앱 설정 [#manual-instrum] - -이전 섹션에서는 OpenTelemetry Python 에이전트를 사용한 자동 계측을 살펴보는 데 도움이 되었습니다. 수집하는 원격 분석에 대해 더 많은 제어를 원하는 경우 이 자습서를 시도하여 사용자 지정 계측을 추가하는 방법을 배울 수 있습니다. 그런 다음 권장 모범 사례를 사용하여 데이터를 New Relic으로 내보내도록 OpenTelemetry SDK를 구성하는 방법을 살펴봅니다. - -이 수동 설정을 위해 완료할 단계는 다음과 같습니다. - -* [A. 데모 애플리케이션 다운로드](#download) -* [B. 필요한 라이브러리 설치](#libraries) -* [C. SDK 구성](#config-sdk) -* [D. 계측 라이브러리 추가: 추적](#library-traces) -* [E. 계측 라이브러리 추가: 메트릭](#library-metrics) -* [F. 계측 라이브러리 추가: 로그](#library-logs) -* [G. Flask 계측 추가](#flask-instrum) -* [H. 사용자 지정 추적 계측: 사용자 지정 범위 만들기](#cust-span) -* [I. 사용자 지정 추적 계측: 예외 기록](#span-exception) -* [J. 사용자 지정 메트릭 계측: 사용자 지정 메트릭 카운터 추가](#cust-metrics) -* [K. 사용자 지정 로그 계측](#cust-log) -* [L. 일부 트래픽을 생성하도록 앱을 실행합니다.](#exercise-app) - -### A. 데모 애플리케이션 다운로드 [#download] - -데모 앱을 다운로드하려면 다음을 실행하십시오. - -``` -git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git -``` - -### B. 필요한 라이브러리 설치 [#libraries] - -필요한 라이브러리를 추가하려면: - -1. 이 자습서의 시작점으로 계측되지 않은 앱의 애플리케이션 디렉터리로 이동합니다. 이 튜토리얼이 끝나면 코드는 `Instrumented` 디렉토리에 있는 것과 같아야 합니다. - - ``` - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` - -2. `Uninstrumented` 디렉터리에서 가상 환경을 만들고 활성화합니다. - - * 맥 OS: - - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * 파워셸: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` - -3. 다음을 설치합니다. - - ``` - pip install opentelemetry-api - pip install opentelemetry-sdk - pip install flask - pip install opentelemetry-instrumentation-logging - pip install opentelemetry-instrumentation-flask - pip install opentelemetry-exporter-otlp - pip install opentelemetry-distro - ``` - -### C. SDK 구성 [#config-sdk] - -1. `app.py`에서 아래 강조 표시된 줄을 **파일 상단**에 추가합니다. 필요에 따라 사용자 정의 속성 `environment` 의 값을 변경하십시오. - -```python lineHighlight=1-10 -########################## -# OpenTelemetry Settings # -########################## -from opentelemetry.sdk.resources import Resource -import uuid - -OTEL_RESOURCE_ATTRIBUTES = { - "service.instance.id": str(uuid.uuid1()), - "environment": "local" -} - -from flask import Flask, jsonify, request - -app = Flask(__name__) -``` - -2. 아래의 [환경 변수 참조 섹션](#ref-env-vars) 으로 이동하여 내보내야 하는 변수를 확인한 후 다음 단계로 이동하여 계측 라이브러리를 추가하십시오. - -### D. 계측 라이브러리 추가: 추적 [#library-traces] - -`app.py`에서 추가한 `OpenTelemetry Settings` 뒤에 다음을 삽입합니다. - -```python -########## -# Traces # -########## -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter -from opentelemetry.trace.status import Status, StatusCode - -# Initialize tracing and an exporter that can send data to an OTLP endpoint -# SELECT * FROM Span WHERE instrumentation.provider='opentelemetry' -trace.set_tracer_provider(TracerProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES))) -trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) -``` - -### E. 계측 라이브러리 추가: 메트릭 [#library-metrics] - -`app.py` 에서 D단계에서 추가한 `Traces` 섹션 뒤에 다음을 추가합니다. - -```python -########### -# Metrics # -########### -from opentelemetry import metrics -from opentelemetry.sdk.metrics import MeterProvider -from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter - -# Initialize metering and an exporter that can send data to an OTLP endpoint -# SELECT count(`http.server.active_requests`) FROM Metric FACET `service.name` TIMESERIES -metrics.set_meter_provider(MeterProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES), metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())])) -metrics.get_meter_provider() -fib_counter = metrics.get_meter("opentelemetry.instrumentation.custom").create_counter("fibonacci.invocations", unit="1", description="Measures the number of times the fibonacci method is invoked.") -``` - -### F. 계측 라이브러리 추가: 로그 [#library-logs] - -`app.py`에서 `Metrics` 섹션 뒤에 다음을 추가합니다. 이는 로깅 모듈을 가져오고 `basicConfig` 로깅 수준을 `DEBUG`로 설정합니다. - -```python -######## -# Logs # - OpenTelemetry Logs are still in the experimental state, so function names may change in the future -######## -import logging -logging.basicConfig(level=logging.DEBUG) - -from opentelemetry import _logs -from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler -from opentelemetry.sdk._logs.export import BatchLogRecordProcessor -from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter - -# Initialize logging and an exporter that can send data to an OTLP endpoint by attaching OTLP handler to root logger -# SELECT * FROM Log WHERE instrumentation.provider='opentelemetry' -_logs.set_logger_provider(LoggerProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES))) -logging.getLogger().addHandler(LoggingHandler(logger_provider=_logs.get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter())))) -``` - -### G. Flask 계측 추가 [#flask-instrum] - -`app.py` 에서 `Logs` 섹션 뒤에 아래 강조표시된 줄을 추가합니다. 이것은 분산 추적 및 로그인 컨텍스트에 대한 연결 범위에 도움이 됩니다. - -```python lineHighlight=1-3,5,8 - -##################### -# Flask Application # -##################### -from flask import Flask, jsonify, request -from opentelemetry.instrumentation.flask import FlaskInstrumentor - -app = Flask(__name__) -FlaskInstrumentor().instrument_app(app) -``` - -### H. 사용자 지정 추적 계측: 사용자 지정 범위 만들기 [#cust-span] - -원하는 스팬은 무엇이든 만들 수 있으며 특정 작업에 대한 속성으로 스팬에 주석을 추가하는 것은 사용자의 몫입니다. 설정한 속성은 결과 또는 작업 속성과 같이 추적 중인 특정 작업에 대한 추가 컨텍스트를 제공합니다. - -`app.py`에서 아래에 강조표시된 줄을 삽입하여 다음을 수행하는 `/fibonacci` 라는 새 스팬을 시작합니다. - -* 이 메서드의 실행에 대한 데이터를 캡처합니다. - -* 사용자 요청에서 n 값을 저장하는 속성을 설정합니다. - - ```python lineHighlight=3,8,16 - - @app.route("/fibonacci") - - @trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") - def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - return jsonify(n=x, result=array[x]) - - except AssertionError: - return jsonify({"message": error_message}) - - app.run(host='0.0.0.0', port=8080) - ``` - -### I. 사용자 지정 추적 계측: 예외 기록 [#span-exception] - -예외가 발생하면 기록할 수 있습니다. 스팬 상태 설정과 함께 이 작업을 수행하는 것이 좋습니다. - -1. 예외가 발생할 때 스팬의 상태 코드를 `ERROR` 로 설정하려면 `opentelemetry.trace.status package`에서 `Status` 및 `StatusCode` 모듈도 가져와야 합니다. 다른 추적 라이브러리가 있는 `Traces` 섹션에 아래 강조 표시된 줄을 추가합니다. - -```python lineHighlight=8 -########## -# Traces # -########## -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter -from opentelemetry.trace.status import Status, StatusCode -``` - -2. 다음으로 아래에 강조 표시된 줄을 삽입하여 New Relic에서 스팬 이벤트로 표시되는 예외를 기록하고 스팬 상태를 `ERROR`로 설정합니다. - -```python lineHighlight=19,20 -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### J. 사용자 지정 메트릭 계측: 사용자 지정 메트릭 카운터 추가 [#cust-metrics] - -메트릭은 개별 측정을 집계로 결합하고 시스템 부하의 함수로 일정한 데이터를 생성하기 때문에 정말 유용한 원격 분석 데이터 유형입니다. 이 데이터를 스팬과 함께 사용하여 추세를 파악하고 애플리케이션 런타임 원격 분석을 제공할 수 있습니다. 메트릭이 나타내는 측정의 하위 구분을 설명하는 데 도움이 되는 속성으로 메트릭에 주석을 달 수도 있습니다. - -OpenTelemetry 메트릭 API는 메트릭 SDK에서 집계하고 외부 프로세스로 내보낸 측정값을 기록하는 여러 계측기를 정의합니다. 악기에는 두 가지 유형이 있습니다. - -* 동기식: 이 계측기는 측정이 발생하는 대로 기록합니다. -* 비동기식: 이러한 도구는 컬렉션당 한 번만 호출되고 관련 컨텍스트가 없는 콜백을 등록합니다. - -1. `app.py`에서 아래의 `Metrics` 섹션에 강조 표시된 줄을 추가하여 카운터를 만듭니다. - -```python lineHighlight=13 -########### -# Metrics # -########### -from opentelemetry import metrics -from opentelemetry.sdk.metrics import MeterProvider -from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter - -# Initialize metering and an exporter that can send data to an OTLP endpoint -# SELECT count(`http.server.active_requests`) FROM Metric FACET `service.name` TIMESERIES -metrics.set_meter_provider(MeterProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES), metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())])) -metrics.get_meter_provider() -fib_counter = metrics.get_meter("opentelemetry.instrumentation.custom").create_counter("fibonacci.invocations", unit="1", description="Measures the number of times the fibonacci method is invoked.") -``` - -2. 다음으로 측정을 위해 방금 만든 카운터를 사용하려면 아래에 강조 표시된 줄을 추가합니다. - -* 이 함수가 성공적으로 실행되는 횟수 -* 실행에 실패한 횟수 - -앱을 다시 시작할 때마다 카운터가 0으로 재설정됩니다. - -```python lineHighlight=16,22 -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - fib_counter.add(1, {"fibonacci.valid.n": "true"}) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - fib_counter.add(1, {"fibonacci.valid.n": "false"}) - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### K. 사용자 지정 로그 계측 [#cust-log] - -OpenTelemetry Python의 로그 신호 상태는 현재 [실험적](https://github.com/open-telemetry/opentelemetry-python#project-status)입니다. - -`app.py`에서 아래 강조 표시된 줄을 다음에 추가합니다. - -* 입력 및 출력 값에 대한 `INFO` 수준 로그를 기록합니다. -* 입력 값이 유효한 범위를 벗어나면 `ERROR` 수준 로그를 기록합니다. - -```python lineHighlight=17,24 - -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - fib_counter.add(1, {"fibonacci.valid.n": "true"}) - logging.info("Compute fibonacci(" + str(x) + ") = " + str(array[x])) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - fib_counter.add(1, {"fibonacci.valid.n": "false"}) - logging.error("Failed to compute fibonacci(" + str(x) + ")") - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### L. 일부 트래픽을 생성하도록 앱을 실행합니다. [#exercise-app] - -New Relic에 일부 데이터를 보낼 준비가 되었습니다! - -1. 터미널에서 `getting-started-guides/python/Uninstrumented` 디렉토리에 있는지 확인한 다음 애플리케이션을 실행합니다. - - * MacOS: - - ``` - python3 app.py - ``` - - * 파워셸: - - ``` - python app.py - ``` - -2. `getting-started-guides/python/Uninstrumented` 디렉토리에서 새 터미널 탭을 열고 부하 생성기를 실행하여 애플리케이션에 대한 트래픽을 생성합니다. - - * MacOS: - - ``` - ./load-generator.sh - ``` - - * 파워셸: - - ``` - .\load-generator.ps1 - ``` - - - 또는 다음 URL에서 브라우저의 엔드포인트에 도달할 수 있습니다: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` . `INSERT_A_VALUE` 을 1에서 90 사이의 값으로 바꿉니다. 오류를 생성하려면 유효한 범위 밖의 정수를 삽입하십시오. - - -3. 일부 데이터를 New Relic에 전송했으므로 이제 [UI에서 데이터 보기에 대한 지침을](#view-data) 참조하십시오. - -## New Relic에서 데모 데이터 보기 [#view-data] - -어떤 튜토리얼을 완료했는지에 관계없이 New Relic UI에서 데이터를 찾기 위한 아래 팁을 따를 수 있습니다. - -[자습서 2: OpenTelemetry Python 에이전트를 사용하여 데모 앱 모니터링: 을](#python-agent)따랐다면 더 세분화된 데이터를 캡처하기 위해 사용자 지정 계측을 수동으로 추가해야 하므로 사용자 지정 데이터(예: 사용자 지정 메트릭 및 로그)가 표시되지 않습니다. - -1. **[one.newrelic.com](https://one.newrelic.com/all-capabilities) > APM & services** 로 이동합니다. -2. `getting-started-python` (또는 제공한 이름)라는 새 항목(서비스)을 클릭합니다. -3. 각 데이터 유형에 대한 섹션에서 세부 정보를 확인하십시오. - - - Microsoft Windows를 사용 중이고 New Relic 계정에 데이터가 표시되지 않으면 방화벽을 통한 트래픽을 허용했는지 확인하십시오. - - -### 트레이스 [#traces] - -New Relic에서 `getting-started-python` 엔티티에 도달하면: - -1. 왼쪽 창의 **Monitor** \[모니터] 섹션에서 **Distributed tracing** \[분산 추적을] 클릭한 다음 `/fibonacci` 추적 그룹을 클릭합니다. - - Screenshot showing how to find your trace group - -2. 거기에서 오류가 있는 트레이스를 찾아 클릭하여 엽니다. - - Screenshot showing an error in distributed tracing - -3. 트레이스가 열려 있으면 `Show in-process spans` 클릭한 다음 결과 범위를 클릭하면 오른쪽에 세부정보 패널이 열립니다. 사용자 입력이 유효하지 않을 때 기록한 예외를 보려면 `View span events` 클릭하십시오. - - Screenshot of in-process spans - -수동 계측 자습서를 완료한 경우 범위로 기록한 예외가 New Relic에서 다음과 같이 표시됩니다. - -Screenshot showing an exception as a span event - -스팬 속성, 스팬 이름 및 상태 코드와 같이 설정한 추가 세부 정보를 보려면 **속성** 탭을 클릭하십시오. 또한 이 창에서는 이 가이드에서 사용한 계측 라이브러리에서 자동으로 수집한 추가 메타데이터와 New Relic에서 첨부한 메타데이터를 볼 수 있습니다. - -Screenshot of the attributes tab - -데이터 보기에 대한 자세한 내용은 [New Relic UI의 OpenTelemetry를](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page) 참조하십시오. - -### 메트릭 [#metrics] - -New Relic에서 `getting-started-python` 엔티티에 도달하면 사용자 정의 카운터 속성과 같은 수집된 모든 메트릭 목록을 볼 수 있습니다. - -#### 측정항목 탐색기 [#metrics-explorer] - -메트릭 목록을 볼 수 있는 도구입니다. - -1. 왼쪽 창에서 **Data > Metrics explorer** 를 선택한 다음 `fibonacci.invocations` 를 선택합니다. - - Screenshot showing metrics explorer - -2. **차원** 아래에서 사용자 정의 메트릭과 함께 수집한 속성을 확인한 다음 **fibonacci.valid.n** 을 클릭하십시오. - - Screenshot showing the total number of invocations of fibonacci function - -[메트릭 탐색기 보기](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-metrics-explorer-page) 에 대한 설명서에서 자세히 알아보세요. - -### 로그 [#logs] - -로그에 액세스할 수 있는 위치는 다음과 같습니다. - -Screenshot showing the main logs page - -또한 터미널에 로그가 표시됩니다. - -Screenshot showing logs in a terminal - -로그 보기로 돌아가서 로그를 선택하면 로그 메시지와 수집된 추가 속성(예: 관련 스팬 및 트레이스 ID, New Relic에서 삽입한 메타데이터)이 있는 창이 열립니다. - -Screenshot showing log details with trace - -이 작은 파란색 아이콘을 클릭하여 상관 분산 추적으로 이동할 수 있습니다. - -Screenshot showing how to find correlated trace - -그러면 추적에 대한 자세한 정보를 볼 수 있는 상관 추적을 표시하는 창이 열립니다. 이 페이지에 대한 자세한 내용 [은 UI의 OpenTelemetry: 분산 추적 페이지](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page/) 및 [분산 추적 UI 이해 및 사용](/docs/distributed-tracing/ui-data/understand-use-distributed-tracing-ui/) 을 참조하세요. - -Screenshot showing the trace waterfall from the logs section - -분산 추적 보기에서 상관 로그를 찾을 수도 있습니다. 해당 로그가 있는 추적을 선택하면 해당 로그가 탭으로 표시되며 보기를 전환하지 않고도 추적에서 직접 로그를 볼 수 있습니다. - -Screenshot showing how to see log details from a trace span - -[여기](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-logs-page) 에서 로그 보기에 대해 자세히 알아보세요. - -## 참조: 환경 변수 [#ref-env-vars] - -튜토리얼 2 또는 3을 수행하는 경우 내보내야 하는 환경 변수 목록입니다. 변수 내보내기를 완료한 후 변수 목록 다음에 오는 링크를 사용하여 자습서로 돌아갑니다. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- OTEL_EXPORTER_OTLP_HEADERS=api-key=YOUR_LICENSE_KEY - - * 헤더: 데이터를 보낼 New Relic 계정을 결정합니다. `YOUR_LICENSE_KEY` (를) - - - - . -
- OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.nr-data.net:4317](https://otlp.nr-data.net:4317) (미국의 경우) - - * 애플리케이션 원격 분석을 내보낼 엔드포인트입니다. New Relic의 OTLP 끝점으로 데이터를 내보냅니다. EU에 있는 경우 다음 엔드포인트를 사용하십시오. OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.eu01.nr-data.net:4317](https://otlp.eu01.nr-data.net:4317) -
- OTEL_SERVICE_NAME=시작-파이썬 - - * 애플리케이션 원격 측정을 New Relic의 엔터티와 연결하는 이름입니다. 이 가이드에서는 이를 `getting-started-python` 이라고 부르지만 원하는 대로 이름을 지정할 수 있습니다. -
- OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_OWN_ID_HERE - - * `INSERT_YOUR_OWN_ID_HERE` 를 고유한 인스턴스 ID로 바꿉니다. 예를 들어 `1234` 을 사용할 수 있습니다. 자세한 내용은 OpenTelemetry의 [리소스 의미 규칙](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service) 을 참조하십시오. -
- OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT=4095 - - * 최대 속성 값 길이에 제한을 설정하면 범위 데이터가 [New Relic 제한](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-attributes/) 을 초과하는 경우 삭제되지 않습니다. -
- OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=DELTA - - * New Relic은 누적의 기본값 대신 델타 시간성의 메트릭을 지원합니다. -
- OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=EXPONENTIAL_BUCKET_HISTOGRAM - - * (권장) 히스토그램 집계: 더 나은 데이터 압축을 위해 기본 명시적 버킷 히스토그램 대신 지수 히스토그램을 사용합니다. -
- OTEL_LOGS_EXPORTER=otlp - - * OTLP를 통한 로그 내보내기를 활성화합니다. 로그 내보내기는 기본적으로 비활성화되어 있습니다. -
- OTEL_EXPORTER_OTLP_COMPRESSION=gzip - - * (권장) gzip 압축을 설정하면 요청당 보낼 수 있는 데이터의 양을 최대화할 수 있습니다. 허용되는 최대 페이로드 크기는 1MB(10^6바이트)입니다. Gzip 압축은 성능이 우수하고 데이터 유출을 낮춥니다. -
- OTEL_EXPERIMENTAL_EXPORTER_OTLP_RETRY_ENABLED=참 - - * (권장) 인터넷의 불안정성에 대처하는 데 도움이 되도록 실험적인 내보내기 재시도를 활성화합니다. -
- OTEL_EXPERIMENTAL_RESOURCE_DISABLED_KEYS=process.command_line - - * (권장) 이것은 종종 New Relic 최대 속성 길이 제한을 초과하고 민감한 정보를 포함할 수 있는 `process.command_line` 자원 속성을 비활성화합니다. -
-
-
- -위 축소기에 나열된 환경 변수를 내보낸 후 자습서로 돌아가서 설정을 완료합니다. - -* [자습서 2: OpenTelemetry Python 에이전트를 사용하여 데모 앱 모니터링](#python-agent) -* [자습서 3: 수동으로 데모 앱 설정](#manual-instrum) - -## 다음은 뭐지? [#what-next] - -이제 OpenTelemetry 계측 및 SDK 구성을 실험했으므로 배운 내용을 적용하여 OpenTelemetry 및 New Relic을 사용하여 자체 앱 또는 서비스를 설정할 수 있습니다. 자세한 내용 [은 OpenTelemetry로 자체 앱 또는 서비스 설정을](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-set-up-your-app) 참조하십시오. \ No newline at end of file From 812e5a3e0d3d2650dce4d1fd0223a0776dd50b1c Mon Sep 17 00:00:00 2001 From: Jack Berg Date: Fri, 19 Jan 2024 10:57:45 -0600 Subject: [PATCH 4/4] Delete kr, jp versions of opentelemetry-tutorial-go.mdx --- .../get-started/opentelemetry-tutorial-go.mdx | 863 ------------------ .../get-started/opentelemetry-tutorial-go.mdx | 863 ------------------ 2 files changed, 1726 deletions(-) delete mode 100644 src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx delete mode 100644 src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx diff --git a/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx b/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx deleted file mode 100644 index 1e16fa2b888..00000000000 --- a/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx +++ /dev/null @@ -1,863 +0,0 @@ ---- -title: 'OpenTelemetry チュートリアル: サンプル Go アプリをインストゥルメントする' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: 'To test out OpenTelemetry on a sample Go app instead of your own app, consider these two tutorials.' -freshnessValidatedDate: never -translationType: machine ---- - -import openttelemetryPythonIntroImage from 'images/opentelemetry_screenshot-crop_python-intro.webp' - -import opentelemetryPythonFindTraceGroup from 'images/opentelemetry_screenshot-crop_find-trace-group.webp' - -import opentelemetryPythonDistributedTracingError from 'images/opentelemetry_screenshot-crop_python-distributed-tracing-error.webp' - -import opentelemetryPythonInProcessSpans from 'images/opentelemetry_screenshot-crop_python-in-process-spans.webp' - -import opentelemetryPythonExceptiononSpanEvent from 'images/opentelemetry_screenshot-crop_python-exception-on-span-event.webp' - -import opentelemetryPytyhonAttributesTab from 'images/opentelemetry_screenshot-crop_python-attributes-tab.webp' - -import opentelemetryPythonMetricsExplorerMain from 'images/opentelemetry_screenshot-crop_python-metrics-explorer-main.webp' - -import opentelemetryPythonMetricsExplorerDimensions from 'images/opentelemetry_screenshot-crop_python-metrics-explorer-dimensions.webp' - -import opentelemetryPythonMainLogsPage from 'images/opentelemetry_screenshot-full_python-main-logs-page.webp' - -import opentelemetryPythonLogsinTerminal from 'images/opentelemetry_screenshot-full_python-logs-in-terminal.webp' - -import opentelemetryPythonLogDetailsWithTrace from 'images/opentelemetry_screenshot-full_python-log-details-with-trace.webp' - -import opentelemetryPythonTraceRelatedtoLog from 'images/opentelemetry_screenshot-full_python-trace-related-to-log.webp' - -import opentelemetryPythonTraceWaterfallFromLog from 'images/opentelemetry_screenshot-full_python-trace-waterfall-from-log.webp' - -import opentelemetryPythonLogCapturedinTraceSpan from 'images/opentelemetry_screenshot-full_python-log-captured-in-trace-span.webp' - - - - これらの Go チュートリアルのいずれかを試して、New Relic プラットフォームが OTLP データで何ができるかを確認してください。選択できる 2 つのチュートリアルがあり、それぞれ同じデモ アプリを使用しています。アプリはフィボナッチ数列の n 番目の数値を計算し、トレースとメトリクスを生成します。 - - これらのチュートリアルに取り組むことで、OpenTelemetry と New Relic を使用して独自のアプリをセットアップするのに役立つスキルを習得できます。 - - - - Screenshot showing response time, throughput, and error rate - -
- これらのチュートリアルのいずれかを完了すると、次のようなグラフでスパン メトリックを表示できるようになります。 -
-
-
- -各チュートリアルは同じデモ アプリを使用しますが、OpenTelemetry と New Relic に慣れるのに役立つさまざまなアプローチがあります。興味のあるオプションを試してみてください。 - -* [チュートリアル 1: 事前にインストルメント化されたデモ アプリを実行する:](#pre-instrum)これは、デモ データを New Relic に送信し、UI でどのように表示されるかを確認する最も速い方法です。このチュートリアルでは、デモ アプリには、トレースとメトリクスを生成およびエクスポートするための[ベスト プラクティス](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-overview/)に従って、事前に読み込まれたインストルメンテーションと SDK 構成が含まれています。コードを調べて、関連するセクションを独自のアプリに適用できます。 -* [チュートリアル 2: デモ アプリを手動でセットアップする:](#manual-instrum)このトラックでは、袖をまくり上げて車のエンジンをいじります。これは、レポートされるテレメトリを最大限に制御し、その方法の詳細を確認したい場合にとるべきアプローチです。インストルメンテーションをデモアプリに手動で挿入してテレメトリをキャプチャし、そのデータを New Relic にエクスポートするように SDK を設定します。 - -[OpenTelemetry Go 自動計測器は](https://github.com/open-telemetry/opentelemetry-go-instrumentation)現在開発中であるため、現時点ではチュートリアルには含まれていません。 - - - アプリケーションから OTLP 経由で New Relic にデータをエクスポートするには、2 つの選択肢があります。 - - * アプリから直接 - * OpenTelemetry コレクター経由 - - このガイドでは、最初のオプションについて説明します。コレクター経由でデータをエクスポートする場合は、この[コレクターのドキュメント](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-basic/)で詳細を確認してください。 - - -## 要件 [#requirements] - -開始する前に、次のものが揃っていることを確認してください。 - -* New Relic アカウント:[無料アカウント](https://newrelic.com/signup)をまだお持ちでない場合は、サインアップしてください。 -* [Go 1.16 以降](https://go.dev/doc/install) - -## チュートリアル 1: 事前にインストルメント化されたデモ アプリを実行する [#pre-instrum] - -New Relic にデータを送信し、UI で表示するのがどのようなものかをすばやく確認できるように、インストルメンテーションを行う場合は、これが最適なオプションです。 - -1. ターミナルで次のコマンドを実行してデモ アプリのクローンを作成し、Getting Started Guides の`go/Instrumented`ディレクトリに移動します。 - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/go/instrumented - ``` - -2. New Relic アカウントにデータを送信するには、次の環境変数を設定します。 - - * 必ず使用してください . - - * New Relic データセンターのリージョンが EU で US ではない場合、エンドポイントを次のように設定します。 `https://otlp.eu01.nr-data.net:4317` - - * OTEL_EXPORTER_OTLP_HEADERS=api-key=INSERT_YOUR_NEW_RELIC_LICENSE_KEY - * OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.nr-data.net:4317](https://otlp.nr-data.net:4317) - -3. この環境変数を設定してサービスに名前を付けます。これは、New Relic アカウントでサービスを識別する方法です。 - - * OTEL_SERVICE_NAME=入門-Python - -4. 同じ `getting-started-guides/python/Instrumented/` ディレクトリで、仮想環境を作成してアクティブ化し、必要なライブラリをインストールして、アプリを実行します。 - - * マックOS: - - ``` - python3 -m venv venv - source venv/bin/activate - pip install -r requirements.txt - python3 app.py - ``` - - * パワーシェル: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - pip install -r requirements.txt - python app.py - ``` - -5. 新しいターミナル タブを開き、 `getting-started-guides/python/Instrumented`ディレクトリに切り替え、次のコマンドを実行してアプリケーションへのトラフィックを生成します: - - * マックOS: - - ``` - ./load-generator.sh - ``` - - * パワーシェル: - - ``` - .\load-generator.ps1 - ``` - - - または、ブラウザの次の URL でエンドポイントにアクセスできます: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` 。`INSERT_A_VALUE`を 1 から 90 の値に置き換えます。エラーを生成するには、有効範囲外の整数を挿入します。 - - -6. **[one.newrelic.com](https://one.newrelic.com/all-capabilities) > APM & services**に移動します。 - -7. `getting-started-python`という新しいエンティティ (サービス) をクリックして、UI を調べます。UI で何を探すべきかについてのその他のヒントについて[は、New Relic でデータを表示する](#view-data)を参照してください。 - -8. UI でデータを確認し終わったら、両方のターミナル セッションで `CONTROL+C` を押してアプリケーションをシャットダウンします。 - -## チュートリアル 2: OpenTelemetry Python エージェントを使用してデモ アプリを監視する [#python-agent] - -これは、同じデモ アプリを使用する別のチュートリアルですが、この場合は、OpenTelemetry Python エージェントを使用して、デモ アプリを自動的に監視します。Python ソース コードを変更する必要はありません。エージェントを使用すると、New Relic へのサンプル データのエクスポートをすぐに開始できます。 - -ただし、ログやカスタム メトリクスなど、アプリに関するより深いレベルの情報を取得するには、カスタム インストルメンテーションを追加する必要があることに注意してください。 - -自動インストルメンテーション エージェントは、バイトコードを動的に挿入して、一般的なライブラリやフレームワークからテレメトリをキャプチャする一連の PyPI パッケージです。これを使用して、受信リクエスト、送信 HTTP 呼び出し、データベース呼び出しなどのデータをキャプチャすることもできます。任意の Python 3 アプリケーションに接続できます。 - - - 追加の構成オプションについては [、OpenTelemetry Python エージェントの公式ドキュメントを](https://opentelemetry.io/docs/instrumentation/python/automatic/) 参照してください。 - - -OpenTelemetry Python エージェントを使用してデモ アプリを監視するには: - -1. これら 2 つのコマンドを実行して、デモ アプリケーション リポジトリをダウンロードし、次のディレクトリに移動します。 - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` - -2. 以下の[環境変数の参照セクション](#ref-env-vars)に移動して、エクスポートする必要がある変数を確認してから、これらの手順に戻ります。 - -3. 次に、同じ `getting-started-guides/python/Uninstrumented/` ディレクトリに仮想環境を作成してアクティブ化します。 - - * マックOS: - - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * パワーシェル: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` - -4. これで、必要なライブラリをインストールする準備が整いました。 - - ``` - pip install flask - pip install opentelemetry-instrumentation-flask - pip install opentelemetry-exporter-otlp - pip install opentelemetry-distro - ``` - -5. `getting-started-guides/python/Uninstrumented/`に進み、アプリでエージェントを起動します。 - - * マックOS: - - ``` - opentelemetry-instrument python3 app.py - ``` - - * パワーシェル: - - ``` - opentelemetry-instrument python app.py - ``` - -6. `getting-started-guides/python/Uninstrumented`ディレクトリで新しいターミナルを開き、ロード ジェネレーターを実行して、アプリケーションへのトラフィックを生成します。 - - * マックOS: - - ``` - ./load-generator.sh - ``` - - * パワーシェル: - - ``` - .\load-generator.ps1 - ``` - - - または、ブラウザの次の URL でエンドポイントにアクセスできます: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` 。`INSERT_A_VALUE`を 1 から 90 の値に置き換えます。エラーを生成するには、有効範囲外の整数を挿入します。 - - -7. New Relic にデータを[送信したので、UI でデータを表示する手順を](#view-data)参照してください。 - -8. UI でデータを確認し終わったら、両方のターミナル セッションで `CONTROL+C` を押してアプリケーションをシャットダウンします。 - -## チュートリアル 3: デモ アプリを手動でセットアップする [#manual-instrum] - -前のセクションは、OpenTelemetry Python エージェントを使用した自動インストルメンテーションを調べるのに役立ちました。収集するテレメトリをより詳細に制御したい場合は、このチュートリアルを試して、カスタム インストルメンテーションを追加する方法を学ぶことができます。次に、推奨されるベスト プラクティスを使用して、OpenTelemetry SDK を設定してデータを New Relic にエクスポートする方法を説明します。 - -この手動セットアップで完了する手順は次のとおりです。 - -* [A. デモ アプリケーションをダウンロードする](#download) -* [B. 必要なライブラリをインストールする](#libraries) -* [C. SDKを構成する](#config-sdk) -* [D. インストルメンテーション ライブラリの追加: トレース](#library-traces) -* [E. インストルメンテーション ライブラリの追加: メトリック](#library-metrics) -* [F. インストルメンテーション ライブラリの追加: ログ](#library-logs) -* [G. Flask インストルメンテーションを追加する](#flask-instrum) -* [H. カスタム トレース インストルメンテーション: カスタム スパンを作成する](#cust-span) -* [I. カスタム トレース インストルメンテーション: 例外を記録する](#span-exception) -* [J. カスタム メトリック インストルメンテーション: カスタム メトリック カウンターを追加する](#cust-metrics) -* [K. カスタム ログ インストルメンテーション](#cust-log) -* [L. アプリを実行してトラフィックを生成する](#exercise-app) - -### A. デモ アプリケーションをダウンロードする [#download] - -以下を実行してデモ アプリをダウンロードします。 - -``` -git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git -``` - -### B. 必要なライブラリをインストールする [#libraries] - -必要なライブラリを追加するには: - -1. このチュートリアルの開始点として、インストルメント化されていないアプリのアプリケーション ディレクトリに移動します。このチュートリアルが終わるまでに、コードは `Instrumented` ディレクトリにあるもののようになっているはずです。 - - ``` - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` - -2. `Uninstrumented` ディレクトリに仮想環境を作成してアクティブ化します。 - - * マックOS: - - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * パワーシェル: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` - -3. 以下をインストールします。 - - ``` - pip install opentelemetry-api - pip install opentelemetry-sdk - pip install flask - pip install opentelemetry-instrumentation-logging - pip install opentelemetry-instrumentation-flask - pip install opentelemetry-exporter-otlp - pip install opentelemetry-distro - ``` - -### C. SDKを構成する [#config-sdk] - -1. `app.py`で、以下の強調表示された行を **ファイルの先頭**に追加します。必要に応じて、カスタム属性 `environment` の値を変更します。 - -```python lineHighlight=1-10 -########################## -# OpenTelemetry Settings # -########################## -from opentelemetry.sdk.resources import Resource -import uuid - -OTEL_RESOURCE_ATTRIBUTES = { - "service.instance.id": str(uuid.uuid1()), - "environment": "local" -} - -from flask import Flask, jsonify, request - -app = Flask(__name__) -``` - -2. 以下の [環境変数リファレンス セクション](#ref-env-vars) に移動して、エクスポートする必要がある変数を確認してから、インストルメンテーション ライブラリを追加する次の手順に進みます。 - -### D. インストルメンテーション ライブラリの追加: トレース [#library-traces] - -`app.py`で、追加した `OpenTelemetry Settings` の後に以下を挿入します。 - -```python -########## -# Traces # -########## -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter -from opentelemetry.trace.status import Status, StatusCode - -# Initialize tracing and an exporter that can send data to an OTLP endpoint -# SELECT * FROM Span WHERE instrumentation.provider='opentelemetry' -trace.set_tracer_provider(TracerProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES))) -trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) -``` - -### E. インストルメンテーション ライブラリの追加: メトリック [#library-metrics] - -`app.py` で、ステップ D で追加した `Traces` セクションの後に次の行を追加します。 - -```python -########### -# Metrics # -########### -from opentelemetry import metrics -from opentelemetry.sdk.metrics import MeterProvider -from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter - -# Initialize metering and an exporter that can send data to an OTLP endpoint -# SELECT count(`http.server.active_requests`) FROM Metric FACET `service.name` TIMESERIES -metrics.set_meter_provider(MeterProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES), metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())])) -metrics.get_meter_provider() -fib_counter = metrics.get_meter("opentelemetry.instrumentation.custom").create_counter("fibonacci.invocations", unit="1", description="Measures the number of times the fibonacci method is invoked.") -``` - -### F. インストルメンテーション ライブラリの追加: ログ [#library-logs] - -`app.py`の `Metrics` セクションの後に以下を追加します。これにより、ログ モジュールがインポートされ、 `basicConfig` ログ レベルが `DEBUG`に設定されます。 - -```python -######## -# Logs # - OpenTelemetry Logs are still in the experimental state, so function names may change in the future -######## -import logging -logging.basicConfig(level=logging.DEBUG) - -from opentelemetry import _logs -from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler -from opentelemetry.sdk._logs.export import BatchLogRecordProcessor -from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter - -# Initialize logging and an exporter that can send data to an OTLP endpoint by attaching OTLP handler to root logger -# SELECT * FROM Log WHERE instrumentation.provider='opentelemetry' -_logs.set_logger_provider(LoggerProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES))) -logging.getLogger().addHandler(LoggingHandler(logger_provider=_logs.get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter())))) -``` - -### G. Flask インストルメンテーションを追加する [#flask-instrum] - -`app.py` の `Logs` セクションの後に、以下の強調表示された行を追加します。これは、分散トレースとログインコンテキストのスパンをリンクするのに役立ちます。 - -```python lineHighlight=1-3,5,8 - -##################### -# Flask Application # -##################### -from flask import Flask, jsonify, request -from opentelemetry.instrumentation.flask import FlaskInstrumentor - -app = Flask(__name__) -FlaskInstrumentor().instrument_app(app) -``` - -### H. カスタム トレース インストルメンテーション: カスタム スパンを作成する [#cust-span] - -必要なスパンを作成できます。特定の操作に関する属性でスパンに注釈を付けるのはあなた次第です。設定した属性は、結果や操作のプロパティなど、追跡している特定の操作に関する追加のコンテキストを提供します。 - -`app.py`に、以下の強調表示された行を挿入して、次の処理を行う `/fibonacci` という新しいスパンを開始します。 - -* このメソッドの実行に関するデータをキャプチャします - -* ユーザーのリクエストから n の値を格納する属性を設定します - - ```python lineHighlight=3,8,16 - - @app.route("/fibonacci") - - @trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") - def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - return jsonify(n=x, result=array[x]) - - except AssertionError: - return jsonify({"message": error_message}) - - app.run(host='0.0.0.0', port=8080) - ``` - -### I. カスタム トレース インストルメンテーション: 例外を記録する [#span-exception] - -例外が発生したときに、例外を記録したい場合があります。スパンステータスの設定と併せてこれを行うことをお勧めします。 - -1. 例外が発生したときにスパンのステータス コードを `ERROR` に設定するには、 `Status` モジュールと `StatusCode` モジュールを `opentelemetry.trace.status package`からインポートする必要もあります。以下の強調表示された行を、他のトレース ライブラリを含む `Traces` セクションに追加します。 - -```python lineHighlight=8 -########## -# Traces # -########## -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter -from opentelemetry.trace.status import Status, StatusCode -``` - -2. 次に、以下の強調表示された行を挿入して例外を記録します。この例外は New Relic でスパン イベントとして表示され、スパンのステータスを `ERROR`に設定します。 - -```python lineHighlight=19,20 -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### J. カスタム メトリック インストルメンテーション: カスタム メトリック カウンターを追加する [#cust-metrics] - -メトリックは、個々の測定値を集計に結合し、システム負荷の関数として一定のデータを生成するため、非常に役立つテレメトリ データ タイプです。このデータをスパンと組み合わせて使用すると、傾向を特定し、アプリケーションのランタイム テレメトリを提供できます。また、メトリクスが表す測定値の下位区分を説明するのに役立つ属性でメトリクスに注釈を付けることもできます。 - -OpenTelemetry メトリクス API は、メトリクス SDK によって集計され、アウト オブ プロセスでエクスポートされる測定値を記録する多数の計測器を定義します。器具には次の 2 種類があります。 - -* 同期: これらの計測器は、発生時に測定値を記録します。 -* 非同期: これらの計測器はコールバックを登録します。これはコレクションごとに 1 回だけ呼び出され、関連付けられたコンテキストはありません。 - -1. `app.py`の `Metrics` セクションに以下の強調表示された行を追加してカウンターを作成します。 - -```python lineHighlight=13 -########### -# Metrics # -########### -from opentelemetry import metrics -from opentelemetry.sdk.metrics import MeterProvider -from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter - -# Initialize metering and an exporter that can send data to an OTLP endpoint -# SELECT count(`http.server.active_requests`) FROM Metric FACET `service.name` TIMESERIES -metrics.set_meter_provider(MeterProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES), metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())])) -metrics.get_meter_provider() -fib_counter = metrics.get_meter("opentelemetry.instrumentation.custom").create_counter("fibonacci.invocations", unit="1", description="Measures the number of times the fibonacci method is invoked.") -``` - -2. 次に、作成したカウンターを使用して測定するために、以下の強調表示された行を追加します。 - -* この関数が正常に実行された回数 -* 実行に失敗した回数 - -アプリを再起動するたびにカウンターが 0 にリセットされることに注意してください。 - -```python lineHighlight=16,22 -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - fib_counter.add(1, {"fibonacci.valid.n": "true"}) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - fib_counter.add(1, {"fibonacci.valid.n": "false"}) - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### K. カスタム ログ インストルメンテーション [#cust-log] - -OpenTelemetry Python のログ信号のステータスは、現在 [実験段階](https://github.com/open-telemetry/opentelemetry-python#project-status)です。 - -`app.py`で、以下の強調表示された行を次の行に追加します。 - -* 入力値と出力値の `INFO` レベルのログを記録します。 -* 入力値が有効範囲外の場合、 `ERROR` レベルのログを記録します。 - -```python lineHighlight=17,24 - -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - fib_counter.add(1, {"fibonacci.valid.n": "true"}) - logging.info("Compute fibonacci(" + str(x) + ") = " + str(array[x])) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - fib_counter.add(1, {"fibonacci.valid.n": "false"}) - logging.error("Failed to compute fibonacci(" + str(x) + ")") - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### L. アプリを実行してトラフィックを生成する [#exercise-app] - -New Relic にデータを送信する準備ができました! - -1. ターミナルで、 `getting-started-guides/python/Uninstrumented` ディレクトリにいることを確認し、アプリケーションを実行します。 - - * マックOS: - - ``` - python3 app.py - ``` - - * パワーシェル: - - ``` - python app.py - ``` - -2. `getting-started-guides/python/Uninstrumented` ディレクトリで新しいターミナル タブを開き、ロード ジェネレーターを実行して、アプリケーションへのトラフィックを生成します。 - - * マックOS: - - ``` - ./load-generator.sh - ``` - - * パワーシェル: - - ``` - .\load-generator.ps1 - ``` - - - または、ブラウザの次の URL でエンドポイントにアクセスできます: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` 。`INSERT_A_VALUE`を 1 から 90 の値に置き換えます。エラーを生成するには、有効範囲外の整数を挿入します。 - - -3. New Relic にデータを[送信したので、UI でデータを表示する手順を](#view-data)参照してください。 - -## New Relic でデモ データを表示する [#view-data] - -どのチュートリアルを完了しても、New Relic UI でデータを見つけるための以下のヒントに従うことができます。 - -[「チュートリアル 2: OpenTelemetry Python エージェントを使用してデモ アプリを監視する:」](#python-agent)に従った場合は、より詳細なデータをキャプチャするにはカスタム インストルメンテーションを手動で追加する必要があるため、カスタム データ (カスタム メトリクスやログなど) が表示されないことに注意してください。 - -1. **[one.newrelic.com](https://one.newrelic.com/all-capabilities) > APM & services**に移動します。 -2. `getting-started-python`という名前の新しいエンティティ (サービス) (または任意の名前) をクリックします。 -3. 各データ型のセクションで詳細を確認してください。 - - - Microsoft Windows を使用していて、New Relic アカウントにデータが表示されない場合は、ファイアウォールを通過するトラフィックを許可しているかどうかを確認してください。 - - -### トレース [#traces] - -New Relic で`getting-started-python`エンティティに到達したら: - -1. 左側のペインの**Monitor** \[モニター]セクションで、 **Distributed tracing** \[分散トレース]をクリックし、 `/fibonacci`トレース グループをクリックします。 - - Screenshot showing how to find your trace group - -2. そこから、エラーのあるトレースを見つけてクリックして開きます。 - - Screenshot showing an error in distributed tracing - -3. トレースを開いたら、 `Show in-process spans`をクリックし、結果のスパンをクリックすると、右側に詳細パネルが開きます。ユーザー入力が無効な場合に記録した例外を確認するには、 `View span events`をクリックします。 - - Screenshot of in-process spans - -手動インストルメンテーション チュートリアルを完了した場合、スパンとして記録した例外が New Relic でどのように表示されるかを以下に示します。 - -Screenshot showing an exception as a span event - -スパン属性、スパン名、ステータス コードなど、設定した追加の詳細を表示するには、\[**属性**] タブをクリックします。このペインでは、このガイドで使用したインストルメンテーション ライブラリによって自動的に収集される追加のメタデータと、New Relic によって添付されたメタデータを表示することもできます。 - -Screenshot of the attributes tab - -データの表示の詳細について[は、New Relic UI の OpenTelemetry を](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page)参照してください。 - -### 指標 [#metrics] - -New Relic の `getting-started-python` エンティティに到達すると、カスタム カウンター属性など、収集されたすべてのメトリクスのリストが表示されます。 - -#### メトリクスエクスプローラー [#metrics-explorer] - -これは、メトリックのリストを表示できるツールです。 - -1. 左側のペインで、\[**データ] > \[メトリクス エクスプローラー]**を選択し、\[ `fibonacci.invocations` ] を選択します。 - - Screenshot showing metrics explorer - -2. \[**ディメンション**] で、収集した属性とカスタム メトリックを表示し、 **fibonacci.valid.n**をクリックします。 - - Screenshot showing the total number of invocations of fibonacci function - -詳しくは、 [メトリクス エクスプローラー ビュー](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-metrics-explorer-page)に関するドキュメントをご覧ください。 - -### ログ [#logs] - -ログにアクセスする場所は次のとおりです。 - -Screenshot showing the main logs page - -ターミナルにもログが表示されます。 - -Screenshot showing logs in a terminal - -ログ ビューに戻り、ログを選択すると、ログ メッセージと、関連するスパンやトレース ID などの収集された追加の属性、および New Relic によって挿入されたメタデータが表示されたペインが開きます。 - -Screenshot showing log details with trace - -この小さな青いアイコンをクリックすると、相関分散トレースに移動できます。 - -Screenshot showing how to find correlated trace - -これにより、相関トレースを表示するペインが開き、トレースに関する詳細を表示できます。このページの詳細について[は、UI の OpenTelemetry: 分散トレース ページ](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page/)および[分散トレース UI の理解と使用](/docs/distributed-tracing/ui-data/understand-use-distributed-tracing-ui/)を参照してください。 - -Screenshot showing the trace waterfall from the logs section - -分散トレース ビューから相関ログを見つけることもできます。対応するログを持つトレースを選択すると、それがタブとして示され、ビューを切り替えることなくトレースから直接ログを表示できます。 - -Screenshot showing how to see log details from a trace span - -ログ ビューの詳細については、 [こちら](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-logs-page)をご覧ください。 - -## 参考:環境変数 [#ref-env-vars] - -これは、チュートリアル 2 または 3 を実行している場合にエクスポートする必要がある環境変数のリストです。変数のエクスポートが完了したら、変数リストに続くリンクを使用してチュートリアルに戻ります。 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- OTEL_EXPORTER_OTLP_HEADERS=api-key=YOUR_LICENSE_KEY - - * ヘッダー: これにより、データが送信される New Relic アカウントが決まります。`YOUR_LICENSE_KEY`をあなたの - - - - . -
- OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.nr-data.net:4317](https://otlp.nr-data.net:4317)(米国向け) - - * これは、アプリケーション テレメトリがエクスポートされるエンドポイントです。データを New Relic の OTLP エンドポイントにエクスポートします。EU にいる場合は、次のエンドポイントを使用してください: OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.eu01.nr-data.net:4317](https://otlp.eu01.nr-data.net:4317) -
- OTEL_SERVICE_NAME=入門-Python - - * これは、アプリケーション テレメトリを New Relic のエンティティに関連付ける名前です。このチュートリアルでは`getting-started-python`と呼んでいますが、任意の名前にすることができます。 -
- OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_OWN_ID_HERE - - * `INSERT_YOUR_OWN_ID_HERE`を一意のインスタンス ID に置き換えます。たとえば、 `1234`を使用できます。詳細については、OpenTelemetry の[Resource Semantic Conventions](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service)を参照してください。 -
- OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT=4095 - - * 属性値の最大長に制限を設定すると、 [New Relic の制限](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-attributes/)を超えた場合にスパン データがドロップされるのを防ぐことができます。 -
- OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=DELTA - - * New Relic は、デフォルトの累積ではなく、デルタ一時性のメトリクスをサポートします。 -
- OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=EXPONENTIAL_BUCKET_HISTOGRAM - - * (推奨) ヒストグラム集約: データ圧縮を向上させるために、既定の明示的なバケット ヒストグラムの代わりに指数ヒストグラムを使用します。 -
- OTEL_LOGS_EXPORTER=otlp - - * OTLP 経由のログ エクスポートを有効にします。ログのエクスポートはデフォルトで無効になっています。 -
- OTEL_EXPORTER_OTLP_COMPRESSION=gzip - - * (推奨) gzip 圧縮を設定すると、リクエストごとに送信できるデータ量を最大化できます。最大許容ペイロード サイズは 1MB (10^6 バイト) です。Gzip 圧縮はパフォーマンスが高く、データ出力が低くなります。 -
- OTEL_EXPERIMENTAL_EXPORTER_OTLP_RETRY_ENABLED=真 - - * (推奨) 実験的なエクスポートの再試行を有効にして、インターネットの信頼性の低さに対処します。 -
- OTEL_EXPERIMENTAL_RESOURCE_DISABLED_KEYS=process.command_line - - * (推奨) これにより、多くの場合、New Relic の最大属性長制限を超え、機密情報が含まれている可能性がある`process.command_line`リソース属性が無効になります。 -
-
-
- -上の折りたたみツールにリストされている環境変数をエクスポートした後、チュートリアルに戻ってセットアップを完了します。 - -* [チュートリアル 2: OpenTelemetry Python エージェントを使用してデモ アプリを監視する](#python-agent) -* [チュートリアル 3: デモ アプリを手動でセットアップする](#manual-instrum) - -## 次は何ですか? [#what-next] - -OpenTelemetry インストルメンテーションと SDK 構成を試したので、学んだことを適用して、OpenTelemetry と New Relic を使用して独自のアプリまたはサービスをセットアップできます。詳細については[、OpenTelemetry を使用して独自のアプリまたはサービスをセットアップする](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-set-up-your-app)を参照してください。 \ No newline at end of file diff --git a/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx b/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx deleted file mode 100644 index 8126e28a659..00000000000 --- a/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-go.mdx +++ /dev/null @@ -1,863 +0,0 @@ ---- -title: 'OpenTelemetry 튜토리얼: 샘플 Go 앱 계측' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: 'To test out OpenTelemetry on a sample Go app instead of your own app, consider these two tutorials.' -freshnessValidatedDate: never -translationType: machine ---- - -import openttelemetryPythonIntroImage from 'images/opentelemetry_screenshot-crop_python-intro.webp' - -import opentelemetryPythonFindTraceGroup from 'images/opentelemetry_screenshot-crop_find-trace-group.webp' - -import opentelemetryPythonDistributedTracingError from 'images/opentelemetry_screenshot-crop_python-distributed-tracing-error.webp' - -import opentelemetryPythonInProcessSpans from 'images/opentelemetry_screenshot-crop_python-in-process-spans.webp' - -import opentelemetryPythonExceptiononSpanEvent from 'images/opentelemetry_screenshot-crop_python-exception-on-span-event.webp' - -import opentelemetryPytyhonAttributesTab from 'images/opentelemetry_screenshot-crop_python-attributes-tab.webp' - -import opentelemetryPythonMetricsExplorerMain from 'images/opentelemetry_screenshot-crop_python-metrics-explorer-main.webp' - -import opentelemetryPythonMetricsExplorerDimensions from 'images/opentelemetry_screenshot-crop_python-metrics-explorer-dimensions.webp' - -import opentelemetryPythonMainLogsPage from 'images/opentelemetry_screenshot-full_python-main-logs-page.webp' - -import opentelemetryPythonLogsinTerminal from 'images/opentelemetry_screenshot-full_python-logs-in-terminal.webp' - -import opentelemetryPythonLogDetailsWithTrace from 'images/opentelemetry_screenshot-full_python-log-details-with-trace.webp' - -import opentelemetryPythonTraceRelatedtoLog from 'images/opentelemetry_screenshot-full_python-trace-related-to-log.webp' - -import opentelemetryPythonTraceWaterfallFromLog from 'images/opentelemetry_screenshot-full_python-trace-waterfall-from-log.webp' - -import opentelemetryPythonLogCapturedinTraceSpan from 'images/opentelemetry_screenshot-full_python-log-captured-in-trace-span.webp' - - - - New Relic 플랫폼이 OTLP 데이터로 무엇을 할 수 있는지 알아보려면 Go 튜토리얼을 시도해 보세요. 선택할 수 있는 두 개의 튜토리얼이 있으며 각 튜토리얼은 동일한 데모 앱을 사용합니다. 앱은 피보나치 수열의 n번째 숫자를 계산하고 추적 및 측정항목을 생성합니다. - - 이 자습서를 통해 작업하면 OpenTelemetry 및 New Relic을 사용하여 자신의 앱을 설정하는 데 도움이 되는 기술을 배울 수 있습니다. - - - - Screenshot showing response time, throughput, and error rate - -
- 이러한 자습서를 마치면 다음과 같은 차트에서 스팬 메트릭을 볼 수 있습니다. -
-
-
- -각 자습서는 동일한 데모 앱을 사용하지만 OpenTelemetry 및 New Relic에 익숙해지는 데 도움이 되는 접근 방식이 다릅니다. 관심 있는 옵션을 시도해 보십시오. - -* [튜토리얼 1: 사전 계측된 데모 앱 실행:](#pre-instrum) 이는 일부 데모 데이터를 New Relic으로 보내고 UI에 어떻게 표시되는지 확인하는 가장 빠른 방법입니다. 이 자습서의 데모 앱에는 추적 및 지표를 생성하고 내보내는 [모범 사례를](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-overview/) 따르는 계측 및 SDK 구성이 사전 로드되어 있습니다. 우리 코드를 검사하고 관련 섹션을 자신의 앱에 적용할 수 있습니다. -* [튜토리얼 2: 데모 앱 수동 설정:](#manual-instrum) 이 트랙에서는 소매를 걷어붙이고 자동차 엔진을 만지작거리게 됩니다. 이는 보고되는 원격 분석을 최대한 제어하고 수행 방법에 대한 세부 정보를 확인하려는 경우 취하는 접근 방식입니다. 원격 측정을 캡처하기 위해 데모 앱에 계측을 수동으로 삽입하고 해당 데이터를 New Relic으로 내보내도록 SDK를 구성합니다. - -[OpenTelemetry Go 자동 계측은](https://github.com/open-telemetry/opentelemetry-go-instrumentation) 현재 개발 중이므로 지금은 자습서에 포함되어 있지 않습니다. - - - OTLP를 통해 애플리케이션에서 New Relic으로 데이터를 내보내는 데는 두 가지 선택이 있습니다. - - * 앱에서 직접 - * OpenTelemetry 수집기를 통해 - - 이 가이드에서는 첫 번째 옵션을 다룹니다. 수집기를 통해 데이터를 내보내려면 이 [수집기 설명서](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/collector/opentelemetry-collector-basic/) 에서 자세한 내용을 확인하세요. - - -## 요구 사항 [#requirements] - -시작하기 전에 다음이 있는지 확인하십시오. - -* New Relic 계정: 아직 계정이 없다면 [무료 계정](https://newrelic.com/signup) 에 가입하세요. -* [1.16 이상으로 이동](https://go.dev/doc/install) - -## 튜토리얼 1: 사전 계측된 데모 앱 실행 [#pre-instrum] - -New Relic에 데이터를 보내고 UI에서 보는 것이 어떤 것인지 빠르게 확인할 수 있도록 계측 작업을 수행하려는 경우에 유용한 옵션입니다. - -1. 터미널에서 다음을 실행하여 데모 앱을 복제하고 시작 안내서의 `go/Instrumented` 디렉토리로 이동합니다. - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/go/instrumented - ``` - -2. New Relic 계정으로 데이터를 보내도록 다음 환경 변수를 설정합니다. - - * 당신의 . - - * New Relic 데이터 센터 지역이 US가 아닌 EU인 경우 끝점을 다음으로 설정합니다. `https://otlp.eu01.nr-data.net:4317` - - * OTEL_EXPORTER_OTLP_HEADERS=api-key=INSERT_YOUR_NEW_RELIC_LICENSE_KEY - * OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.nr-data.net:4317](https://otlp.nr-data.net:4317) - -3. 이 환경 변수를 설정하여 서비스 이름을 지정하십시오. 다음은 New Relic 계정에서 서비스를 식별하는 방법입니다. - - * OTEL_SERVICE_NAME=시작-파이썬 - -4. 동일한 `getting-started-guides/python/Instrumented/` 디렉토리에서 가상 환경을 생성 및 활성화하고 필요한 라이브러리를 설치한 후 앱을 실행합니다. - - * 맥 OS: - - ``` - python3 -m venv venv - source venv/bin/activate - pip install -r requirements.txt - python3 app.py - ``` - - * 파워셸: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - pip install -r requirements.txt - python app.py - ``` - -5. 새 터미널 탭을 열고 `getting-started-guides/python/Instrumented` 디렉터리로 전환한 후 다음 명령을 실행하여 애플리케이션에 대한 일부 트래픽을 생성합니다. - - * 맥 OS: - - ``` - ./load-generator.sh - ``` - - * 파워셸: - - ``` - .\load-generator.ps1 - ``` - - - 또는 다음 URL에서 브라우저의 엔드포인트에 도달할 수 있습니다: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` . `INSERT_A_VALUE` 을 1에서 90 사이의 값으로 바꿉니다. 오류를 생성하려면 유효한 범위 밖의 정수를 삽입하십시오. - - -6. **[one.newrelic.com](https://one.newrelic.com/all-capabilities) > APM & services** 로 이동합니다. - -7. `getting-started-python` 라는 새 항목(서비스)을 클릭하고 UI를 탐색합니다. UI에서 무엇을 찾아야 하는지에 대한 추가 팁은 [New Relic에서 데이터 보기](#view-data) 를 참조하십시오. - -8. UI에서 데이터 확인을 마치면 두 터미널 세션에서 `CONTROL+C` 눌러 애플리케이션을 종료합니다. - -## 자습서 2: OpenTelemetry Python 에이전트를 사용하여 데모 앱 모니터링 [#python-agent] - -다음은 동일한 데모 앱을 사용하는 다른 자습서이지만 이 경우 OpenTelemetry Python 에이전트를 사용하여 데모 앱을 자동으로 모니터링합니다. Python 소스 코드를 수정할 필요가 없습니다. 에이전트를 사용하면 샘플 데이터를 New Relic으로 빠르게 내보낼 수 있습니다. - -그러나 로그 및 사용자 정의 메트릭과 같은 앱에 대한 더 깊은 수준의 정보를 캡처하려면 사용자 정의 계측을 추가해야 합니다. - -자동 계측 에이전트는 널리 사용되는 라이브러리 및 프레임워크에서 원격 분석을 캡처하기 위해 바이트 코드를 동적으로 주입하는 시리즈 PyPI 패키지입니다. 인바운드 요청, 아웃바운드 HTTP 호출 및 데이터베이스 호출과 같은 데이터를 캡처하는 데 사용할 수도 있습니다. 모든 Python 3 응용 프로그램에 연결할 수 있습니다. - - - 추가 구성 옵션은 [공식 OpenTelemetry Python 에이전트 설명서를](https://opentelemetry.io/docs/instrumentation/python/automatic/) 참조하세요. - - -OpenTelemetry Python 에이전트로 데모 앱을 모니터링하려면: - -1. 이 두 명령을 실행하여 데모 애플리케이션 리포지토리를 다운로드하고 다음 디렉터리로 변경합니다. - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` - -2. 아래의 [환경 변수 참조 섹션](#ref-env-vars) 으로 이동하여 내보내야 하는 변수를 확인한 다음 이 단계로 돌아갑니다. - -3. 그런 다음 동일한 `getting-started-guides/python/Uninstrumented/` 디렉토리에서 가상 환경을 만들고 활성화합니다. - - * 맥 OS: - - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * 파워셸: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` - -4. 이제 필요한 라이브러리를 설치할 준비가 되었습니다. - - ``` - pip install flask - pip install opentelemetry-instrumentation-flask - pip install opentelemetry-exporter-otlp - pip install opentelemetry-distro - ``` - -5. 앱으로 에이전트를 시작하려면 `getting-started-guides/python/Uninstrumented/` 에서 계속합니다. - - * 맥 OS: - - ``` - opentelemetry-instrument python3 app.py - ``` - - * 파워셸: - - ``` - opentelemetry-instrument python app.py - ``` - -6. `getting-started-guides/python/Uninstrumented` 디렉터리에서 새 터미널을 열고 부하 생성기를 실행하여 애플리케이션에 대한 트래픽을 생성합니다. - - * 맥 OS: - - ``` - ./load-generator.sh - ``` - - * 파워셸: - - ``` - .\load-generator.ps1 - ``` - - - 또는 다음 URL에서 브라우저의 엔드포인트에 도달할 수 있습니다: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` . `INSERT_A_VALUE` 을 1에서 90 사이의 값으로 바꿉니다. 오류를 생성하려면 유효한 범위 밖의 정수를 삽입하십시오. - - -7. 일부 데이터를 New Relic에 전송했으므로 이제 [UI에서 데이터 보기에 대한 지침을](#view-data) 참조하십시오. - -8. UI에서 데이터 확인을 마치면 두 터미널 세션에서 `CONTROL+C` 눌러 애플리케이션을 종료합니다. - -## 자습서 3: 수동으로 데모 앱 설정 [#manual-instrum] - -이전 섹션에서는 OpenTelemetry Python 에이전트를 사용한 자동 계측을 살펴보는 데 도움이 되었습니다. 수집하는 원격 분석에 대해 더 많은 제어를 원하는 경우 이 자습서를 시도하여 사용자 지정 계측을 추가하는 방법을 배울 수 있습니다. 그런 다음 권장 모범 사례를 사용하여 데이터를 New Relic으로 내보내도록 OpenTelemetry SDK를 구성하는 방법을 살펴봅니다. - -이 수동 설정을 위해 완료할 단계는 다음과 같습니다. - -* [A. 데모 애플리케이션 다운로드](#download) -* [B. 필요한 라이브러리 설치](#libraries) -* [C. SDK 구성](#config-sdk) -* [D. 계측 라이브러리 추가: 추적](#library-traces) -* [E. 계측 라이브러리 추가: 메트릭](#library-metrics) -* [F. 계측 라이브러리 추가: 로그](#library-logs) -* [G. Flask 계측 추가](#flask-instrum) -* [H. 사용자 지정 추적 계측: 사용자 지정 범위 만들기](#cust-span) -* [I. 사용자 지정 추적 계측: 예외 기록](#span-exception) -* [J. 사용자 지정 메트릭 계측: 사용자 지정 메트릭 카운터 추가](#cust-metrics) -* [K. 사용자 지정 로그 계측](#cust-log) -* [L. 일부 트래픽을 생성하도록 앱을 실행합니다.](#exercise-app) - -### A. 데모 애플리케이션 다운로드 [#download] - -데모 앱을 다운로드하려면 다음을 실행하십시오. - -``` -git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git -``` - -### B. 필요한 라이브러리 설치 [#libraries] - -필요한 라이브러리를 추가하려면: - -1. 이 자습서의 시작점으로 계측되지 않은 앱의 애플리케이션 디렉터리로 이동합니다. 이 튜토리얼이 끝나면 코드는 `Instrumented` 디렉토리에 있는 것과 같아야 합니다. - - ``` - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` - -2. `Uninstrumented` 디렉터리에서 가상 환경을 만들고 활성화합니다. - - * 맥 OS: - - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * 파워셸: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` - -3. 다음을 설치합니다. - - ``` - pip install opentelemetry-api - pip install opentelemetry-sdk - pip install flask - pip install opentelemetry-instrumentation-logging - pip install opentelemetry-instrumentation-flask - pip install opentelemetry-exporter-otlp - pip install opentelemetry-distro - ``` - -### C. SDK 구성 [#config-sdk] - -1. `app.py`에서 아래 강조 표시된 줄을 **파일 상단**에 추가합니다. 필요에 따라 사용자 정의 속성 `environment` 의 값을 변경하십시오. - -```python lineHighlight=1-10 -########################## -# OpenTelemetry Settings # -########################## -from opentelemetry.sdk.resources import Resource -import uuid - -OTEL_RESOURCE_ATTRIBUTES = { - "service.instance.id": str(uuid.uuid1()), - "environment": "local" -} - -from flask import Flask, jsonify, request - -app = Flask(__name__) -``` - -2. 아래의 [환경 변수 참조 섹션](#ref-env-vars) 으로 이동하여 내보내야 하는 변수를 확인한 후 다음 단계로 이동하여 계측 라이브러리를 추가하십시오. - -### D. 계측 라이브러리 추가: 추적 [#library-traces] - -`app.py`에서 추가한 `OpenTelemetry Settings` 뒤에 다음을 삽입합니다. - -```python -########## -# Traces # -########## -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter -from opentelemetry.trace.status import Status, StatusCode - -# Initialize tracing and an exporter that can send data to an OTLP endpoint -# SELECT * FROM Span WHERE instrumentation.provider='opentelemetry' -trace.set_tracer_provider(TracerProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES))) -trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) -``` - -### E. 계측 라이브러리 추가: 메트릭 [#library-metrics] - -`app.py` 에서 D단계에서 추가한 `Traces` 섹션 뒤에 다음을 추가합니다. - -```python -########### -# Metrics # -########### -from opentelemetry import metrics -from opentelemetry.sdk.metrics import MeterProvider -from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter - -# Initialize metering and an exporter that can send data to an OTLP endpoint -# SELECT count(`http.server.active_requests`) FROM Metric FACET `service.name` TIMESERIES -metrics.set_meter_provider(MeterProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES), metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())])) -metrics.get_meter_provider() -fib_counter = metrics.get_meter("opentelemetry.instrumentation.custom").create_counter("fibonacci.invocations", unit="1", description="Measures the number of times the fibonacci method is invoked.") -``` - -### F. 계측 라이브러리 추가: 로그 [#library-logs] - -`app.py`에서 `Metrics` 섹션 뒤에 다음을 추가합니다. 이는 로깅 모듈을 가져오고 `basicConfig` 로깅 수준을 `DEBUG`로 설정합니다. - -```python -######## -# Logs # - OpenTelemetry Logs are still in the experimental state, so function names may change in the future -######## -import logging -logging.basicConfig(level=logging.DEBUG) - -from opentelemetry import _logs -from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler -from opentelemetry.sdk._logs.export import BatchLogRecordProcessor -from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter - -# Initialize logging and an exporter that can send data to an OTLP endpoint by attaching OTLP handler to root logger -# SELECT * FROM Log WHERE instrumentation.provider='opentelemetry' -_logs.set_logger_provider(LoggerProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES))) -logging.getLogger().addHandler(LoggingHandler(logger_provider=_logs.get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter())))) -``` - -### G. Flask 계측 추가 [#flask-instrum] - -`app.py` 에서 `Logs` 섹션 뒤에 아래 강조표시된 줄을 추가합니다. 이것은 분산 추적 및 로그인 컨텍스트에 대한 연결 범위에 도움이 됩니다. - -```python lineHighlight=1-3,5,8 - -##################### -# Flask Application # -##################### -from flask import Flask, jsonify, request -from opentelemetry.instrumentation.flask import FlaskInstrumentor - -app = Flask(__name__) -FlaskInstrumentor().instrument_app(app) -``` - -### H. 사용자 지정 추적 계측: 사용자 지정 범위 만들기 [#cust-span] - -원하는 스팬은 무엇이든 만들 수 있으며 특정 작업에 대한 속성으로 스팬에 주석을 추가하는 것은 사용자의 몫입니다. 설정한 속성은 결과 또는 작업 속성과 같이 추적 중인 특정 작업에 대한 추가 컨텍스트를 제공합니다. - -`app.py`에서 아래에 강조표시된 줄을 삽입하여 다음을 수행하는 `/fibonacci` 라는 새 스팬을 시작합니다. - -* 이 메서드의 실행에 대한 데이터를 캡처합니다. - -* 사용자 요청에서 n 값을 저장하는 속성을 설정합니다. - - ```python lineHighlight=3,8,16 - - @app.route("/fibonacci") - - @trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") - def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - return jsonify(n=x, result=array[x]) - - except AssertionError: - return jsonify({"message": error_message}) - - app.run(host='0.0.0.0', port=8080) - ``` - -### I. 사용자 지정 추적 계측: 예외 기록 [#span-exception] - -예외가 발생하면 기록할 수 있습니다. 스팬 상태 설정과 함께 이 작업을 수행하는 것이 좋습니다. - -1. 예외가 발생할 때 스팬의 상태 코드를 `ERROR` 로 설정하려면 `opentelemetry.trace.status package`에서 `Status` 및 `StatusCode` 모듈도 가져와야 합니다. 다른 추적 라이브러리가 있는 `Traces` 섹션에 아래 강조 표시된 줄을 추가합니다. - -```python lineHighlight=8 -########## -# Traces # -########## -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter -from opentelemetry.trace.status import Status, StatusCode -``` - -2. 다음으로 아래에 강조 표시된 줄을 삽입하여 New Relic에서 스팬 이벤트로 표시되는 예외를 기록하고 스팬 상태를 `ERROR`로 설정합니다. - -```python lineHighlight=19,20 -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### J. 사용자 지정 메트릭 계측: 사용자 지정 메트릭 카운터 추가 [#cust-metrics] - -메트릭은 개별 측정을 집계로 결합하고 시스템 부하의 함수로 일정한 데이터를 생성하기 때문에 정말 유용한 원격 분석 데이터 유형입니다. 이 데이터를 스팬과 함께 사용하여 추세를 파악하고 애플리케이션 런타임 원격 분석을 제공할 수 있습니다. 메트릭이 나타내는 측정의 하위 구분을 설명하는 데 도움이 되는 속성으로 메트릭에 주석을 달 수도 있습니다. - -OpenTelemetry 메트릭 API는 메트릭 SDK에서 집계하고 외부 프로세스로 내보낸 측정값을 기록하는 여러 계측기를 정의합니다. 악기에는 두 가지 유형이 있습니다. - -* 동기식: 이 계측기는 측정이 발생하는 대로 기록합니다. -* 비동기식: 이러한 도구는 컬렉션당 한 번만 호출되고 관련 컨텍스트가 없는 콜백을 등록합니다. - -1. `app.py`에서 아래의 `Metrics` 섹션에 강조 표시된 줄을 추가하여 카운터를 만듭니다. - -```python lineHighlight=13 -########### -# Metrics # -########### -from opentelemetry import metrics -from opentelemetry.sdk.metrics import MeterProvider -from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter - -# Initialize metering and an exporter that can send data to an OTLP endpoint -# SELECT count(`http.server.active_requests`) FROM Metric FACET `service.name` TIMESERIES -metrics.set_meter_provider(MeterProvider(resource=Resource.create(OTEL_RESOURCE_ATTRIBUTES), metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())])) -metrics.get_meter_provider() -fib_counter = metrics.get_meter("opentelemetry.instrumentation.custom").create_counter("fibonacci.invocations", unit="1", description="Measures the number of times the fibonacci method is invoked.") -``` - -2. 다음으로 측정을 위해 방금 만든 카운터를 사용하려면 아래에 강조 표시된 줄을 추가합니다. - -* 이 함수가 성공적으로 실행되는 횟수 -* 실행에 실패한 횟수 - -앱을 다시 시작할 때마다 카운터가 0으로 재설정됩니다. - -```python lineHighlight=16,22 -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - fib_counter.add(1, {"fibonacci.valid.n": "true"}) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - fib_counter.add(1, {"fibonacci.valid.n": "false"}) - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### K. 사용자 지정 로그 계측 [#cust-log] - -OpenTelemetry Python의 로그 신호 상태는 현재 [실험적](https://github.com/open-telemetry/opentelemetry-python#project-status)입니다. - -`app.py`에서 아래 강조 표시된 줄을 다음에 추가합니다. - -* 입력 및 출력 값에 대한 `INFO` 수준 로그를 기록합니다. -* 입력 값이 유효한 범위를 벗어나면 `ERROR` 수준 로그를 기록합니다. - -```python lineHighlight=17,24 - -@app.route("/fibonacci") -@trace.get_tracer("opentelemetry.instrumentation.custom").start_as_current_span("/fibonacci") -def fibonacci(): - args = request.args - x = int(args.get("n")) - error_message = "n must be 1 <= n <= 90." - trace.get_current_span().set_attribute("fibonacci.n", x) - - try: - assert 1 <= x <= 90 - array = [0, 1] - for n in range(2, x + 1): - array.append(array[n - 1] + array[n - 2]) - - trace.get_current_span().set_attribute("fibonacci.result", array[x]) - fib_counter.add(1, {"fibonacci.valid.n": "true"}) - logging.info("Compute fibonacci(" + str(x) + ") = " + str(array[x])) - return jsonify(n=x, result=array[x]) - - except AssertionError: - trace.get_current_span().record_exception(exception=Exception, attributes={"exception.type": "AssertionError", "exception.message": error_message}) - trace.get_current_span().set_status(Status(StatusCode.ERROR, error_message)) - fib_counter.add(1, {"fibonacci.valid.n": "false"}) - logging.error("Failed to compute fibonacci(" + str(x) + ")") - return jsonify({"message": error_message}) - -app.run(host='0.0.0.0', port=8080) -``` - -### L. 일부 트래픽을 생성하도록 앱을 실행합니다. [#exercise-app] - -New Relic에 일부 데이터를 보낼 준비가 되었습니다! - -1. 터미널에서 `getting-started-guides/python/Uninstrumented` 디렉토리에 있는지 확인한 다음 애플리케이션을 실행합니다. - - * MacOS: - - ``` - python3 app.py - ``` - - * 파워셸: - - ``` - python app.py - ``` - -2. `getting-started-guides/python/Uninstrumented` 디렉토리에서 새 터미널 탭을 열고 부하 생성기를 실행하여 애플리케이션에 대한 트래픽을 생성합니다. - - * MacOS: - - ``` - ./load-generator.sh - ``` - - * 파워셸: - - ``` - .\load-generator.ps1 - ``` - - - 또는 다음 URL에서 브라우저의 엔드포인트에 도달할 수 있습니다: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` . `INSERT_A_VALUE` 을 1에서 90 사이의 값으로 바꿉니다. 오류를 생성하려면 유효한 범위 밖의 정수를 삽입하십시오. - - -3. 일부 데이터를 New Relic에 전송했으므로 이제 [UI에서 데이터 보기에 대한 지침을](#view-data) 참조하십시오. - -## New Relic에서 데모 데이터 보기 [#view-data] - -어떤 튜토리얼을 완료했는지에 관계없이 New Relic UI에서 데이터를 찾기 위한 아래 팁을 따를 수 있습니다. - -[자습서 2: OpenTelemetry Python 에이전트를 사용하여 데모 앱 모니터링: 을](#python-agent)따랐다면 더 세분화된 데이터를 캡처하기 위해 사용자 지정 계측을 수동으로 추가해야 하므로 사용자 지정 데이터(예: 사용자 지정 메트릭 및 로그)가 표시되지 않습니다. - -1. **[one.newrelic.com](https://one.newrelic.com/all-capabilities) > APM & services** 로 이동합니다. -2. `getting-started-python` (또는 제공한 이름)라는 새 항목(서비스)을 클릭합니다. -3. 각 데이터 유형에 대한 섹션에서 세부 정보를 확인하십시오. - - - Microsoft Windows를 사용 중이고 New Relic 계정에 데이터가 표시되지 않으면 방화벽을 통한 트래픽을 허용했는지 확인하십시오. - - -### 트레이스 [#traces] - -New Relic에서 `getting-started-python` 엔티티에 도달하면: - -1. 왼쪽 창의 **Monitor** \[모니터] 섹션에서 **Distributed tracing** \[분산 추적을] 클릭한 다음 `/fibonacci` 추적 그룹을 클릭합니다. - - Screenshot showing how to find your trace group - -2. 거기에서 오류가 있는 트레이스를 찾아 클릭하여 엽니다. - - Screenshot showing an error in distributed tracing - -3. 트레이스가 열려 있으면 `Show in-process spans` 클릭한 다음 결과 범위를 클릭하면 오른쪽에 세부정보 패널이 열립니다. 사용자 입력이 유효하지 않을 때 기록한 예외를 보려면 `View span events` 클릭하십시오. - - Screenshot of in-process spans - -수동 계측 자습서를 완료한 경우 범위로 기록한 예외가 New Relic에서 다음과 같이 표시됩니다. - -Screenshot showing an exception as a span event - -스팬 속성, 스팬 이름 및 상태 코드와 같이 설정한 추가 세부 정보를 보려면 **속성** 탭을 클릭하십시오. 또한 이 창에서는 이 가이드에서 사용한 계측 라이브러리에서 자동으로 수집한 추가 메타데이터와 New Relic에서 첨부한 메타데이터를 볼 수 있습니다. - -Screenshot of the attributes tab - -데이터 보기에 대한 자세한 내용은 [New Relic UI의 OpenTelemetry를](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page) 참조하십시오. - -### 메트릭 [#metrics] - -New Relic에서 `getting-started-python` 엔티티에 도달하면 사용자 정의 카운터 속성과 같은 수집된 모든 메트릭 목록을 볼 수 있습니다. - -#### 측정항목 탐색기 [#metrics-explorer] - -메트릭 목록을 볼 수 있는 도구입니다. - -1. 왼쪽 창에서 **Data > Metrics explorer** 를 선택한 다음 `fibonacci.invocations` 를 선택합니다. - - Screenshot showing metrics explorer - -2. **차원** 아래에서 사용자 정의 메트릭과 함께 수집한 속성을 확인한 다음 **fibonacci.valid.n** 을 클릭하십시오. - - Screenshot showing the total number of invocations of fibonacci function - -[메트릭 탐색기 보기](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-metrics-explorer-page) 에 대한 설명서에서 자세히 알아보세요. - -### 로그 [#logs] - -로그에 액세스할 수 있는 위치는 다음과 같습니다. - -Screenshot showing the main logs page - -또한 터미널에 로그가 표시됩니다. - -Screenshot showing logs in a terminal - -로그 보기로 돌아가서 로그를 선택하면 로그 메시지와 수집된 추가 속성(예: 관련 스팬 및 트레이스 ID, New Relic에서 삽입한 메타데이터)이 있는 창이 열립니다. - -Screenshot showing log details with trace - -이 작은 파란색 아이콘을 클릭하여 상관 분산 추적으로 이동할 수 있습니다. - -Screenshot showing how to find correlated trace - -그러면 추적에 대한 자세한 정보를 볼 수 있는 상관 추적을 표시하는 창이 열립니다. 이 페이지에 대한 자세한 내용 [은 UI의 OpenTelemetry: 분산 추적 페이지](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page/) 및 [분산 추적 UI 이해 및 사용](/docs/distributed-tracing/ui-data/understand-use-distributed-tracing-ui/) 을 참조하세요. - -Screenshot showing the trace waterfall from the logs section - -분산 추적 보기에서 상관 로그를 찾을 수도 있습니다. 해당 로그가 있는 추적을 선택하면 해당 로그가 탭으로 표시되며 보기를 전환하지 않고도 추적에서 직접 로그를 볼 수 있습니다. - -Screenshot showing how to see log details from a trace span - -[여기](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-logs-page) 에서 로그 보기에 대해 자세히 알아보세요. - -## 참조: 환경 변수 [#ref-env-vars] - -튜토리얼 2 또는 3을 수행하는 경우 내보내야 하는 환경 변수 목록입니다. 변수 내보내기를 완료한 후 변수 목록 다음에 오는 링크를 사용하여 자습서로 돌아갑니다. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- OTEL_EXPORTER_OTLP_HEADERS=api-key=YOUR_LICENSE_KEY - - * 헤더: 데이터를 보낼 New Relic 계정을 결정합니다. `YOUR_LICENSE_KEY` (를) - - - - . -
- OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.nr-data.net:4317](https://otlp.nr-data.net:4317) (미국의 경우) - - * 애플리케이션 원격 분석을 내보낼 엔드포인트입니다. New Relic의 OTLP 끝점으로 데이터를 내보냅니다. EU에 있는 경우 다음 엔드포인트를 사용하십시오. OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.eu01.nr-data.net:4317](https://otlp.eu01.nr-data.net:4317) -
- OTEL_SERVICE_NAME=시작-파이썬 - - * 애플리케이션 원격 측정을 New Relic의 엔터티와 연결하는 이름입니다. 이 가이드에서는 이를 `getting-started-python` 이라고 부르지만 원하는 대로 이름을 지정할 수 있습니다. -
- OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_OWN_ID_HERE - - * `INSERT_YOUR_OWN_ID_HERE` 를 고유한 인스턴스 ID로 바꿉니다. 예를 들어 `1234` 을 사용할 수 있습니다. 자세한 내용은 OpenTelemetry의 [리소스 의미 규칙](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service) 을 참조하십시오. -
- OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT=4095 - - * 최대 속성 값 길이에 제한을 설정하면 범위 데이터가 [New Relic 제한](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-attributes/) 을 초과하는 경우 삭제되지 않습니다. -
- OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=DELTA - - * New Relic은 누적의 기본값 대신 델타 시간성의 메트릭을 지원합니다. -
- OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=EXPONENTIAL_BUCKET_HISTOGRAM - - * (권장) 히스토그램 집계: 더 나은 데이터 압축을 위해 기본 명시적 버킷 히스토그램 대신 지수 히스토그램을 사용합니다. -
- OTEL_LOGS_EXPORTER=otlp - - * OTLP를 통한 로그 내보내기를 활성화합니다. 로그 내보내기는 기본적으로 비활성화되어 있습니다. -
- OTEL_EXPORTER_OTLP_COMPRESSION=gzip - - * (권장) gzip 압축을 설정하면 요청당 보낼 수 있는 데이터의 양을 최대화할 수 있습니다. 허용되는 최대 페이로드 크기는 1MB(10^6바이트)입니다. Gzip 압축은 성능이 우수하고 데이터 유출을 낮춥니다. -
- OTEL_EXPERIMENTAL_EXPORTER_OTLP_RETRY_ENABLED=참 - - * (권장) 인터넷의 불안정성에 대처하는 데 도움이 되도록 실험적인 내보내기 재시도를 활성화합니다. -
- OTEL_EXPERIMENTAL_RESOURCE_DISABLED_KEYS=process.command_line - - * (권장) 이것은 종종 New Relic 최대 속성 길이 제한을 초과하고 민감한 정보를 포함할 수 있는 `process.command_line` 자원 속성을 비활성화합니다. -
-
-
- -위 축소기에 나열된 환경 변수를 내보낸 후 자습서로 돌아가서 설정을 완료합니다. - -* [자습서 2: OpenTelemetry Python 에이전트를 사용하여 데모 앱 모니터링](#python-agent) -* [자습서 3: 수동으로 데모 앱 설정](#manual-instrum) - -## 다음은 뭐지? [#what-next] - -이제 OpenTelemetry 계측 및 SDK 구성을 실험했으므로 배운 내용을 적용하여 OpenTelemetry 및 New Relic을 사용하여 자체 앱 또는 서비스를 설정할 수 있습니다. 자세한 내용 [은 OpenTelemetry로 자체 앱 또는 서비스 설정을](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-set-up-your-app) 참조하십시오. \ No newline at end of file