From 2d5678b4f17e75a675f843dd30507b89d751399d Mon Sep 17 00:00:00 2001 From: Alan West <3676547+alanwest@users.noreply.github.com> Date: Mon, 20 May 2024 15:02:23 -0700 Subject: [PATCH 01/11] Simplify OpenTelemetry APM getting started documentation --- .../opentelemetry-apm-intro.mdx | 101 +- .../apm-monitoring/opentelemetry-apm-java.mdx | 1119 ----------------- .../opentelemetry-apm-python.mdx | 839 ------------ src/nav/opentelemetry.yml | 4 - 4 files changed, 64 insertions(+), 1999 deletions(-) delete mode 100644 src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx delete mode 100644 src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx index 7d6a0a12065..792d188974b 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx @@ -16,64 +16,91 @@ import moreintegrationsNativeOtlpNoCollector from 'images/more-integrations_diag import moreintegrationsNativeOtlpWithCollector from 'images/more-integrations_diagram_native-otlp-with-collector.webp' -OpenTelemetry provides general purpose APIs and SDKs for collecting, processing, and exporting observability data. One of the most popular use cases for these APIs and SDKs is APM monitoring, where instrumentation is installed to monitor an app or service. +OpenTelemetry provides general purpose APIs and SDKs for collecting, processing, +and exporting observability data. One of the most popular use cases for these +APIs and SDKs is APM monitoring, where instrumentation is installed to monitor +an app or service. -This page describes common set up steps for OpenTelemetry based APM monitoring with New Relic. For some languages, we provide working code examples: - -* [Java example](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java) -* [Python example](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python) +This page describes common set up steps for OpenTelemetry based APM monitoring +with New Relic. ## Before you start [#prereqs] -* If you haven't already done so, sign up for a free [New Relic account](https://newrelic.com/signup). -* Get the [license key](https://one.newrelic.com/launcher/api-keys-ui.launcher) for the New Relic account to which you want to report data. +* [Sign up](https://newrelic.com/signup) for a New Relic account. +* Get the [license key](https://one.newrelic.com/launcher/api-keys-ui.launcher) + for the New Relic account to which you want to report data. ## Instrument your app or service with OpenTelemetry [#instrument] -OpenTelemetry provides [language-specific APIs and SDKs](https://opentelemetry.io/docs/languages/), and [instrumentation](https://opentelemetry.io/docs/concepts/instrumentation/) for popular libraries and frameworks which utilizes the APIs. The mechanism for installing instrumentation varies: some languages support [zero code](https://opentelemetry.io/docs/concepts/instrumentation/zero-code/) (or automatically installed) instrumentation akin to New Relic agents, others support [instrumentation libraries](https://opentelemetry.io/docs/concepts/instrumentation/libraries/) which require some manual installation, and some libraries and frameworks are natively instrumented with OpenTelemetry. - -For details about what instrumentation is available, and installation instructions, please see the relevant [OpenTelemetry language documentation](https://opentelemetry.io/docs/languages/). - - - -## Configure export to New Relic via OTLP [#configure-oltp-export] - -New Relic supports [native OTLP ingest](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/). +OpenTelemetry provides +[language-specific APIs and SDKs](https://opentelemetry.io/docs/languages/) +for instrumenting applications. Most languages provide a rich set of +[instrumentation](https://opentelemetry.io/docs/concepts/instrumentation/) +for popular libraries and frameworks. + +To help you get started, we offer a simple example application in a variety of +languages. For each language, the application is built using web framework popular +to that language. The examples demonstrate how to configure: + +1. The service name which will display in New Relic. +2. The OpenTelemetry Protocol (OTLP) exporter to send data to New Relic. +3. Additional recommended settings to optimize OpenTelemetry for the best New + Relic experience. + + + -There are two options for exporting OpenTelemetry APM data to New Relic via OTLP: + -* **Directly from your app.** Each OpenTelemetry language SDK comes packaged with OTLP exporters. Configure the SDK to export via OTLP. Consult relevant OpenTelemetry documentation and ensure [configuration matches New Relic OTLP requirements](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/). + - Diagram showing a direct export to New Relic to your app -
- The OTLP exporter in your app or service can export directly to the New Relic OTLP endpoint. -
-* **Export from an OpenTelemetry Collector.** Configure the app to export to an intermediate OpenTelemetry collector, and from the collector to New Relic via OTLP. Ensure the collector's OTLP exporter [configuration matches New Relic OTLP requirements](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/). See [Collector for Processing](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/collector-pipeline/opentelemetry-collector-pipeline-intro) for more details. + - Diagram showing the export to New Relic from a collector -
- The OpenTelemetry Collector can act as a gateway to process APM telemetry data before sending to New Relic via OTLP. -
-
+ - -## Configure your app with APM resource attributes [#configure-resource] + -New Relic requires that apps and services monitored with OpenTelemetry contain certain [resource attributes](https://opentelemetry.io/docs/concepts/resources/) like `service.name` and `telemetry.sdk.name`. Others like `service.instance.id` are recommended. See [Service entities](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-resources/#services) for more information. +For more information about what instrumentation is available and more advanced +scenarios, please see the relevant +[OpenTelemetry language documentation](https://opentelemetry.io/docs/languages/). diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx deleted file mode 100644 index d6315ea036f..00000000000 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx +++ /dev/null @@ -1,1119 +0,0 @@ ---- -title: 'OpenTelemetry tutorials: Instrument a sample Java app' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: To test out OpenTelemetry on a sample app instead of your own app, consider these three tutorials. -translate: - - kr -freshnessValidatedDate: never -redirects: - - /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-java/ ---- - -import opentelemetrySpringBootASCIIDisplay from 'images/opentelemetry_screenshot-crop_Spring-Boot-ASCII-display.webp' - -import opentelemetryMainDistributedTracingPage from 'images/opentelemetry_screenshot-crop_main-distributed-tracing-page.webp' - -import opentelemetryDistributedTracingError from 'images/opentelemetry_screenshot-crop_distributed-tracing-error.webp' - -import opentelemetryInProcessSpans from 'images/opentelemetry_screenshot-crop_in-process-spans.webp' - -import opentelemetryExceptiononSpanEvent from 'images/opentelemetry_screenshot-crop_exception-on-span-event.webp' - -import opentelemetryAttributesTab from 'images/opentelemetry_screenshot-crop_attributes-tab.webp' - -import opentelemetryMetricsExplorerMain from 'images/opentelemetry_screenshot-crop_metrics-explorer-main.webp' - -import opentelemetryMetricsExplorerDimensions from 'images/opentelemetry_screenshot-crop_metrics-explorer-dimensions.webp' - -import opentelemetryJvmsPageMain from 'images/opentelemetry_screenshot-crop_jvms-page-main.webp' - -import opentelemetryCompareJvmInstances from 'images/opentelemetry_screenshot-full_compare-jvm-instances.webp' - -import opentelemetryJvmColorCodedComparison from 'images/opentelemetry_screenshot-full_jvm-color-coded-comparison.webp' - -import opentelemetryMainLogsPage from 'images/opentelemetry_screenshot-full_main-logs-page.webp' - -import opentelemetryLogsinTerminal from 'images/opentelemetry_screenshot-full_logs-in-terminal.webp' - -import opentelemetryLogDetailsWithTrace from 'images/opentelemetry_screenshot-full_log-details-with-trace.webp' - -import opentelemetryTraceRelatedtoLog from 'images/opentelemetry_screenshot-full_trace-related-to-log.webp' - -import opentelemetryTraceWaterfallFromLog from 'images/opentelemetry_screenshot-full_trace-waterfall-from-log.webp' - -import opentelemetryLogCapturedinTraceSpan from 'images/opentelemetry_screenshot-full_log-captured-in-trace-span.webp' - -import opentelemetryTraceDurationDemoChart from 'images/opentelemetry_screenshot-crop_jvm-metric-charts.webp' - - - - -Try out these Java tutorials to see what the New Relic platform can do with your OTLP data. We have three tutorials you can choose from, each one using the same demo Spring app. The app will calculate the nth number in the Fibonacci sequence and generate traces, metrics, and logs. - -By working through these tutorials, you can learn skills to help you set up your own app with OpenTelemetry and New Relic. - -Screenshot showing various JVM metric charts - -
- After you finish any of these tutorials, you can view JVM metrics in charts like these. -
- -## Requirements [#requirements] - -To 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. -* Java 17 or higher: If you don't already have this, see [these download options](https://www.java.com/en/download/manual.jsp). - -## Tutorials [#tutorials] - -Although each tutorial uses the same demo app, they have different approaches to help you become acquainted with OpenTelemetry and New Relic. -* [Pre-instrumented app](#pre-instrumented-tutorial): Run our pre-instrumented demo app for a quick way to see data in our UI. -* [OpenTelemetry Java agent](#java-agent-tutorial): Monitor our demo app with the OpenTelemetry Java agent. -* [Manual setup](#manual-setup-tutorial): Instrument our demo app manually. - -Click on the tab below for the tutorial you want to complete. - - -When using OpenTelemetry, you'll have two choices for exporting data from your application to New Relic via OTLP: -* Directly from your app to New Relic -* Your app sends data to an OpenTelemetry Collector where it is then exported to New Relic - -These tutorials cover the first option. If you want to export your data via a collector, check out this [collector documentation](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/collector-processing/opentelemetry-collector-processing-intro) for details. - - - - - - - Pre-instrumented app - - - OpenTelemetry Java agent - - - Manual setup - - - - - -### 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 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' `java` directory. - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/java - ``` -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` - - * `OTEL_EXPORTER_OTLP_HEADERS=api-key=INSERT_YOUR_NEW_RELIC_LICENSE_KEY` - * `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` - * Replace `INSERT_YOUR_OWN_ID_HERE` with a unique instance id. For example, you could use 1234. - * `OTEL_LOGS_EXPORTER=otlp` -4. In the same `getting-started-guides/java` directory, build and run the application: - * macOS: - ```bash - ./gradlew bootRun - ``` - - * PowerShell: - ```bash - .\gradlew.bat build - ``` -5. Open a new terminal tab, switch to the `getting-started-guides/java/Instrumented` directory, and run the following command to generate some traffic to the application: - * macOS: - ```bash - ./load-generator.sh - ``` - - * PowerShell: - ```bash - .\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. - - -6. Go to **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services**. -7. Click your new entity (service) called `getting-started-java` and explore the UI. For more tips about what to look for in the UI, see [View your data in New Relic](#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. - - - - -### Monitor the demo app with the OpenTelemetry Java agent [#java-agent] - -Here's a different tutorial that also uses the same demo app. In this case, you'll use the OpenTelemetry Java agent to automatically monitor the demo app. You don't need to modify the Java source code. By using the agent, you can quickly start exporting sample data to New Relic. - -The auto-instrumentation agent is a JAR file 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 Java 8+ application. - - - See the [official Java agent documentation](https://opentelemetry.io/docs/instrumentation/java/automatic/) for additional configuration options. - - -To monitor our demo app with the OpenTelemetry Java agent: - -1. Download the [agent JAR file](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/latest/download/opentelemetry-javaagent.jar), which contains the agent and instrumentation libraries. Place it in your preferred directory and note the path, which you will use later. -2. If you haven't already done so, download the demo application repository and switch to the following directory: - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/java - ``` -3. Build the demo app with this command: - * macOS: - ```bash - ./gradlew build - ``` - * PowerShell: - ```bash - .\gradlew.bat build - ``` - - After a successful build, you will find the resulting application JAR file in `Uninstrumented/build/libs`, called `uninstrumented.jar`. - - -4. 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. - -5. Continue in `getting-started-guides/java/Uninstrumented` to launch the agent with the app: - - - Replace `path/to` with the location of the JAR file you downloaded earlier. - - ```bash - java -javaagent:path/to/opentelemetry-javaagent.jar \ - -jar ./build/libs/uninstrumented.jar - ``` -6. Generate traffic to the application by opening a new terminal in the `getting-started-guides/java/Uninstrumented` directory and running the load generator: - * macOS: - ```bash - ./load-generator.sh - ``` - - * PowerShell: - ```bash - .\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. - - - - - -### Set up the demo app manually [#manual-instrum] - -The previous tutorial helped you explore automatic instrumentation with the OpenTelemetry Java agent. This tutorial will show you how to use custom instrumentation to have more control over the telemetry you gather. You'll manually insert instrumentation into our demo app to capture telemetry, and then you'll configure the SDK to export that data to New Relic. - - - While you can manually configure the SDK, we will show you how to configure the SDK using the [autoconfigure option](https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/autoconfigure), which simplifies the the process by using environment variables and system properties. - - - - -#### Download the demo application [#download] - -If you haven't already downloaded our demo app, run the following: - -```bash -git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git -``` - - -#### Install dependencies [#dependencies] - -To add dependencies: - -1. Go to the application directory. - ```bash - cd newrelic-opentelemetry-examples/getting-started-guides/java/uninstrumented - ``` -2. Open `build.gradle`. -3. Add the following highlighted items to the `dependencies` block (you may need to scroll down inside the code block): - ```gradle lineHighlight=29-42 - plugins { - id 'org.springframework.boot' version '2.7.5' - id 'io.spring.dependency-management' version '1.1.0' - id 'java' - } - - java { - toolchain { - languageVersion = JavaLanguageVersion.of(17) - } - } - - repositories { - mavenCentral() - } - - bootRun { - mainClass.set 'com.example.demo.Application' - } - - configurations.all { - exclude module: 'spring-boot-starter-logging' - } - - dependencies { - implementation 'org.springframework.boot:spring-boot-starter-web' - implementation 'org.springframework.boot:spring-boot-starter-log4j2' - - // OpenTelemetry core - implementation platform('io.opentelemetry:opentelemetry-bom:1.22.0') - implementation platform('io.opentelemetry:opentelemetry-bom-alpha:1.22.0-alpha') - implementation 'io.opentelemetry:opentelemetry-api' - implementation 'io.opentelemetry:opentelemetry-sdk' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp-logs' - implementation 'io.opentelemetry:opentelemetry-sdk-extension-autoconfigure' - - // OpenTelemetry instrumentation - implementation platform('io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom-alpha:1.22.1-alpha') - implementation 'io.opentelemetry.instrumentation:opentelemetry-runtime-metrics' - implementation 'io.opentelemetry.instrumentation:opentelemetry-log4j-appender-2.17' - implementation 'io.opentelemetry.instrumentation:opentelemetry-spring-webmvc-6.0' - } - ``` - -Notes: - -* The `bom` (bill of materials) dependencies are used to synchronize versions of dependencies for a particular ecosystem. Since OpenTelemetry publishes a lot of Java components, these help ensure that all the versions are synchronized, whether you use just a few or a lot of them. -* The remaining dependencies provide access to the SDK, API, OTLP exporter, and instrumentation libraries. -* There is an additional configuration to exclude the spring-boot-starter-logging module. This prevents a build error message relating to `log4j-slf4j-impl cannot be present with log4j-to-slf4j`. - - -#### Configure the SDK with the autoconfigure extension [#auto-config-ext] - -While you can configure the SDK manually, we recommend you use the autoconfigure extension since it streamlines the process. - -1. Go to the app's source code directory: - ```bash - cd newrelic-opentelemetry-examples/getting-started-guides/java/uninstrumented/src/main/java/com/example/demo - ``` -2. Open `Application.java`. -3. Insert the highlighted lines: - ```java lineHighlight=7-12,17-20 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - } - ``` -4. 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. - - -#### Add instrumentation libraries: traces [#library-traces] - -In `Application.java`, add the highlighted instrumentation for Spring Web MVC by registering a tracing filter: - -```java lineHighlight=22-26 -@SpringBootApplication -public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } -} -``` - - - -#### Add instrumentation libraries: metrics [#library-metrics] - -Generate and collect metrics about your Java runtime by registering the following in the `Application.java` file. Insert the highlighted lines below: - -```java lineHighlight=14-20 -@SpringBootApplication -public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - // Register runtime metrics instrumentation - BufferPools.registerObservers(openTelemetrySdk); - Classes.registerObservers(openTelemetrySdk); - Cpu.registerObservers(openTelemetrySdk); - GarbageCollector.registerObservers(openTelemetrySdk); - MemoryPools.registerObservers(openTelemetrySdk); - Threads.registerObservers(openTelemetrySdk); - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } -} -``` - - -#### Add instrumentation libraries: logs [#library-logs] - -This demo application is configured to use the `OpenTelemetryAppender` (via `log4j.xml`), which uses `GlobalLoggerProvider`. Setting `GlobalLoggerProvider` wires up the `OpenTelemetryAppender` to the Log SDK that is configured using autoconfigure here: - -1. Open `Application.java`. -2. Insert the following highlighted lines. - ```java lineHighlight=14-15 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - // Set GlobalLoggerProvider, which is used by Log4j2 appender - GlobalLoggerProvider.set(openTelemetrySdk.getSdkLoggerProvider()); - - // Register runtime metrics instrumentation - BufferPools.registerObservers(openTelemetrySdk); - Classes.registerObservers(openTelemetrySdk); - Cpu.registerObservers(openTelemetrySdk); - GarbageCollector.registerObservers(openTelemetrySdk); - MemoryPools.registerObservers(openTelemetrySdk); - Threads.registerObservers(openTelemetrySdk); - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - -3. Create a directory called `resources` in `Uninstrumented/src/main`. -4. In this new directory, create a file called `log4j2.xml` with the following contents: - ```xml - - - - - - - - - - - - - - - - ``` - - The `packages=...` section of this line allows Log4J to find and configure the `OpenTelemetryAppender`. The source code is [in the OpenTelemetry repository](https://github.com/open-telemetry/opentelemetry-java-instrumentation/tree/main/instrumentation/log4j/log4j-appender-2.17/library) and was added as a dependency via `io.opentelemetry.instrumentation:opentelemetry-log4j-appender-2.17`) - - - -#### Custom trace instrumentation: Create span attribute constants [#custom-attribs] - -Each trace is made up of spans, which represent a logical unit of work or an operation within a particular request. The code below demonstrates: - -* Static constants to hold attribute keys that can be used to provide request-level insights in your spans -* How to initialize a [Tracer](https://opentelemetry.io/docs/concepts/signals/traces/#tracer), which creates spans - -Insert the following highlighted lines into `Controller.java`: - -```java lineHighlight=4-14 -@RestController -public class Controller { - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - - private final Tracer tracer; - - @Autowired - Controller(OpenTelemetry openTelemetry) { - // Initialize tracer - tracer = openTelemetry.getTracer(Controller.class.getName()); - } - - @GetMapping(value = "/fibonacci") - . . . -} -``` - - -#### 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. - -1. In `Controller.java`, insert these highlighted lines 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 - ```java lineHighlight=2-3 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - . . . - } - ``` -2. Add granular detail into your code by adding an attribute to your span for storing information about successful requests: - ```java lineHighlight=20-21 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - try { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, last); - return last; - } catch (IllegalArgumentException e) { - throw e; - } - } - ``` - - - -#### 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. First, set your span as the current span, set the status code to error in the event of an exception, and then end the span: - -```java lineHighlight=5-6,26-27,29-32 -private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - throw e; - } finally { - // End the span - span.end(); - } -} -``` - -This method throws an `IllegalArgumentException` if a user provides invalid input. When this happens, the exception is recorded as an event on the span and the span's status will be set to `ERROR`. The exception message is captured as the status description. The exception will be recorded as an event on the span where it occurs. - -Finally, in `handleException()` in the `ErrorHandler` class, set the status for the span to `ERROR` with these highlighted lines: - -```java lineHighlight=10-11 -@ControllerAdvice -private static class ErrorHandler { - - @ExceptionHandler({ - IllegalArgumentException.class, - MissingServletRequestParameterException.class, - HttpRequestMethodNotSupportedException.class - }) - public ResponseEntity handleException(Exception e) { - // Set the span status and description - Span.current().setStatus(StatusCode.ERROR, e.getMessage()); - return new ResponseEntity<>(Map.of("message", e.getMessage()), HttpStatus.BAD_REQUEST); - } -} -``` -As in the previous step, this sets the span's status code if the user inputs an invalid number. However, because this happens in the exception handler, rather than in `fibonacci()`, the current span is the parent span for the request. This parent span comes from the Spring Web MVC instrumentation added via the filter in the Application class. Now, when your application endpoint raises an exception, both the parent span and child span will have a span status of `ERROR`. - - - -#### Custom metric instrumentation: Add a custom metric counter [#metrics-cust] - -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 - - - If you have any questions about the status of metric in the OpenTelemetry project, see the [signal statuses](https://opentelemetry.io/docs/instrumentation/java/#status-and-releases). - - -Complete the following to add a custom counter: - -1. Instantiate a boolean attribute for your custom metric and initialize a metrics instrument. - - In this case, we are using a [LongCounter](https://opentelemetry.io/docs/instrumentation/java/manual/#metrics), which records only positive values and is useful for counting things, such as the number of bytes sent over a network. By default, counter measurements are aggregated to monotonic (always increasing) sums. - - - ```java lineHighlight=7,10,16-21 - @RestController - public class Controller { - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - private static final AttributeKey ATTR_VALID_N = AttributeKey.booleanKey("fibonacci.valid.n"); - - private final Tracer tracer; - private final LongCounter fibonacciInvocations; - - @Autowired - Controller(OpenTelemetry openTelemetry) { - // Initialize tracer - tracer = openTelemetry.getTracer(Controller.class.getName()); - // Initialize instrument - Meter meter = openTelemetry.getMeter(Controller.class.getName()); - fibonacciInvocations = meter - .counterBuilder("fibonacci.invocations") - .setDescription("Measures the number of times the fibonacci method is invoked.") - .build(); - } - . . . - } - ``` -2. Insert the following highlighed lines so your custom counter can capture valid and invalid inputs, as well as the number of times each occurs. - ```java lineHighlight=24-25,30-31 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - // Counter to increment the number of times a valid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, true)); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - // Counter to increment the number of times an invalid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, false)); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - -#### Custom log instrumentation [#cust-log] - -The status of the logs signal in OpenTelemetry Java is currently [experimental](https://opentelemetry.io/docs/instrumentation/java/#status-and-releases). Log messages are managed by the root handler in your app, which will send logs of `INFO` level and higher to the console by default. However, you can modify the logger behavior by changing the logging level, including for specific classes, or installing a custom handler or filter. - -##### Initialize the logger [#initialize-logger] - -As previously stated, this is from the `java.util.logging` library. The Logger is not an OpenTelemetry component, but the application has been configured to send Log4j logs to the OpenTelemetry Log SDK: - -```java lineHighlight=4-5 -@RestController -public class Controller { - - // Logger (note that this is not an OTel component) - private static final Logger LOGGER = LogManager.getLogger(Controller.class); - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - private static final AttributeKey ATTR_VALID_N = AttributeKey.booleanKey("fibonacci.valid.n"); - . . . -} -``` - -##### Add custom log messages [#cust-log-messages] - -Once you've initialized the logger, you can use the logger to record: - -* The result of a valid input, along with the value of that result -* When no output was recorded - -Insert the following highlighted lines: - -```java lineHighlight=26-27,34-35 -private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - // Counter to increment the number of times a valid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, true)); - // Log the result of a valid input - LOGGER.info("Compute fibonacci(" + n + ") = " + result); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - // Counter to increment the number of times an invalid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, false)); - // Log when no output was recorded - LOGGER.info("Failed to compute fibonacci(" + n + ")"); - throw e; - } finally { - // End the span - span.end(); - } -} -``` - - - -#### Exercise the app to generate some traffic [#exercise-app] - -You're ready to send some data to New Relic! - -1. Go to the directory `getting-started-guides/java`, and build and run the app with this command: - * macOS: - ```bash - ./gradlew bootRun - ``` - - * PowerShell: - ```bash - .\gradlew.bat build - ``` - - If your terminal displays the Spring ASCII, it means your app has successfully built and is running: - - Screenshot showing Spring Boot ASCII logo - -2. Generate traffic from the application by opening a new terminal in the `getting-started-guides/java/Uninstrumented` directory and running the load generator: - * macOS: - ```bash - ./load-generator.sh - ``` - - * PowerShell: - ```bash - .\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. - -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-java` (or whatever name you provided). -3. Check out the details in the sections for each data type. - - - If you are using 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-java` entity in New Relic: - - -1. In the left pane's **Monitor** section, click **Distributed tracing**, and then click the **Fibonacci** trace group. - Screenshot showing the main distributed tracing page -2. From there, find a trace with an error and click to open it. - - With the OpenTelemetry Java agent, you might see different result than you'd see with the New Relic APM Java agent. This is because there's a difference in error handling between the two agent types. For more information, see [Handling error rate in OpenTelemetry and New Relic](https://newrelic.com/blog/how-to-relic/error-rate-opentelemetry-and-new-relic). - - 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-java` entity in New Relic, you can see a list of all collected metrics, such as runtime metrics (JVMs) and 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). - - -#### JVMs [#jvms] - -You can also view visualizations of your Java runtime metrics, including throughput, memory usage, and garbage collection time per minute, by heading to the JVM page: - -Screenshot of the main JVMs page - -You can view the metrics for a single instance, or select multiple instances to compare them: - -Screenshot of how to compare JVM instances - -Here is what you will see after selecting your instances and clicking **Compare**, where each instance is color coded for easy identification: - -Screenshot showing the color-coded JVM comparison - -To learn more, see our documentation about the [JVMs view](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-jvms-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` (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` - - * This is the name that associates your application telemetry with an entity in New Relic. In this tutorial we're calling it `getting-started-java`, 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/semantic-conventions/blob/main/docs/resource/README.md#service-experimental). -
- `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 [attribute limit](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/#attribute-limits). -
- `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=BASE2_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 created 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 Java agent)](#java-agent) -* [Tutorial 3 (Set up the demo app manually)](#auto-config-ext) - -## 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/apm-monitoring/opentelemetry-apm-intro). diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx deleted file mode 100644 index bf648db5c6c..00000000000 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx +++ /dev/null @@ -1,839 +0,0 @@ ---- -title: 'OpenTelemetry tutorials: Instrument a sample Python app' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: To test out OpenTelemetry on a sample Pythyon app instead of your own app, consider these three tutorials. -freshnessValidatedDate: never -redirects: - - /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-tutorial-python/ ---- - -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' - - - - - -Try out any of these Python tutorials to see what the New Relic platform can do with your OTLP data. We have three tutorials you can choose from, each one using the same demo Flask app. The app calculates the nth number in the Fibonacci sequence and generates traces, metrics, and logs. - -By working through any of 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. -
- -## 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. -* Python 3.8 or higher, and pip (included in Python version 3.4 and later): If you don't already have these, see these [download options](https://www.python.org/downloads/). - -## Tutorials [#tutorials] - -Although each tutorial uses the same demo app, they have different approaches to help you become acquainted with OpenTelemetry and New Relic. - -* [Pre-instrumented app](#pre-instrumented-tutorial): Run our pre-instrumented demo app for a quick way to see data in our UI. -* [OpenTelemetry Python agent](#python-agent-tutorial): Monitor our demo app with the OpenTelemetry Python agent. -* [Manual setup](#manual-setup-tutorial): Instrument our demo app manually. - -Click on the tab below for the tutorial you want to complete. - - -When using OpenTelemetry, you'll have two choices for exporting data from your application to New Relic via OTLP: -* Directly from your app to New Relic -* Your app sends data to an OpenTelemetry Collector where it is then exported to New Relic - -These tutorials cover the first option. If you want to export your data via a collector, check out this [collector documentation](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/collector-processing/opentelemetry-collector-processing-intro) for details. - - - - - - Pre-instrumented app - - - OpenTelemetry Python agent - - - Manual setup - - - - - -### 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' `python/Instrumented` directory. - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/python/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` - - * OTEL_EXPORTER_OTLP_HEADERS=api-key=INSERT_YOUR_NEW_RELIC_LICENSE_KEY - * 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: - ``` - 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 > All capabilities](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. - - - - -### 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'll 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. - - - - -### Set up the demo app manually [#manual-instrum] - -The previous tutorial helped you explore automatic instrumentation with the OpenTelemetry Python agent. This tutorial will show you how to use custom instrumentation to have more control over the telemetry you gather. Then, you'll see how to configure the OpenTelemetry SDK to export the data to New Relic. - - - - -### Download the demo application [#download] - -Run the following to download our demo app: - -``` -git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git -``` - - - -### 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 - ``` - - - -### 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. - - - -### 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.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 -# 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())) -``` - - - -### 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.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 -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.") -``` - - - -### 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.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' -_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())))) -``` - - - -### 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) -``` - - - -### 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) - ``` - - - -### 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, you will use the `Status` and `StatusCode` modules from the `opentelemetry.trace.status package` that you added in step [D](#library-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.http.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) - ``` - - - -### 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 step [E](#library-metrics), you added the highlighted line below, which will 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.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 - 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) -``` - - - -### 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) -``` - - - -### 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 > 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. - - -### 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 (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 -
- 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 [attribute limit](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/#attribute-limits). -
- 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=base2_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/apm-monitoring/opentelemetry-apm-intro). diff --git a/src/nav/opentelemetry.yml b/src/nav/opentelemetry.yml index f07a7b93b25..630951049dc 100644 --- a/src/nav/opentelemetry.yml +++ b/src/nav/opentelemetry.yml @@ -17,10 +17,6 @@ pages: pages: - title: Overview path: /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro - - title: Java example - path: /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java - - title: Python example - path: /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python - title: Collector for infrastructure monitoring pages: - title: Overview From 7276ab1bb599b8a597925a23aae18890df1357ea Mon Sep 17 00:00:00 2001 From: Alan West <3676547+alanwest@users.noreply.github.com> Date: Mon, 3 Jun 2024 13:44:21 -0700 Subject: [PATCH 02/11] Remove commented out PHP tile --- .../apm-monitoring/opentelemetry-apm-intro.mdx | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx index 792d188974b..e76bd7951cd 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx @@ -76,14 +76,6 @@ to that language. The examples demonstrate how to configure: to="https://github.com/newrelic/newrelic-opentelemetry-examples/tree/main/getting-started-guides/javascript" /> - - Date: Mon, 3 Jun 2024 14:32:48 -0700 Subject: [PATCH 03/11] Delete translations --- .../apm-monitoring/opentelemetry-apm-java.mdx | 1200 ----------------- .../opentelemetry-apm-python.mdx | 909 ------------- .../apm-monitoring/opentelemetry-apm-java.mdx | 1198 ---------------- .../opentelemetry-apm-python.mdx | 907 ------------- .../apm-monitoring/opentelemetry-apm-java.mdx | 1198 ---------------- .../opentelemetry-apm-python.mdx | 907 ------------- .../apm-monitoring/opentelemetry-apm-java.mdx | 1200 ----------------- .../opentelemetry-apm-python.mdx | 909 ------------- 8 files changed, 8428 deletions(-) delete mode 100644 src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx delete mode 100644 src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx delete mode 100644 src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx delete mode 100644 src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx delete mode 100644 src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx delete mode 100644 src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx delete mode 100644 src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx delete mode 100644 src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx diff --git a/src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx b/src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx deleted file mode 100644 index fef7cc45b42..00000000000 --- a/src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx +++ /dev/null @@ -1,1200 +0,0 @@ ---- -title: 'Tutoriales de OpenTelemetry: instrumentación de una aplicación Java de muestra' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: 'To test out OpenTelemetry on a sample app instead of your own app, consider these three tutorials.' -freshnessValidatedDate: never -translationType: machine ---- - -import opentelemetrySpringBootASCIIDisplay from 'images/opentelemetry_screenshot-crop_Spring-Boot-ASCII-display.webp' - -import opentelemetryMainDistributedTracingPage from 'images/opentelemetry_screenshot-crop_main-distributed-tracing-page.webp' - -import opentelemetryDistributedTracingError from 'images/opentelemetry_screenshot-crop_distributed-tracing-error.webp' - -import opentelemetryInProcessSpans from 'images/opentelemetry_screenshot-crop_in-process-spans.webp' - -import opentelemetryExceptiononSpanEvent from 'images/opentelemetry_screenshot-crop_exception-on-span-event.webp' - -import opentelemetryAttributesTab from 'images/opentelemetry_screenshot-crop_attributes-tab.webp' - -import opentelemetryMetricsExplorerMain from 'images/opentelemetry_screenshot-crop_metrics-explorer-main.webp' - -import opentelemetryMetricsExplorerDimensions from 'images/opentelemetry_screenshot-crop_metrics-explorer-dimensions.webp' - -import opentelemetryJvmsPageMain from 'images/opentelemetry_screenshot-crop_jvms-page-main.webp' - -import opentelemetryCompareJvmInstances from 'images/opentelemetry_screenshot-full_compare-jvm-instances.webp' - -import opentelemetryJvmColorCodedComparison from 'images/opentelemetry_screenshot-full_jvm-color-coded-comparison.webp' - -import opentelemetryMainLogsPage from 'images/opentelemetry_screenshot-full_main-logs-page.webp' - -import opentelemetryLogsinTerminal from 'images/opentelemetry_screenshot-full_logs-in-terminal.webp' - -import opentelemetryLogDetailsWithTrace from 'images/opentelemetry_screenshot-full_log-details-with-trace.webp' - -import opentelemetryTraceRelatedtoLog from 'images/opentelemetry_screenshot-full_trace-related-to-log.webp' - -import opentelemetryTraceWaterfallFromLog from 'images/opentelemetry_screenshot-full_trace-waterfall-from-log.webp' - -import opentelemetryLogCapturedinTraceSpan from 'images/opentelemetry_screenshot-full_log-captured-in-trace-span.webp' - -import opentelemetryTraceDurationDemoChart from 'images/opentelemetry_screenshot-crop_jvm-metric-charts.webp' - -Pruebe estos tutoriales de Java para ver qué puede hacer la plataforma New Relic con sus datos OTLP. Tenemos tres tutoriales entre los que puede elegir, cada uno de los cuales utiliza la misma aplicación de demostración Spring. La aplicación calculará el enésimo número de la secuencia de Fibonacci y generará traza, métrica y log. - -Al seguir estos tutoriales, puede aprender habilidades que le ayudarán a configurar su propia aplicación con OpenTelemetry y New Relic. - -Screenshot showing various JVM metric charts - -
- Después de terminar cualquiera de estos tutoriales, podrá ver JVM métrica en gráficos como estos. -
- -## Requisitos [#requirements] - -Para comenzar, asegúrese de tener lo siguiente: - -* Una cuenta New Relic: Regístrese para obtener una [cuenta gratuita](https://newrelic.com/signup) si aún no tiene una. -* Java 17 o superior: si aún no lo tienes, consulta [estas opciones de descarga](https://www.java.com/en/download/manual.jsp). - -## Tutoriales [#tutorials] - -Aunque cada tutorial utiliza la misma aplicación de demostración, tienen diferentes enfoques para ayudarlo a familiarizarse con OpenTelemetry y New Relic. - -* [Aplicación pre-instrumentada](#pre-instrumented-tutorial): ejecute nuestra aplicación de demostración pre-instrumentada para ver rápidamente los datos en nuestra UI. -* [OpenTelemetry agente de Java](#java-agent-tutorial): monitor nuestra aplicación de demostración con el agente de Java OpenTelemetry. -* [Configuración manual](#manual-setup-tutorial): instrumente nuestra aplicación de demostración manualmente. - -Haga clic en la pestaña a continuación para ver el tutorial que desea completar. - - - Cuando utilice OpenTelemetry, tendrá dos opciones para exportar datos desde su aplicación a New Relic a través de OTLP: - - * Directamente desde tu aplicación a New Relic - * Su aplicación envía datos a un recopilador OpenTelemetry donde luego se exporta a New Relic - - Estos tutoriales cubren la primera opción. Si desea exportar sus datos a través de un recopilador, consulte esta [documentación del recopilador](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/collector-processing/opentelemetry-collector-processing-intro) para obtener más detalles. - - - - - - Aplicación pre-instrumentada - - - - OpenTelemetry agente de Java - - - - Configuración manual - - - - - - ### Ejecute la aplicación de demostración pre-instrumentada [#pre-instrum] - - Esta es una excelente opción si desea que hagamos la instrumentación para que pueda ver rápidamente cómo es enviar datos a New Relic y verlos en nuestra UI. - - 1. En su terminal, ejecute lo siguiente para clonar la aplicación de demostración y navegue hasta el directorio `java` de las Guías de introducción. - - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/java - ``` - - 2. Configure estas dos variables de entorno para enviar datos a su cuenta New Relic: - - * Asegúrate de utilizar tu . - - * Si la región de su centro de datos New Relic es la UE y no los EE. UU., configure el extremo en: `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_PROTOCOL=http/protobuf` - - 3. Configure la primera variable de entorno a continuación para nombrar el servicio, luego configure la segunda para el ID del servicio de la instancia, que activa cierta característica de la plataforma. Finalmente, habilite el log ya que el logging está desactivado de forma predeterminada: - - * `OTEL_SERVICE_NAME=getting-started-java` - - * `OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_ID_HERE` - - * Reemplace `INSERT_YOUR_OWN_ID_HERE` con un ID único de la instancia. Por ejemplo, podrías usar 1234. - - * `OTEL_LOGS_EXPORTER=otlp` - - 4. En el mismo directorio `getting-started-guides/java` , cree y ejecute la aplicación: - - * Mac OS: - - ```bash - ./gradlew bootRun - ``` - - * Potencia Shell: - - ```bash - .\gradlew.bat build - ``` - - 5. Abra una nueva pestaña de terminal, cambie al directorio `getting-started-guides/java/Instrumented` y ejecute el siguiente comando para generar algo de tráfico a la aplicación: - - * Mac OS: - - ```bash - ./load-generator.sh - ``` - - * Potencia Shell: - - ```bash - .\load-generator.ps1 - ``` - - - Alternativamente, puede llegar al extremo en el browser en esta URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Reemplace `INSERT_A_VALUE` con un valor de 1 a 90. Para generar un error, inserte un número entero fuera del rango válido. - - - 6. Vaya a **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services**. - - 7. Haga clic en su nueva entidad (servicio) llamada `getting-started-java` y explore la UI. Para obtener más consejos sobre qué buscar en la UI, consulte [Ver sus datos en New Relic](#view-data). - - 8. Cuando haya terminado de ver sus datos en la UI, cierre la aplicación presionando CONTROL+C en ambas sesiones de terminal. - - - - ### monitor la aplicación de demostración con el agente de Java OpenTelemetry [#java-agent] - - Aquí hay un tutorial diferente que también utiliza la misma aplicación de demostración. En este caso, utilizará el agente de Java OpenTelemetry para monitor automáticamente la aplicación de demostración. No es necesario modificar el código fuente de Java. Al utilizar el agente, puede comenzar rápidamente a exportar datos de muestra a New Relic. - - El agente de instrumentación automática es un archivo JAR que inyecta dinámicamente código de bytes para capturar telemetría de bibliotecas y marcos populares. También puede usarlo para capturar datos como solicitudes entrantes, llamadas HTTP salientes y llamadas de base de datos. Se puede adjuntar a cualquier aplicación Java 8+. - - - Consulte la [documentación oficial del agente de Java](https://opentelemetry.io/docs/instrumentation/java/automatic/) para obtener opciones de configuración adicionales. - - - Para monitor nuestra aplicación de demostración con el agente de Java OpenTelemetry: - - 1. Descargue el [archivo JAR del agente](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/latest/download/opentelemetry-javaagent.jar), que contiene la biblioteca del agente y la instrumentación. Colóquelo en su directorio preferido y anote la ruta que utilizará más adelante. - - 2. Si aún no lo ha hecho, descargue el repositorio de la aplicación de demostración y cambie al siguiente directorio: - - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/java - ``` - - 3. Cree la aplicación de demostración con este comando: - - * Mac OS: - - ```bash - ./gradlew build - ``` - - * Potencia Shell: - - ```bash - .\gradlew.bat build - ``` - - - Después de una compilación exitosa, encontrará el archivo JAR de la aplicación resultante en `Uninstrumented/build/libs`, llamado `uninstrumented.jar`. - - - 4. Vaya a nuestra [sección de referencia de variables de entorno](#ref-env-vars) a continuación para ver qué variables necesita exportar y luego volver a estos pasos. - - 5. Continúe en `getting-started-guides/java/Uninstrumented` para lanzar el agente con la aplicación: - - - Reemplace `path/to` con la ubicación del archivo JAR que descargó anteriormente. - - - ```bash - java -javaagent:path/to/opentelemetry-javaagent.jar \ - -jar ./build/libs/uninstrumented.jar - ``` - - 6. Genere tráfico a la aplicación abriendo una nueva terminal en el directorio `getting-started-guides/java/Uninstrumented` y ejecutando el generador de carga: - - * Mac OS: - - ```bash - ./load-generator.sh - ``` - - * Potencia Shell: - - ```bash - .\load-generator.ps1 - ``` - - - Alternativamente, puede llegar al extremo en el browser en esta URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Reemplace `INSERT_A_VALUE` con un valor de 1 a 90. Para generar un error, inserte un número entero fuera del rango válido. - - - 7. Ahora que ha enviado algunos datos a New Relic, consulte nuestras [instrucciones sobre cómo ver los datos en la UI](#view-data). - - 8. Cuando haya terminado de ver sus datos en la UI, cierre la aplicación presionando CONTROL+C en ambas sesiones de terminal. - - - - ### Configure la aplicación de demostración manualmente [#manual-instrum] - - El tutorial anterior le ayudó a explorar la instrumentación automática con el agente de Java OpenTelemetry. Este tutorial le mostrará cómo utilizar instrumentación personalizada para tener más control sobre la telemetría que recopila. Insertará manualmente la instrumentación en nuestra aplicación de demostración para capturar la telemetría y luego configurará el SDK para exportar esos datos a New Relic. - - - Si bien puede configurar manualmente el SDK, le mostraremos cómo configurar el SDK usando la [opción de configuración automática](https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/autoconfigure), que simplifica el proceso mediante el uso de variables de entorno y propiedades del sistema. - - - - - #### Descargue la aplicación de demostración [#download] - - Si aún no ha descargado nuestra aplicación de demostración, ejecute lo siguiente: - - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - ``` - - - - #### Instalar dependencia [#dependencies] - - Para agregar dependencia: - - 1. Vaya al directorio de la aplicación. - - ```bash - cd newrelic-opentelemetry-examples/getting-started-guides/java/uninstrumented - ``` - - 2. Abra `build.gradle`. - - 3. Agregue los siguientes elementos resaltados al bloque `dependencies` (es posible que deba desplazarse hacia abajo dentro del bloque de código): - - ```gradle lineHighlight=29-42 - plugins { - id 'org.springframework.boot' version '2.7.5' - id 'io.spring.dependency-management' version '1.1.0' - id 'java' - } - - java { - toolchain { - languageVersion = JavaLanguageVersion.of(17) - } - } - - repositories { - mavenCentral() - } - - bootRun { - mainClass.set 'com.example.demo.Application' - } - - configurations.all { - exclude module: 'spring-boot-starter-logging' - } - - dependencies { - implementation 'org.springframework.boot:spring-boot-starter-web' - implementation 'org.springframework.boot:spring-boot-starter-log4j2' - - // OpenTelemetry core - implementation platform('io.opentelemetry:opentelemetry-bom:1.22.0') - implementation platform('io.opentelemetry:opentelemetry-bom-alpha:1.22.0-alpha') - implementation 'io.opentelemetry:opentelemetry-api' - implementation 'io.opentelemetry:opentelemetry-sdk' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp-logs' - implementation 'io.opentelemetry:opentelemetry-sdk-extension-autoconfigure' - - // OpenTelemetry instrumentation - implementation platform('io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom-alpha:1.22.1-alpha') - implementation 'io.opentelemetry.instrumentation:opentelemetry-runtime-metrics' - implementation 'io.opentelemetry.instrumentation:opentelemetry-log4j-appender-2.17' - implementation 'io.opentelemetry.instrumentation:opentelemetry-spring-webmvc-6.0' - } - ``` - - Notas: - - * La dependencia `bom` (lista de materiales) se utiliza para sincronizar versiones de dependencia para un ecosistema en particular. Dado que OpenTelemetry publica muchos componentes Java, estos ayudan a garantizar que todas las versiones estén sincronizadas, ya sea que use solo unas pocas o muchas. - * Las dependencias restantes brindan acceso al SDK, API, exportador OTLP y biblioteca de instrumentación. - * Hay una configuración adicional para excluir el módulo spring-boot-starter-logging. Esto evita un mensaje de error de compilación relacionado con `log4j-slf4j-impl cannot be present with log4j-to-slf4j`. - - - - #### Configure el SDK con la extensión de configuración automática [#auto-config-ext] - - Si bien puede configurar el SDK manualmente, le recomendamos utilizar la extensión de configuración automática, ya que agiliza el proceso. - - 1. Vaya al directorio del código fuente de la aplicación: - - ```bash - cd newrelic-opentelemetry-examples/getting-started-guides/java/uninstrumented/src/main/java/com/example/demo - ``` - - 2. Abra `Application.java`. - - 3. Inserte las líneas resaltadas: - - ```java lineHighlight=7-12,17-20 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - } - ``` - - 4. Vaya a nuestra [sección de referencia de variables de entorno](#ref-env-vars) a continuación para ver qué variables necesita exportar y luego volver a estos pasos. - - - - #### Añadir instrumentación biblioteca: traza [#library-traces] - - En `Application.java`, agregue la instrumentación resaltada para Spring Web MVC registrando un filtro de seguimiento: - - ```java lineHighlight=22-26 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - - - - #### Agregar biblioteca de instrumentación: métrica [#library-metrics] - - Genere y recopile métricas sobre su tiempo de ejecución de Java registrando lo siguiente en el archivo `Application.java` . Inserte las líneas resaltadas a continuación: - - ```java lineHighlight=14-20 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - // Register runtime metrics instrumentation - BufferPools.registerObservers(openTelemetrySdk); - Classes.registerObservers(openTelemetrySdk); - Cpu.registerObservers(openTelemetrySdk); - GarbageCollector.registerObservers(openTelemetrySdk); - MemoryPools.registerObservers(openTelemetrySdk); - Threads.registerObservers(openTelemetrySdk); - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - - - - #### Agregar biblioteca de instrumentación: log [#library-logs] - - Esta aplicación de demostración está configurada para usar `OpenTelemetryAppender` (a través de `log4j.xml`), que usa `GlobalLoggerProvider`. La configuración de `GlobalLoggerProvider` conecta el `OpenTelemetryAppender` al SDK log que se configura mediante la configuración automática aquí: - - 1. Abra `Application.java`. - - 2. Inserte las siguientes líneas resaltadas. - - ```java lineHighlight=14-15 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - // Set GlobalLoggerProvider, which is used by Log4j2 appender - GlobalLoggerProvider.set(openTelemetrySdk.getSdkLoggerProvider()); - - // Register runtime metrics instrumentation - BufferPools.registerObservers(openTelemetrySdk); - Classes.registerObservers(openTelemetrySdk); - Cpu.registerObservers(openTelemetrySdk); - GarbageCollector.registerObservers(openTelemetrySdk); - MemoryPools.registerObservers(openTelemetrySdk); - Threads.registerObservers(openTelemetrySdk); - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - - 3. Cree un directorio llamado `resources` en `Uninstrumented/src/main`. - - 4. En este nuevo directorio, cree un archivo llamado `log4j2.xml` con el siguiente contenido: - - ```xml - - - - - - - - - - - - - - - - ``` - - - La sección `packages=...` de esta línea permite a Log4J encontrar y configurar el `OpenTelemetryAppender`. El código fuente está [en el repositorio de OpenTelemetry](https://github.com/open-telemetry/opentelemetry-java-instrumentation/tree/main/instrumentation/log4j/log4j-appender-2.17/library) y se agregó como una dependencia a través de `io.opentelemetry.instrumentation:opentelemetry-log4j-appender-2.17`) - - - - - #### Instrumentación de traza personalizada: Crear constantes de atributo span [#custom-attribs] - - Cada traza se compone de tramos, que representan una unidad de trabajo lógica o una operación dentro de una solicitud particular. El siguiente código lo demuestra: - - * Constantes estáticas para contener claves de atributos que se pueden usar para proporcionar Insights a nivel de solicitud en sus intervalos. - * Cómo inicializar un [rastreador](https://opentelemetry.io/docs/concepts/signals/traces/#tracer), que crea tramos - - Inserte las siguientes líneas resaltadas en `Controller.java`: - - ```java lineHighlight=4-14 - @RestController - public class Controller { - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - - private final Tracer tracer; - - @Autowired - Controller(OpenTelemetry openTelemetry) { - // Initialize tracer - tracer = openTelemetry.getTracer(Controller.class.getName()); - } - - @GetMapping(value = "/fibonacci") - . . . - } - ``` - - - - #### Traza instrumentación personalizada: Crear un tramo personalizado [#cust-span] - - Puede crear los intervalos que desee y depende de usted anotar sus intervalos con atributos en operaciones específicas. El atributo que establezca proporcionará contexto adicional sobre la operación específica que está rastreando, como resultados o propiedades de la operación. - - 1. En `Controller.java`, inserte estas líneas resaltadas para iniciar un nuevo intervalo llamado `fibonacci` que hace lo siguiente: - - * Captura datos sobre la ejecución de este método. - * Establece un atributo que almacena el valor de n de la solicitud del usuario. - - ```java lineHighlight=2-3 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - . . . - } - ``` - - 2. Agregue detalles granulares a su código agregando un atributo a su intervalo para almacenar información sobre solicitudes exitosas: - - ```java lineHighlight=20-21 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - try { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, last); - return last; - } catch (IllegalArgumentException e) { - throw e; - } - } - ``` - - - - #### Instrumentación de traza personalizada: Registrar una excepción [#span-exception] - - Es posible que desee registrar las excepciones a medida que ocurren. Le recomendamos hacer esto junto con la configuración del estado del intervalo. Primero, establezca su intervalo como el intervalo actual, establezca el código de estado en error en caso de una excepción y luego finalice el intervalo: - - ```java lineHighlight=5-6,26-27,29-32 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - Este método genera un `IllegalArgumentException` si un usuario proporciona una entrada no válida. Cuando esto sucede, la excepción se registra como un evento en el intervalo y el estado del intervalo se establecerá en `ERROR`. El mensaje de excepción se captura como descripción del estado. La excepción se registrará como un evento en el lapso donde ocurra. - - Finalmente, en `handleException()` en la clase `ErrorHandler` , establezca el estado del intervalo en `ERROR` con estas líneas resaltadas: - - ```java lineHighlight=10-11 - @ControllerAdvice - private static class ErrorHandler { - - @ExceptionHandler({ - IllegalArgumentException.class, - MissingServletRequestParameterException.class, - HttpRequestMethodNotSupportedException.class - }) - public ResponseEntity handleException(Exception e) { - // Set the span status and description - Span.current().setStatus(StatusCode.ERROR, e.getMessage()); - return new ResponseEntity<>(Map.of("message", e.getMessage()), HttpStatus.BAD_REQUEST); - } - } - ``` - - Como en el paso anterior, esto establece el código de estado del intervalo si el usuario ingresa un número no válido. Sin embargo, debido a que esto sucede en el controlador de excepciones, en lugar de en `fibonacci()`, el intervalo actual es el principal de intervalo de la solicitud. Este tramo principal proviene de la instrumentación Spring Web MVC agregada mediante el filtro en la clase de aplicación. Ahora, cuando el extremo de su aplicación genere una excepción, tanto el tramo principal como el tramo secundario tendrán un estado de tramo de `ERROR`. - - - - #### Instrumentación métrica personalizada: Añadir un contador métrica personalizada [#metrics-cust] - - Las métricas son un tipo telemetry data que son realmente útiles porque combinan mediciones individuales en agregaciones y producen datos que son constantes en función de la carga del sistema. Puede utilizar estos datos junto con intervalos para ayudar a detectar tendencias y proporcionar telemetría en tiempo de ejecución de la aplicación. También puede anotar cualquier métrica con un atributo para ayudar a describir qué subdivisión de las medidas representa la métrica. - - La API de OpenTelemetry métrica define una serie de instrumentados, que registran mediciones que son agregadas por el SDK de métrica y exportadas fuera de proceso. Hay dos tipos de instrumentado: - - * Síncrono: Estos instrumentados registran las mediciones a medida que ocurren. - * Asincrónico: Estos instrumentados registran un callback, el cual se invoca solo una vez por colección y no tiene contexto asociado - - - Si tiene alguna pregunta sobre el estado de la métrica en el proyecto OpenTelemetry, consulte los [estados de las señales](https://opentelemetry.io/docs/instrumentation/java/#status-and-releases). - - - Complete lo siguiente para agregar un contador personalizado: - - 1. Cree una instancia de un atributo booleano para su métrica personalizada e inicialice una métrica instrumentada. En este caso, estamos usando un [LongCounter](https://opentelemetry.io/docs/instrumentation/java/manual/#metrics), que registra solo valores positivos y es útil para contar cosas, como la cantidad de bytes enviados a través de una red. De forma predeterminada, las medidas de los contadores se agregan a sumas monótonas (siempre crecientes). - - ```java lineHighlight=7,10,16-21 - @RestController - public class Controller { - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - private static final AttributeKey ATTR_VALID_N = AttributeKey.booleanKey("fibonacci.valid.n"); - - private final Tracer tracer; - private final LongCounter fibonacciInvocations; - - @Autowired - Controller(OpenTelemetry openTelemetry) { - // Initialize tracer - tracer = openTelemetry.getTracer(Controller.class.getName()); - // Initialize instrument - Meter meter = openTelemetry.getMeter(Controller.class.getName()); - fibonacciInvocations = meter - .counterBuilder("fibonacci.invocations") - .setDescription("Measures the number of times the fibonacci method is invoked.") - .build(); - } - . . . - } - ``` - - 2. Inserte las siguientes líneas resaltadas para que su contador personalizado pueda capturar entradas válidas e inválidas, así como la cantidad de veces que ocurre cada una. - - ```java lineHighlight=24-25,30-31 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - // Counter to increment the number of times a valid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, true)); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - // Counter to increment the number of times an invalid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, false)); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - - - #### Instrumentación log personalizados [#cust-log] - - El estado de la señal de log en OpenTelemetry Java es actualmente [experimental](https://opentelemetry.io/docs/instrumentation/java/#status-and-releases). Los mensajes de log son administrados por el controlador raíz de su aplicación, que enviará logs de nivel `INFO` y superiores a la consola de forma predeterminada. Sin embargo, puede modificar el comportamiento logger cambiando el nivel de logging, incluso para clases específicas, o instalando un controlador o filtro personalizado. - - ##### Inicializar el logger [#initialize-logger] - - Como se indicó anteriormente, esto es de la biblioteca `java.util.logging` . El logger no es un componente de OpenTelemetry, pero la aplicación se ha configurado para enviar el log de Log4j al SDK log OpenTelemetry: - - ```java lineHighlight=4-5 - @RestController - public class Controller { - - // Logger (note that this is not an OTel component) - private static final Logger LOGGER = LogManager.getLogger(Controller.class); - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - private static final AttributeKey ATTR_VALID_N = AttributeKey.booleanKey("fibonacci.valid.n"); - . . . - } - ``` - - ##### Agregar mensaje de log personalizado [#cust-log-messages] - - Una vez que haya inicializado el logger, puede utilizarlo para logger : - - * El resultado de una entrada válida, junto con el valor de ese resultado. - * Cuando no se registró ninguna salida - - Inserte las siguientes líneas resaltadas: - - ```java lineHighlight=26-27,34-35 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - // Counter to increment the number of times a valid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, true)); - // Log the result of a valid input - LOGGER.info("Compute fibonacci(" + n + ") = " + result); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - // Counter to increment the number of times an invalid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, false)); - // Log when no output was recorded - LOGGER.info("Failed to compute fibonacci(" + n + ")"); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - - - #### Ejercite la aplicación para generar algo de tráfico. [#exercise-app] - - ¡Estás listo para enviar algunos datos a New Relic! - - 1. Vaya al directorio `getting-started-guides/java` y cree y ejecute la aplicación con este comando: - - * Mac OS: - - ```bash - ./gradlew bootRun - ``` - - * Potencia Shell: - - ```bash - .\gradlew.bat build - ``` - - - Si su terminal muestra Spring ASCII, significa que su aplicación se ha creado correctamente y se está ejecutando: - - Screenshot showing Spring Boot ASCII logo - - - 2. Genere tráfico desde la aplicación abriendo una nueva terminal en el directorio `getting-started-guides/java/Uninstrumented` y ejecutando el generador de carga: - - * Mac OS: - - ```bash - ./load-generator.sh - ``` - - * Potencia Shell: - - ```bash - .\load-generator.ps1 - ``` - - - Alternativamente, puede llegar al extremo en el browser en esta URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Reemplace `INSERT_A_VALUE` con un valor de 1 a 90. Para generar un error, inserte un número entero fuera del rango válido. - - - 3. Ahora que ha enviado algunos datos a New Relic, consulte nuestras [instrucciones sobre cómo ver los datos en la UI](#view-data). - - - - - - -## Vea los datos de su demostración en New Relic [#view-data] - -No importa qué tutorial haya completado, puede seguir los consejos a continuación para encontrar sus datos en la UI de New Relic. - -1. Vaya a - - **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services** - - . - -2. Haga clic en su nueva entidad (servicio) llamada `getting-started-java` (o cualquier nombre que haya proporcionado). - -3. Consulte los detalles en las secciones para cada tipo de datos. - - - Si está utilizando Windows y no ve datos en su cuenta de New Relic, verifique que haya permitido el tráfico a través del firewall. - - -### Traza [#traces] - -Una vez que hayas llegado a la entidad `getting-started-java` en New Relic: - -1. En la sección - - **Monitor** - - del panel izquierdo, haga clic en - - **Distributed tracing** - - y luego haga clic en el grupo de trazas - - **Fibonacci** - - . - - Screenshot showing the main distributed tracing page - -2. Desde allí, busca una traza con un error y haz clic para abrirla. - - Con el agente de Java OpenTelemetry , es posible que vea resultados diferentes a los que vería con el agente de Java New Relic APM . Esto se debe a que existe una diferencia en el manejo de errores entre los dos tipos de agente. Para obtener más información, consulte [Manejo de tasas de errores en OpenTelemetry y New Relic](https://newrelic.com/blog/how-to-relic/error-rate-opentelemetry-and-new-relic). - - Screenshot showing an error in distributed tracing - -3. Una vez que tenga la traza abierta, haga clic en `Show in-process spans` y luego haga clic en el tramo resultante, lo que abrirá un panel de detalles a la derecha. Para ver la excepción que registró cuando la entrada de un usuario no es válida, haga clic en `View span events`: - - Screenshot of in-process spans - -Si completó el tutorial de instrumentación manual, así es como se verá la excepción que registró como un lapso en New Relic: - -Screenshot showing an exception as a span event - -Para ver detalles adicionales que configuró, como el atributo de intervalo, el nombre del intervalo y el código de estado, haga clic en la pestaña **Attributes** . En este panel también puede ver metadatos adicionales que recopila automáticamente la biblioteca de instrumentación que utilizó en esta guía, así como los metadatos adjuntos de New Relic: - -Screenshot of the attributes tab - -Para obtener más detalles sobre cómo ver sus datos, consulte [OpenTelemetry en la UI de New Relic](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page) - -### Métrica [#metrics] - -Una vez que haya llegado a la entidad `getting-started-java` en New Relic, podrá ver una lista de todas las métricas recopiladas, como las métricas de tiempo de ejecución (JVM) y su atributo de contador personalizado. - -#### Explorador métrico [#metrics-explorer] - -Esta es una herramienta que te permite ver una lista de tus métricas. - -1. En el panel izquierdo, seleccione **Data > Metrics explorer** y luego seleccione `fibonacci.invocations`. - - Screenshot showing metrics explorer - -2. En **Dimensions**, vea el atributo que recopiló junto con su métrica personalizada y luego haga clic en **fibonacci.valid.n**. - - Screenshot showing the total number of invocations of fibonacci function - -Conozca más en nuestra documentación sobre la [vista del explorador métrica](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-metrics-explorer-page). - -#### JVM [#jvms] - -También puede ver visualizaciones de su métrica de tiempo de ejecución de Java, incluido el rendimiento, el uso de memoria y el tiempo de recolección de basura por minuto, dirigiéndose a la página de JVM: - -Screenshot of the main JVMs page - -Puede ver la métrica de una sola instancia o seleccionar varias instancias para compararlas: - -Screenshot of how to compare JVM instances - -Esto es lo que verá después de seleccionar sus instancias y hacer clic en **Compare**, donde cada instancia está codificada por colores para una fácil identificación: - -Screenshot showing the color-coded JVM comparison - -Para obtener más información, consulte nuestra documentación sobre la [vista JVM](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-jvms-page/). - -### Logs [#logs] - -Aquí es donde acceder a su log: - -Screenshot showing the main logs page - -También verás iniciar sesión en tu terminal: - -Screenshot showing logs in a terminal - -De vuelta en su vista de log, seleccione un log y verá un panel abierto con el mensaje de log y los atributos adicionales que se recopilaron, como el intervalo asociado y los identificadores de traza, así como los metadatos inyectados por New Relic: - -Screenshot showing log details with trace - -Puedes navegar al rastreo distribuido correlacionado haciendo clic en este pequeño icono azul: - -Screenshot showing how to find correlated trace - -Esto abrirá un panel que muestra la traza correlacionada, donde podrá ver más detalles sobre la traza. Para obtener más información sobre esta página, consulte [OpenTelemetry en la UI: página de rastreo distribuido](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page/) y [Comprender y utilizar la UI de rastreo distribuido](/docs/distributed-tracing/ui-data/understand-use-distributed-tracing-ui/): - -Screenshot showing the trace waterfall from the logs section - -También puede encontrar el log correlacionado desde la vista de rastreo distribuido. Cuando selecciones una traza que tenga su correspondiente log, lo verás indicado como una pestaña, y podrás visualizar el log directamente desde la traza sin tener que cambiar de vista: - -Screenshot showing how to see log details from a trace span - -Obtenga más información sobre la vista de registro [aquí](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-logs). - -## Referencia: variables de entorno [#ref-env-vars] - -Esta es una lista de las variables de entorno que debes exportar si estás realizando el tutorial 2 o 3. Una vez que termine de exportar las variables, regrese a los tutoriales utilizando los enlaces que siguen a la lista de variables: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- `OTEL_EXPORTER_OTLP_HEADERS=api-key=YOUR_LICENSE_KEY` - - * Encabezados: Esto determina a qué cuenta de New Relic se enviarán sus datos. Reemplace `YOUR_LICENSE_KEY` con su - - - - . -
- `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net` (Para EE. UU.) `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.eu01.nr-data.net` (Para la UE) - - * Este es el extremo al que se exportará la telemetría de su aplicación. Exportar datos al extremo OTLP de New Relic. -
- `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` - - * Especifica que se debe utilizar OTLP `http/protobuf` , que es el preferido por New Relic. -
- `OTEL_SERVICE_NAME=getting-started-java` - - * Este es el nombre que asocia la telemetría de su aplicación con una entidad en New Relic. En este tutorial lo llamamos `getting-started-java`, pero puedes llamarlo como quieras. -
- `OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_OWN_ID_HERE` - - * Reemplace `INSERT_YOUR_OWN_ID_HERE` con un ID único de la instancia. Por ejemplo, podrías usar `1234`. Para obtener más detalles, consulte [Convenciones semánticas de recursos](https://github.com/open-telemetry/semantic-conventions/blob/main/docs/resource/README.md#service-experimental) de OpenTelemetry. -
- `OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT=4095` - - * Establecer un límite en la longitud máxima del valor del atributo evitará que los datos del intervalo se eliminen si exceden el [límite del atributo](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/#attribute-limits). -
- `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=DELTA` - - * New Relic admite métrica en temporalidad delta en lugar del valor predeterminado de acumulativa. -
- `OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=BASE2_EXPONENTIAL_BUCKET_HISTOGRAM` - - * (Recomendado) Agregación de histogramas: utilice un histograma exponencial en lugar del histograma de depósito explícito predeterminado para una mejor compresión de datos. -
- `OTEL_LOGS_EXPORTER=otlp` - - * Habilite la exportación log a través de OTLP. La exportación log está deshabilitada de forma predeterminada. -
- `OTEL_EXPORTER_OTLP_COMPRESSION=gzip` - - * (Recomendado) Configurar la compresión gzip le permite maximizar la cantidad de datos que puede enviar por solicitud. Nuestro tamaño de carga útil máximo permitido es 1 MB (10^6 bytes). La compresión Gzip tiene un buen rendimiento y reduce la salida de datos. -
- `OTEL_EXPERIMENTAL_EXPORTER_OTLP_RETRY_ENABLED=true` - - * (Recomendado) Habilite el reintento de exportación experimental para ayudar a hacer frente a la falta de confiabilidad de Internet. -
- `OTEL_EXPERIMENTAL_RESOURCE_DISABLED_KEYS=process.command_line` - - * (Recomendado) Esto deshabilita el atributo de recurso `process.command_line` , que a menudo excede el límite de longitud máxima del atributo New Relic y puede contener información confidencial. -
-
-
- -Una vez que haya creado las variables de entorno enumeradas en el colapsador anterior, regrese al tutorial y complete la configuración: - -* [Tutorial 2 (monitor la aplicación demo con el agente de Java OpenTelemetry)](#java-agent) -* [Tutorial 3 (Configurar la aplicación de demostración manualmente)](#auto-config-ext) - -## ¿Que sigue? [#what-next] - -Ahora que experimentó con la instrumentación de OpenTelemetry y la configuración del SDK, puede aplicar lo que aprendió para configurar su propia aplicación o servicio con OpenTelemetry y New Relic. Para obtener más información, consulte [Configure su propia aplicación o servicio con OpenTelemetry](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro). \ No newline at end of file diff --git a/src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx b/src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx deleted file mode 100644 index 84ef3f7c103..00000000000 --- a/src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx +++ /dev/null @@ -1,909 +0,0 @@ ---- -title: 'Tutoriales de OpenTelemetry: instrumentación de una aplicación Python de muestra' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: 'To test out OpenTelemetry on a sample Pythyon app instead of your own app, consider these three 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' - -Pruebe cualquiera de estos tutoriales de Python para ver qué puede hacer la plataforma New Relic con sus datos OTLP. Tenemos tres tutoriales entre los que puede elegir, cada uno de los cuales utiliza la misma aplicación de demostración Flask. La aplicación calcula el enésimo número de la secuencia de Fibonacci y genera traza, métrica y log. - -Al seguir cualquiera de estos tutoriales, puede aprender habilidades que le ayudarán a configurar su propia aplicación con OpenTelemetry y New Relic. - -Screenshot showing response time, throughput, and error rate - -
- Después de terminar cualquiera de estos tutoriales, podrá ver la amplitud métrica en gráficos como estos. -
- -## Requisitos [#requirements] - -Antes de comenzar, asegúrese de tener lo siguiente: - -* Una cuenta New Relic: Regístrese para obtener una [cuenta gratuita](https://newrelic.com/signup) si aún no tiene una. -* Python 3.8 o superior y pip (incluido en la versión 3.4 y posterior de Python): si aún no los tiene, consulte estas [opciones de descarga](https://www.python.org/downloads/). - -## Tutoriales [#tutorials] - -Aunque cada tutorial utiliza la misma aplicación de demostración, tienen diferentes enfoques para ayudarlo a familiarizarse con OpenTelemetry y New Relic. - -* [Aplicación pre-instrumentada](#pre-instrumented-tutorial): ejecute nuestra aplicación de demostración pre-instrumentada para ver rápidamente los datos en nuestra UI. -* [Agente OpenTelemetry Python](#python-agent-tutorial): monitor nuestra aplicación de demostración con el agente OpenTelemetry Python. -* [Configuración manual](#manual-setup-tutorial): instrumente nuestra aplicación de demostración manualmente. - -Haga clic en la pestaña a continuación para ver el tutorial que desea completar. - - - Cuando utilice OpenTelemetry, tendrá dos opciones para exportar datos desde su aplicación a New Relic a través de OTLP: - - * Directamente desde tu aplicación a New Relic - * Su aplicación envía datos a un recopilador OpenTelemetry donde luego se exporta a New Relic - - Estos tutoriales cubren la primera opción. Si desea exportar sus datos a través de un recopilador, consulte esta [documentación del recopilador](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/collector-processing/opentelemetry-collector-processing-intro) para obtener más detalles. - - - - - - Aplicación pre-instrumentada - - - - Agente Python de OpenTelemetry - - - - Configuración manual - - - - - - ### Ejecute la aplicación de demostración pre-instrumentada [#pre-instrum] - - Esta es una excelente opción si desea que hagamos la instrumentación para que pueda ver rápidamente cómo es enviar datos a New Relic y verlos en nuestra UI. - - 1. En su terminal, ejecute lo siguiente para clonar la aplicación de demostración y navegue hasta el directorio `python/Instrumented` de las Guías de introducción. - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/python/Instrumented - ``` - - 2. Configure estas variables de entorno para enviar datos a su cuenta New Relic: - - * Asegúrate de utilizar tu . - - * Si la región de su centro de datos New Relic es la UE y no los EE. UU., configure el extremo en: `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](https://otlp.nr-data.net) - - 3. Establezca esta variable de entorno para nombrar el servicio; así es como identificarás tu servicio en tu cuenta New Relic: - - * OTEL_SERVICE_NAME=getting-started-python - - 4. En el mismo directorio `getting-started-guides/python/Instrumented/` , cree y active un entorno virtual, instale la biblioteca requerida y ejecute la aplicación: - - * Mac OS: - - ``` - python3 -m venv venv - source venv/bin/activate - pip install -r requirements.txt - python3 app.py - ``` - - * Potencia Shell: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - pip install -r requirements.txt - python app.py - ``` - - 5. Abra una nueva pestaña de terminal, cambie al directorio `getting-started-guides/python/Instrumented` y ejecute el siguiente comando para generar algo de tráfico a la aplicación: - - * Mac OS: - - ``` - ./load-generator.sh - ``` - - * Potencia Shell: - - ``` - .\load-generator.ps1 - ``` - - - Alternativamente, puede llegar al extremo en el browser en esta URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Reemplace `INSERT_A_VALUE` con un valor de 1 a 90. Para generar un error, inserte un número entero fuera del rango válido. - - - 6. Vaya a **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services**. - - 7. Haga clic en su nueva entidad (servicio) llamada `getting-started-python` y explore la UI. Para obtener más consejos sobre qué buscar en la UI, consulte [Ver sus datos en New Relic](#view-data). - - 8. Cuando haya terminado de ver sus datos en la UI, cierre la aplicación presionando `CONTROL+C` en ambas sesiones de terminal. - - - - ### Monitor la aplicación de demostración con el agente OpenTelemetry Python [#python-agent] - - Aquí hay un tutorial diferente que también usa la misma aplicación de demostración, pero en este caso, usará el agente OpenTelemetry Python para monitor automáticamente la aplicación de demostración. No es necesario modificar el código fuente de Python. Al utilizar el agente, puede comenzar rápidamente a exportar datos de muestra a New Relic. - - Sin embargo, tenga en cuenta que deberá agregar instrumentación personalizada para capturar niveles más profundos de información sobre la aplicación, como logs y métricas personalizadas. - - El agente de instrumentación automática es un paquete PyPI de serie que inyecta dinámicamente código de bytes para capturar telemetría de bibliotecas y marcos populares. También puede usarlo para capturar datos como solicitudes entrantes, llamadas HTTP salientes y llamadas de base de datos. Se puede adjuntar a cualquier aplicación Python 3. - - - Consulte la [documentación oficial del agente OpenTelemetry Python](https://opentelemetry.io/docs/instrumentation/python/automatic/) para obtener opciones de configuración adicionales. - - - Para monitor nuestra aplicación de demostración con el agente OpenTelemetry Python: - - 1. Ejecute estos dos comandos para descargar el repositorio de la aplicación de demostración y cambiar al siguiente directorio: - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` - - 2. Vaya a nuestra [sección de referencia de variables de entorno](#ref-env-vars) a continuación para ver qué variables necesita exportar y luego volver a estos pasos. - - 3. Luego, en el mismo directorio `getting-started-guides/python/Uninstrumented/` , cree y active un entorno virtual: - - * Mac OS: - - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * Potencia Shell: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` - - 4. Ahora está listo para instalar la biblioteca requerida: - - ``` - pip install flask - pip install opentelemetry-instrumentation-flask - pip install opentelemetry-exporter-otlp - pip install opentelemetry-distro - ``` - - 5. Continúe en `getting-started-guides/python/Uninstrumented/` para lanzar el agente con la aplicación: - - * Mac OS: - - ``` - opentelemetry-instrument python3 app.py - ``` - - * Potencia Shell: - - ``` - opentelemetry-instrument python app.py - ``` - - 6. Genere tráfico a la aplicación abriendo una nueva terminal en el directorio `getting-started-guides/python/Uninstrumented` y ejecutando el generador de carga: - - * Mac OS: - - ``` - ./load-generator.sh - ``` - - * Potencia Shell: - - ``` - .\load-generator.ps1 - ``` - - - Alternativamente, puede llegar al extremo en el browser en esta URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Reemplace `INSERT_A_VALUE` con un valor de 1 a 90. Para generar un error, inserte un número entero fuera del rango válido. - - - 7. Ahora que ha enviado algunos datos a New Relic, consulte nuestras [instrucciones sobre cómo ver los datos en la UI](#view-data). - - 8. Cuando haya terminado de ver sus datos en la UI, cierre la aplicación presionando `CONTROL+C` en ambas sesiones de terminal. - - - - ### Configure la aplicación de demostración manualmente [#manual-instrum] - - El tutorial anterior le ayudó a explorar la instrumentación automática con el agente OpenTelemetry Python. Este tutorial le mostrará cómo utilizar instrumentación personalizada para tener más control sobre la telemetría que recopila. Luego, verá cómo configurar el SDK de OpenTelemetry para exportar los datos a New Relic. - - - - ### Descargue la aplicación de demostración [#download] - - Ejecute lo siguiente para descargar nuestra aplicación de demostración: - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - ``` - - - - ### Instalar la biblioteca requerida [#libraries] - - Para agregar la biblioteca requerida: - - 1. Vaya al directorio de la aplicación no instrumentada como punto de partida para este tutorial. Al final de este tutorial, el código debería verse como el del directorio `Instrumented` . - - ``` - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` - - 2. Cree y active un entorno virtual en el directorio `Uninstrumented` : - - * Mac OS: - - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * Potencia Shell: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` - - 3. Instale lo siguiente: - - ``` - 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 - ``` - - - - ### Configurar el SDK [#config-sdk] - - 1. En `app.py`, agregue las líneas resaltadas a continuación al **top of the file**. Cambie el valor del atributo personalizado `environment` según sea necesario. - - ```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. Vaya a nuestra [sección de referencia de variables de entorno](#ref-env-vars) a continuación para ver qué variables necesita exportar y luego avance al siguiente paso para agregar la biblioteca de instrumentación. - - - - ### Añadir instrumentación biblioteca: traza [#library-traces] - - En `app.py`, inserte lo siguiente después del `OpenTelemetry Settings` que agregó: - - ```python - ########## - # Traces # - ########## - from opentelemetry import trace - from opentelemetry.sdk.trace import TracerProvider - from opentelemetry.sdk.trace.export import BatchSpanProcessor - 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 - # 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())) - ``` - - - - ### Agregar biblioteca de instrumentación: métrica [#library-metrics] - - En `app.py` agregue lo siguiente después de la sección `Traces` que agregó en el Paso 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.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 - 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.") - ``` - - - - ### Agregar biblioteca de instrumentación: log [#library-logs] - - En `app.py`, agregue lo siguiente después de la sección `Metrics` . Esto importará el módulo de logging y establecerá el nivel de logging `basicConfig` en `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.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' - _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())))) - ``` - - - - ### Agregar instrumentación de matraz [#flask-instrum] - - En `app.py` agregue las líneas resaltadas a continuación, después de la sección `Logs` . Esto ayuda a vincular tramos para rastreo distribuido y contexto de inicio de sesión: - - ```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) - ``` - - - - ### Traza instrumentación personalizada: Crear un tramo personalizado [#cust-span] - - Puede crear los intervalos que desee y depende de usted anotar sus intervalos con atributos en operaciones específicas. El atributo que establezca proporcionará contexto adicional sobre la operación específica que está rastreando, como resultados o propiedades de la operación. - - En `app.py`, inserte las líneas resaltadas a continuación para iniciar un nuevo intervalo llamado `/fibonacci` que hace lo siguiente: - - * Captura datos sobre la ejecución de este método. - - * Establece un atributo que almacena el valor de n de la solicitud del usuario. - - ```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) - ``` - - - - ### Instrumentación de traza personalizada: Registrar una excepción [#span-exception] - - Es posible que desee registrar las excepciones a medida que ocurren. Le recomendamos hacer esto junto con la configuración del estado del intervalo. - - 1. Para establecer el código de estado del intervalo en `ERROR` cuando se produce una excepción, utilizará los módulos `Status` y `StatusCode` del `opentelemetry.trace.status package` que agregó en el paso [D](#library-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.http.trace_exporter import OTLPSpanExporter - from opentelemetry.trace.status import Status, StatusCode - ``` - - 2. A continuación, inserte las líneas resaltadas a continuación para registrar la excepción, que se mostrará como un evento de intervalo en New Relic, y establezca el estado del intervalo en `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) - ``` - - - - ### Instrumentación métrica personalizada: Añadir un contador métrica personalizada [#cust-metrics] - - Las métricas son un tipo telemetry data que son realmente útiles porque combinan mediciones individuales en agregaciones y producen datos que son constantes en función de la carga del sistema. Puede utilizar estos datos junto con intervalos para ayudar a detectar tendencias y proporcionar telemetría en tiempo de ejecución de la aplicación. También puede anotar cualquier métrica con un atributo para ayudar a describir qué subdivisión de las medidas representa la métrica. - - La API de OpenTelemetry métrica define una serie de instrumentados, que registran mediciones que son agregadas por el SDK de métrica y exportadas fuera de proceso. Hay dos tipos de instrumentado: - - * Síncrono: Estos instrumentados registran las mediciones a medida que ocurren. - * Asincrónico: Estos instrumentados registran un callback, el cual se invoca solo una vez por colección y no tiene contexto asociado - - 1. En el paso [E](#library-metrics), agregó la línea resaltada a continuación, que creará un contador: - - ```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.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 - 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. A continuación, agregue las líneas resaltadas a continuación para usar el contador que acaba de crear para medir: - - * El número de veces que esta función se ejecuta correctamente - * El número de veces que no se ejecuta - - Tenga en cuenta que el contador se restablecerá a 0 cada vez que reinicie su aplicación. - - ```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) - ``` - - - - ### Instrumentación log personalizados [#cust-log] - - El estado de la señal de log en OpenTelemetry Python es actualmente [experimental](https://github.com/open-telemetry/opentelemetry-python#project-status). - - En `app.py`, agregue las líneas resaltadas a continuación para: - - * Registre un log de nivel `INFO` para los valores de entrada y salida. - * Registre un log de nivel `ERROR` cuando el valor de entrada esté fuera del rango válido - - ```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) - ``` - - - - ### Ejercite la aplicación para generar algo de tráfico. [#exercise-app] - - ¡Estás listo para enviar algunos datos a New Relic! - - 1. En la terminal, confirma que estás en el directorio `getting-started-guides/python/Uninstrumented` y luego ejecuta la aplicación: - - * Mac OS: - - ``` - python3 app.py - ``` - - * Potencia Shell: - - ``` - python app.py - ``` - - 2. Genere tráfico a la aplicación abriendo una nueva pestaña de terminal en el directorio `getting-started-guides/python/Uninstrumented` y ejecutando el generador de carga: - - * Mac OS: - - ``` - ./load-generator.sh - ``` - - * Potencia Shell: - - ``` - .\load-generator.ps1 - ``` - - - Alternativamente, puede llegar al extremo en el browser en esta URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Reemplace `INSERT_A_VALUE` con un valor de 1 a 90. Para generar un error, inserte un número entero fuera del rango válido. - - - 3. Ahora que ha enviado algunos datos a New Relic, consulte nuestras [instrucciones sobre cómo ver los datos en la UI](#view-data). - - - - - - -## Vea los datos de su demostración en New Relic [#view-data] - -No importa qué tutorial haya completado, puede seguir los consejos a continuación para encontrar sus datos en la UI de New Relic. - -Tenga en cuenta que si siguió [el Tutorial 2: monitor la aplicación de demostración con el agente OpenTelemetry Python:](#python-agent), no verá los datos personalizados (como la métrica personalizada y el log), ya que necesita agregar manualmente instrumentación personalizada para capturar datos más granulares. - -1. Vaya a - - **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services** - - . - -2. Haga clic en su nueva entidad (servicio) llamada `getting-started-python` (o cualquier nombre que haya proporcionado). - -3. Consulte los detalles en las secciones para cada tipo de datos. - - - Si está utilizando Microsoft Windows y no ve datos en su cuenta New Relic, verifique que haya permitido el tráfico a través del firewall. - - -### Traza [#traces] - -Una vez que hayas llegado a la entidad `getting-started-python` en New Relic: - -1. En la sección - - **Monitor** - - del panel izquierdo, haga clic en - - **Distributed tracing** - - y luego haga clic en el grupo de trazas `/fibonacci` . - - Screenshot showing how to find your trace group - -2. Desde allí, busca una traza con un error y haz clic para abrirla: - - Screenshot showing an error in distributed tracing - -3. Una vez que tenga la traza abierta, haga clic en `Show in-process spans` y luego haga clic en el tramo resultante, lo que abrirá un panel de detalles a la derecha. Para ver la excepción que registró cuando la entrada de un usuario no es válida, haga clic en `View span events`: - - Screenshot of in-process spans - -Si completó el tutorial de instrumentación manual, así es como se verá la excepción que registró como un lapso en New Relic: - -Screenshot showing an exception as a span event - -Para ver detalles adicionales que configuró, como el atributo de intervalo, el nombre del intervalo y el código de estado, haga clic en la pestaña **Attributes** . En este panel también puede ver metadatos adicionales que recopila automáticamente la biblioteca de instrumentación que utilizó en esta guía, así como los metadatos adjuntos de New Relic: - -Screenshot of the attributes tab - -Para obtener más detalles sobre cómo ver sus datos, consulte [OpenTelemetry en la UI de New Relic](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page) - -### Métrica [#metrics] - -Una vez que haya llegado a la entidad `getting-started-python` en New Relic, podrá ver una lista de todas las métricas recopiladas, como su atributo de contador personalizado. - -#### Explorador métrico [#metrics-explorer] - -Esta es una herramienta que te permite ver una lista de tus métricas. - -1. En el panel izquierdo, seleccione **Data > Metrics explorer** y luego seleccione `fibonacci.invocations`. - - Screenshot showing metrics explorer - -2. En **Dimensions**, vea el atributo que recopiló junto con su métrica personalizada y luego haga clic en **fibonacci.valid.n**. - - Screenshot showing the total number of invocations of fibonacci function - -Conozca más en nuestra documentación sobre la [vista del explorador métrica](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-metrics-explorer-page). - -### Logs [#logs] - -Aquí es donde acceder a su log: - -Screenshot showing the main logs page - -También verás iniciar sesión en tu terminal: - -Screenshot showing logs in a terminal - -De vuelta en su vista de log, seleccione un log y verá un panel abierto con el mensaje de log y los atributos adicionales que se recopilaron, como el intervalo asociado y los identificadores de traza, así como los metadatos inyectados por New Relic: - -Screenshot showing log details with trace - -Puedes navegar al rastreo distribuido correlacionado haciendo clic en este pequeño icono azul: - -Screenshot showing how to find correlated trace - -Esto abrirá un panel que muestra la traza correlacionada, donde podrá ver más detalles sobre la traza. Para obtener más información sobre esta página, consulte [OpenTelemetry en la UI: página de rastreo distribuido](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page/) y [Comprender y utilizar la UI de rastreo distribuido](/docs/distributed-tracing/ui-data/understand-use-distributed-tracing-ui/): - -Screenshot showing the trace waterfall from the logs section - -También puede encontrar el log correlacionado desde la vista de rastreo distribuido. Cuando selecciones una traza que tenga su correspondiente log, lo verás indicado como una pestaña, y podrás visualizar el log directamente desde la traza sin tener que cambiar de vista: - -Screenshot showing how to see log details from a trace span - -Obtenga más información sobre la vista de registro [aquí](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-logs). - -## Referencia: variables de entorno [#ref-env-vars] - -Esta es una lista de las variables de entorno que debes exportar si estás realizando el tutorial 2 o 3. Una vez que termine de exportar las variables, regrese a los tutoriales utilizando los enlaces que siguen a la lista de variables: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- OTEL_EXPORTER_OTLP_HEADERS=api-key=YOUR_LICENSE_KEY - - * Encabezados: Esto determina a qué cuenta de New Relic se enviarán sus datos. Reemplace `YOUR_LICENSE_KEY` con su - - - - . -
- OTEL_EXPORTER_OTLP_ENDPOINT=[https://otlp.nr-data.net](https://otlp.nr-data.net) (Para EE. UU.) - - * Este es el extremo al que se exportará la telemetría de su aplicación. Exportar datos al extremo OTLP de New Relic. Si estás en la UE, utiliza este extremo: OTEL_EXPORTER_OTLP_ENDPOINT=[https://otlp.eu01.nr-data.net](https://otlp.eu01.nr-data.net) -
- OTEL_SERVICE_NAME=getting-started-python - - * Este es el nombre que asocia la telemetría de su aplicación con una entidad en New Relic. En este tutorial lo llamamos `getting-started-python`, pero puedes llamarlo como quieras. -
- OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_OWN_ID_HERE - - * Reemplace `INSERT_YOUR_OWN_ID_HERE` con un ID único de la instancia. Por ejemplo, podrías usar `1234`. Para obtener más detalles, consulte [Convenciones semánticas de recursos](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service) de OpenTelemetry. -
- OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT=4095 - - * Establecer un límite en la longitud máxima del valor del atributo evitará que los datos del intervalo se eliminen si exceden el [límite del atributo](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/#attribute-limits). -
- OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=Delta - - * New Relic admite métrica en temporalidad delta en lugar del valor predeterminado de acumulativa. -
- OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=base2_exponential_bucket_histogram - - * (Recomendado) Agregación de histogramas: utilice un histograma exponencial en lugar del histograma de depósito explícito predeterminado para una mejor compresión de datos. -
- OTEL_LOGS_EXPORTER=otlp - - * Habilite la exportación log a través de OTLP. La exportación log está deshabilitada de forma predeterminada. -
- OTEL_EXPORTER_OTLP_COMPRESSION=gzip - - * (Recomendado) Configurar la compresión gzip le permite maximizar la cantidad de datos que puede enviar por solicitud. Nuestro tamaño de carga útil máximo permitido es 1 MB (10^6 bytes). La compresión Gzip tiene un buen rendimiento y reduce la salida de datos. -
- OTEL_EXPERIMENTAL_EXPORTER_OTLP_RETRY_ENABLED=true - - * (Recomendado) Habilite el reintento de exportación experimental para ayudar a hacer frente a la falta de confiabilidad de Internet. -
- OTEL_EXPERIMENTAL_RESOURCE_DISABLED_KEYS=process.command_line - - * (Recomendado) Esto deshabilita el atributo de recurso `process.command_line` , que a menudo excede el límite de longitud máxima del atributo New Relic y puede contener información confidencial. -
-
-
- -Una vez que haya exportado las variables de entorno enumeradas en el colapsador anterior, regrese al tutorial y complete la configuración: - -* [Tutorial 2: monitor la aplicación de demostración con el agente OpenTelemetry Python](#python-agent) -* [Tutorial 3: configurar la aplicación de demostración manualmente](#manual-instrum) - -## ¿Que sigue? [#what-next] - -Ahora que experimentó con la instrumentación de OpenTelemetry y la configuración del SDK, puede aplicar lo que aprendió para configurar su propia aplicación o servicio con OpenTelemetry y New Relic. Para obtener más información, consulte [Configure su propia aplicación o servicio con OpenTelemetry](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro). \ No newline at end of file diff --git a/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx b/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx deleted file mode 100644 index 2a72c427ff5..00000000000 --- a/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx +++ /dev/null @@ -1,1198 +0,0 @@ ---- -title: 'OpenTelemetry チュートリアル: サンプル Java アプリを計測する' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: 'To test out OpenTelemetry on a sample app instead of your own app, consider these three tutorials.' -freshnessValidatedDate: never -translationType: machine ---- - -import opentelemetrySpringBootASCIIDisplay from 'images/opentelemetry_screenshot-crop_Spring-Boot-ASCII-display.webp' - -import opentelemetryMainDistributedTracingPage from 'images/opentelemetry_screenshot-crop_main-distributed-tracing-page.webp' - -import opentelemetryDistributedTracingError from 'images/opentelemetry_screenshot-crop_distributed-tracing-error.webp' - -import opentelemetryInProcessSpans from 'images/opentelemetry_screenshot-crop_in-process-spans.webp' - -import opentelemetryExceptiononSpanEvent from 'images/opentelemetry_screenshot-crop_exception-on-span-event.webp' - -import opentelemetryAttributesTab from 'images/opentelemetry_screenshot-crop_attributes-tab.webp' - -import opentelemetryMetricsExplorerMain from 'images/opentelemetry_screenshot-crop_metrics-explorer-main.webp' - -import opentelemetryMetricsExplorerDimensions from 'images/opentelemetry_screenshot-crop_metrics-explorer-dimensions.webp' - -import opentelemetryJvmsPageMain from 'images/opentelemetry_screenshot-crop_jvms-page-main.webp' - -import opentelemetryCompareJvmInstances from 'images/opentelemetry_screenshot-full_compare-jvm-instances.webp' - -import opentelemetryJvmColorCodedComparison from 'images/opentelemetry_screenshot-full_jvm-color-coded-comparison.webp' - -import opentelemetryMainLogsPage from 'images/opentelemetry_screenshot-full_main-logs-page.webp' - -import opentelemetryLogsinTerminal from 'images/opentelemetry_screenshot-full_logs-in-terminal.webp' - -import opentelemetryLogDetailsWithTrace from 'images/opentelemetry_screenshot-full_log-details-with-trace.webp' - -import opentelemetryTraceRelatedtoLog from 'images/opentelemetry_screenshot-full_trace-related-to-log.webp' - -import opentelemetryTraceWaterfallFromLog from 'images/opentelemetry_screenshot-full_trace-waterfall-from-log.webp' - -import opentelemetryLogCapturedinTraceSpan from 'images/opentelemetry_screenshot-full_log-captured-in-trace-span.webp' - -import opentelemetryTraceDurationDemoChart from 'images/opentelemetry_screenshot-crop_jvm-metric-charts.webp' - -これらの Java チュートリアルを試して、New Relic プラットフォームが OTLP データで何ができるかを確認してください。選択できる 3 つのチュートリアルがあり、それぞれ同じデモ Spring アプリを使用しています。アプリはフィボナッチ数列の n 番目の数値を計算し、トレース、メトリクス、ログを生成します。 - -これらのチュートリアルに取り組むことで、OpenTelemetry と New Relic を使用して独自のアプリをセットアップするのに役立つスキルを習得できます。 - -Screenshot showing various JVM metric charts - -
- これらのチュートリアルのいずれかを終了すると、JVM メトリックを次のようなグラフで表示できます。 -
- -## 要件 [#requirements] - -始めるには、次のものが揃っていることを確認してください。 - -* New Relic アカウント:[無料アカウント](https://newrelic.com/signup)をまだお持ちでない場合は、サインアップしてください。 -* Java 17 以降: まだお持ちでない場合は、こちら[のダウンロード オプション](https://www.java.com/en/download/manual.jsp)を参照してください。 - -## チュートリアル [#tutorials] - -各チュートリアルでは同じデモ アプリを使用しますが、OpenTelemetry と New Relic に慣れるのに役立つ異なるアプローチが用意されています。 - -* [プレインストゥルメント化されたアプリ](#pre-instrumented-tutorial): プレインストゥルメント化されたデモ アプリを実行すると、UI でデータを簡単に確認できます。 -* [OpenTelemetry Java エージェント](#java-agent-tutorial): OpenTelemetry Java エージェントを使用してデモ アプリを監視します。 -* [手動セットアップ](#manual-setup-tutorial): デモアプリを手動でインストルメントしました。 - -完了したいチュートリアルに応じて、下のタブをクリックしてください。 - - - OpenTelemetry を使用する場合、OTLP 経由でアプリケーションから New Relic にデータをエクスポートするには 2 つの選択肢があります。 - - * アプリから New Relic に直接 - * アプリは OpenTelemetry Collector にデータを送信し、そこで New Relic にエクスポートされます。 - - これらのチュートリアルでは、最初のオプションについて説明します。 コレクター経由でデータをエクスポートする場合は、この[コレクターのドキュメント](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/collector-processing/opentelemetry-collector-processing-intro)で詳細を確認してください。 - - - - - - 事前にインストルメント化されたアプリ - - - - OpenTelemetry Java エージェント - - - - 手動セットアップ - - - - - - ### 事前にインストルメント化されたデモ アプリを実行する [#pre-instrum] - - これは、New Relic にデータを送信して UI で表示することがどのようなものかをすぐに確認できるように、インストルメンテーションを当社に実行してもらいたい場合に最適なオプションです。 - - 1. ターミナルで次のコマンドを実行してデモ アプリのクローンを作成し、Getting Started Guides の`java`ディレクトリに移動します。 - - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/java - ``` - - 2. 次の 2 つの環境変数を設定して、New Relic アカウントにデータを送信します。 - - * 必ずを使用してください。 - - * New Relic データセンターのリージョンが EU で US ではない場合、エンドポイントを次のように設定します。 `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_PROTOCOL=http/protobuf` - - 3. 以下の最初の環境変数を設定してサービスに名前を付け、次に 2 番目の環境変数をサービス インスタンス ID に設定します。これにより、特定のプラットフォーム機能がアクティブになります。デフォルトではログがオフになっているため、最後にログを有効にします。 - - * `OTEL_SERVICE_NAME=getting-started-java` - - * `OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_ID_HERE` - - * `INSERT_YOUR_OWN_ID_HERE`一意のインスタンス ID に置き換えます。たとえば、1234 を使用できます。 - - * `OTEL_LOGS_EXPORTER=otlp` - - 4. 同じ`getting-started-guides/java`ディレクトリで、アプリケーションをビルドして実行します。 - - * マックOS: - - ```bash - ./gradlew bootRun - ``` - - * パワーシェル: - - ```bash - .\gradlew.bat build - ``` - - 5. 新しいターミナル タブを開き、 `getting-started-guides/java/Instrumented`ディレクトリに切り替え、次のコマンドを実行してアプリケーションへのトラフィックを生成します: - - * マックOS: - - ```bash - ./load-generator.sh - ``` - - * パワーシェル: - - ```bash - .\load-generator.ps1 - ``` - - - または、ブラウザの次の URL でエンドポイントにアクセスできます: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE` 。`INSERT_A_VALUE`を 1 から 90 の値に置き換えます。エラーを生成するには、有効範囲外の整数を挿入します。 - - - 6. **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services**に移動します。 - - 7. `getting-started-java`という新しいエンティティ (サービス) をクリックして、UI を調べます。UI で何を探すべきかについてのその他のヒントについて[は、New Relic でデータを表示する](#view-data)を参照してください。 - - 8. UI でデータを見終わったら、両方のターミナル セッションで CONTROL+C を押してアプリケーションをシャットダウンします。 - - - - ### OpenTelemetry Java エージェントを使用してデモ アプリを監視する [#java-agent] - - これは、同じデモ アプリを使用する別のチュートリアルです。この場合、OpenTelemetry Java エージェントを使用して、デモ アプリを自動的に監視します。Java ソース コードを変更する必要はありません。エージェントを使用すると、New Relic へのサンプル データのエクスポートをすぐに開始できます。 - - 自動インスツルメンテーション エージェントは、バイトコードを動的に挿入して一般的なライブラリやフレームワークからテレメトリを取得する JAR ファイルです。また、インバウンド要求、アウトバウンド HTTP 呼び出し、およびデータベース呼び出しなどのデータをキャプチャするためにも使用できます。任意の Java 8+ アプリケーションにアタッチできます。 - - - 追加の構成オプションについては、 [Java エージェントの公式ドキュメント](https://opentelemetry.io/docs/instrumentation/java/automatic/)を参照してください。 - - - OpenTelemetry Java エージェントを使用してデモ アプリを監視するには: - - 1. エージェントとインストルメンテーション ライブラリを含む[エージェント JAR ファイル](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/latest/download/opentelemetry-javaagent.jar)をダウンロードします。好みのディレクトリに配置し、後で使用するパスを書き留めます。 - - 2. まだ行っていない場合は、デモ アプリケーション リポジトリをダウンロードして、次のディレクトリに切り替えます。 - - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/java - ``` - - 3. 次のコマンドでデモ アプリをビルドします。 - - * マックOS: - - ```bash - ./gradlew build - ``` - - * パワーシェル: - - ```bash - .\gradlew.bat build - ``` - - - ビルドが成功すると、結果として得られるアプリケーション JAR ファイルが `Uninstrumented/build/libs`にあり、その名前は `uninstrumented.jar`になります。 - - - 4. 以下の[環境変数の参照セクション](#ref-env-vars)に移動して、エクスポートする必要がある変数を確認してから、これらの手順に戻ります。 - - 5. `getting-started-guides/java/Uninstrumented`に進み、アプリでエージェントを起動します。 - - - `path/to`を、以前にダウンロードした JAR ファイルの場所に置き換えます。 - - - ```bash - java -javaagent:path/to/opentelemetry-javaagent.jar \ - -jar ./build/libs/uninstrumented.jar - ``` - - 6. `getting-started-guides/java/Uninstrumented`ディレクトリで新しいターミナルを開き、ロード ジェネレーターを実行して、アプリケーションへのトラフィックを生成します。 - - * マックOS: - - ```bash - ./load-generator.sh - ``` - - * パワーシェル: - - ```bash - .\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 を押してアプリケーションをシャットダウンします。 - - - - ### デモアプリを手動でセットアップする [#manual-instrum] - - 前のチュートリアルは、OpenTelemetry Java エージェントを使用した自動インストゥルメンテーションを探索するのに役立ちました。 このチュートリアルでは、カスタムインストゥルメンテーションを使用して、収集したテレメトリーをより詳細に制御する方法を説明します。 インストゥルメンテーションをデモアプリに手動で挿入してテレメトリーをキャプチャし、そのデータを New Relic にエクスポートするように SDK を設定します。 - - - SDK を手動で構成することもできますが、 [自動構成オプション](https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/autoconfigure)を使用して SDK を構成する方法を紹介します。これにより、環境変数とシステム プロパティを使用してプロセスが簡素化されます。 - - - - - #### デモアプリケーションをダウンロードする [#download] - - デモ アプリをまだダウンロードしていない場合は、次を実行します。 - - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - ``` - - - - #### 依存関係のインストール [#dependencies] - - 依存関係を追加するには: - - 1. アプリケーション ディレクトリに移動します。 - - ```bash - cd newrelic-opentelemetry-examples/getting-started-guides/java/uninstrumented - ``` - - 2. `build.gradle`を開きます。 - - 3. 次の強調表示された項目を`dependencies`ブロックに追加します (コード ブロック内を下にスクロールする必要がある場合があります)。 - - ```gradle lineHighlight=29-42 - plugins { - id 'org.springframework.boot' version '2.7.5' - id 'io.spring.dependency-management' version '1.1.0' - id 'java' - } - - java { - toolchain { - languageVersion = JavaLanguageVersion.of(17) - } - } - - repositories { - mavenCentral() - } - - bootRun { - mainClass.set 'com.example.demo.Application' - } - - configurations.all { - exclude module: 'spring-boot-starter-logging' - } - - dependencies { - implementation 'org.springframework.boot:spring-boot-starter-web' - implementation 'org.springframework.boot:spring-boot-starter-log4j2' - - // OpenTelemetry core - implementation platform('io.opentelemetry:opentelemetry-bom:1.22.0') - implementation platform('io.opentelemetry:opentelemetry-bom-alpha:1.22.0-alpha') - implementation 'io.opentelemetry:opentelemetry-api' - implementation 'io.opentelemetry:opentelemetry-sdk' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp-logs' - implementation 'io.opentelemetry:opentelemetry-sdk-extension-autoconfigure' - - // OpenTelemetry instrumentation - implementation platform('io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom-alpha:1.22.1-alpha') - implementation 'io.opentelemetry.instrumentation:opentelemetry-runtime-metrics' - implementation 'io.opentelemetry.instrumentation:opentelemetry-log4j-appender-2.17' - implementation 'io.opentelemetry.instrumentation:opentelemetry-spring-webmvc-6.0' - } - ``` - - メモ: - - * `bom` (部品表) 依存関係は、特定のエコシステムの依存関係のバージョンを同期するために使用されます。OpenTelemetry は多数の Java コンポーネントを公開しているため、使用するコンポーネントが少数であろうと多数であろうと、これらはすべてのバージョンが確実に同期されるようにするのに役立ちます。 - * 残りの依存関係は、SDK、API、OTLP エクスポーター、および計測ライブラリへのアクセスを提供します。 - * spring-boot-starter-logging モジュールを除外する追加の構成があります。これにより、 `log4j-slf4j-impl cannot be present with log4j-to-slf4j`に関連するビルド エラー メッセージが表示されなくなります。 - - - - #### autoconfigure 拡張機能を使用して SDK を構成する [#auto-config-ext] - - SDK を手動で構成することもできますが、プロセスが合理化されるため、自動構成拡張機能を使用することをお勧めします。 - - 1. アプリのソース コード ディレクトリに移動します。 - - ```bash - cd newrelic-opentelemetry-examples/getting-started-guides/java/uninstrumented/src/main/java/com/example/demo - ``` - - 2. `Application.java`を開きます。 - - 3. 強調表示された行を挿入します。 - - ```java lineHighlight=7-12,17-20 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - } - ``` - - 4. 以下の[環境変数の参照セクション](#ref-env-vars)に移動して、エクスポートする必要がある変数を確認してから、これらの手順に戻ります。 - - - - #### インストルメンテーション ライブラリの追加: トレース [#library-traces] - - `Application.java`で、トレース フィルタを登録して、強調表示されている Spring Web MVC のインストルメンテーションを追加します。 - - ```java lineHighlight=22-26 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - - - - #### インストルメンテーション ライブラリの追加: メトリクス [#library-metrics] - - `Application.java`ファイルに以下を登録して、Java ランタイムに関する指標を生成および収集します。以下の強調表示された行を挿入します。 - - ```java lineHighlight=14-20 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - // Register runtime metrics instrumentation - BufferPools.registerObservers(openTelemetrySdk); - Classes.registerObservers(openTelemetrySdk); - Cpu.registerObservers(openTelemetrySdk); - GarbageCollector.registerObservers(openTelemetrySdk); - MemoryPools.registerObservers(openTelemetrySdk); - Threads.registerObservers(openTelemetrySdk); - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - - - - #### インストルメンテーション ライブラリの追加: ログ [#library-logs] - - このデモ アプリケーションは、 `GlobalLoggerProvider` を使用する`OpenTelemetryAppender`を( `log4j.xml`経由で) 使用するように構成されています。`GlobalLoggerProvider`を設定すると、ここで autoconfigure を使用して構成された Log SDK に`OpenTelemetryAppender`が接続されます。 - - 1. `Application.java`を開きます。 - - 2. 次の強調表示された行を挿入します。 - - ```java lineHighlight=14-15 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - // Set GlobalLoggerProvider, which is used by Log4j2 appender - GlobalLoggerProvider.set(openTelemetrySdk.getSdkLoggerProvider()); - - // Register runtime metrics instrumentation - BufferPools.registerObservers(openTelemetrySdk); - Classes.registerObservers(openTelemetrySdk); - Cpu.registerObservers(openTelemetrySdk); - GarbageCollector.registerObservers(openTelemetrySdk); - MemoryPools.registerObservers(openTelemetrySdk); - Threads.registerObservers(openTelemetrySdk); - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - - 3. `Uninstrumented/src/main`に`resources`というディレクトリを作成します。 - - 4. この新しいディレクトリに、次の内容の`log4j2.xml`というファイルを作成します: - - ```xml - - - - - - - - - - - - - - - - ``` - - - この行の`packages=...`セクションにより、Log4J は`OpenTelemetryAppender`を見つけて構成できます。ソース コードは[OpenTelemetry リポジトリ](https://github.com/open-telemetry/opentelemetry-java-instrumentation/tree/main/instrumentation/log4j/log4j-appender-2.17/library)にあり、 `io.opentelemetry.instrumentation:opentelemetry-log4j-appender-2.17`を介して依存関係として追加されました) - - - - - #### カスタム トレース インストルメンテーション: スパン属性定数の作成 [#custom-attribs] - - 各トレースはスパンで構成されています。スパンは、作業の論理単位または特定の要求内の操作を表します。以下のコードは、次のことを示しています。 - - * スパンでリクエストレベルの洞察を提供するために使用できる属性キーを保持する静的定数 - * スパンを作成する[Tracer](https://opentelemetry.io/docs/concepts/signals/traces/#tracer)を初期化する方法 - - 次の強調表示された行を`Controller.java`に挿入します。 - - ```java lineHighlight=4-14 - @RestController - public class Controller { - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - - private final Tracer tracer; - - @Autowired - Controller(OpenTelemetry openTelemetry) { - // Initialize tracer - tracer = openTelemetry.getTracer(Controller.class.getName()); - } - - @GetMapping(value = "/fibonacci") - . . . - } - ``` - - - - #### カスタム トレース インストルメンテーション: カスタム スパンの作成 [#cust-span] - - 必要なスパンを作成できます。特定の操作に関する属性でスパンに注釈を付けるのはあなた次第です。設定した属性は、結果や操作のプロパティなど、追跡している特定の操作に関する追加のコンテキストを提供します。 - - 1. `Controller.java`で、これらの強調表示された行を挿入して、 `fibonacci`という名前の新しいスパンを開始します。これは次のことを行います: - - * このメソッドの実行に関するデータをキャプチャします - * ユーザーのリクエストから n の値を格納する属性を設定します - - ```java lineHighlight=2-3 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - . . . - } - ``` - - 2. 成功したリクエストに関する情報を保存する属性をスパンに追加して、コードに詳細を追加します。 - - ```java lineHighlight=20-21 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - try { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, last); - return last; - } catch (IllegalArgumentException e) { - throw e; - } - } - ``` - - - - #### カスタム トレース インストルメンテーション: 例外を記録する [#span-exception] - - 発生した例外を記録したい場合があります。これは、スパン ステータスの設定と併せて行うことをお勧めします。まず、スパンを現在のスパンとして設定し、例外が発生した場合にステータス コードをエラーに設定してから、スパンを終了します。 - - ```java lineHighlight=5-6,26-27,29-32 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - ユーザーが無効な入力を提供した場合、このメソッドは`IllegalArgumentException`をスローします。これが発生すると、例外がスパンのイベントとして記録され、スパンのステータスが`ERROR`に設定されます。例外メッセージは、ステータスの説明としてキャプチャされます。例外は、発生したスパンでイベントとして記録されます。 - - 最後に、 `ErrorHandler`クラスの`handleException()`で、次の強調表示された行でスパンのステータスを`ERROR`に設定します。 - - ```java lineHighlight=10-11 - @ControllerAdvice - private static class ErrorHandler { - - @ExceptionHandler({ - IllegalArgumentException.class, - MissingServletRequestParameterException.class, - HttpRequestMethodNotSupportedException.class - }) - public ResponseEntity handleException(Exception e) { - // Set the span status and description - Span.current().setStatus(StatusCode.ERROR, e.getMessage()); - return new ResponseEntity<>(Map.of("message", e.getMessage()), HttpStatus.BAD_REQUEST); - } - } - ``` - - 前の手順と同様に、これにより、ユーザーが無効な数値を入力した場合にスパンのステータス コードが設定されます。ただし、これは`fibonacci()`ではなく例外ハンドラで発生するため、現在のスパンがリクエストの親スパンになります。この親スパンは、Application クラスのフィルターを介して追加された Spring Web MVC インストルメンテーションから取得されます。これで、アプリケーション エンドポイントが例外を発生させると、親スパンと子スパンの両方のスパン ステータスが`ERROR`になります。 - - - - #### カスタム メトリック インストルメンテーション: カスタム メトリック カウンターを追加します。 [#metrics-cust] - - メトリックは、個々の測定値を集計に結合し、システム負荷の関数として一定のデータを生成するため、非常に役立つテレメトリ データ タイプです。このデータをスパンと組み合わせて使用すると、傾向を特定し、アプリケーションのランタイム テレメトリを提供できます。また、メトリクスが表す測定値の下位区分を説明するのに役立つ属性でメトリクスに注釈を付けることもできます。 - - OpenTelemetry メトリクス API は、メトリクス SDK によって集計され、アウト オブ プロセスでエクスポートされる測定値を記録する多数の計測器を定義します。器具には次の 2 種類があります。 - - * 同期: これらの計測器は、発生時に測定値を記録します。 - * 非同期: これらの計測器はコールバックを登録します。これはコレクションごとに 1 回だけ呼び出され、関連付けられたコンテキストはありません。 - - - OpenTelemetry プロジェクトのメトリックのステータスについて質問がある場合は、[シグナル ステータス](https://opentelemetry.io/docs/instrumentation/java/#status-and-releases)を参照してください。 - - - カスタム カウンターを追加するには、次の手順を実行します。 - - 1. カスタム メトリックのブール属性をインスタンス化し、メトリック インストルメントを初期化します。この場合、 [LongCounter](https://opentelemetry.io/docs/instrumentation/java/manual/#metrics)を使用しています。これは正の値のみを記録し、ネットワーク経由で送信されたバイト数などをカウントするのに役立ちます。デフォルトでは、カウンタ測定値は単調 (常に増加) 合計に集計されます。 - - ```java lineHighlight=7,10,16-21 - @RestController - public class Controller { - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - private static final AttributeKey ATTR_VALID_N = AttributeKey.booleanKey("fibonacci.valid.n"); - - private final Tracer tracer; - private final LongCounter fibonacciInvocations; - - @Autowired - Controller(OpenTelemetry openTelemetry) { - // Initialize tracer - tracer = openTelemetry.getTracer(Controller.class.getName()); - // Initialize instrument - Meter meter = openTelemetry.getMeter(Controller.class.getName()); - fibonacciInvocations = meter - .counterBuilder("fibonacci.invocations") - .setDescription("Measures the number of times the fibonacci method is invoked.") - .build(); - } - . . . - } - ``` - - 2. 次の強調表示された行を挿入して、カスタム カウンターが有効な入力と無効な入力、およびそれぞれの発生回数をキャプチャできるようにします。 - - ```java lineHighlight=24-25,30-31 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - // Counter to increment the number of times a valid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, true)); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - // Counter to increment the number of times an invalid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, false)); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - - - #### カスタムログ計測 [#cust-log] - - OpenTelemetry Java のログ シグナルのステータスは、現在[実験](https://opentelemetry.io/docs/instrumentation/java/#status-and-releases)段階です。ログ メッセージはアプリのルート ハンドラによって管理され、デフォルトで`INFO`レベル以上のログがコンソールに送信されます。ただし、特定のクラスを含めてロギング レベルを変更するか、カスタム ハンドラまたはフィルタをインストールすることで、ロガーの動作を変更できます。 - - ##### ロガーを初期化する [#initialize-logger] - - 前述のとおり、これは`java.util.logging`ライブラリからのものです。Logger は OpenTelemetry コンポーネントではありませんが、アプリケーションは Log4j ログを OpenTelemetry Log SDK に送信するように構成されています。 - - ```java lineHighlight=4-5 - @RestController - public class Controller { - - // Logger (note that this is not an OTel component) - private static final Logger LOGGER = LogManager.getLogger(Controller.class); - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - private static final AttributeKey ATTR_VALID_N = AttributeKey.booleanKey("fibonacci.valid.n"); - . . . - } - ``` - - ##### カスタム ログ メッセージを追加する [#cust-log-messages] - - ロガーを初期化したら、ロガーを使用して次のことを記録できます。 - - * 有効な入力の結果とその結果の値 - * 出力が記録されなかった場合 - - 次の強調表示された行を挿入します。 - - ```java lineHighlight=26-27,34-35 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - // Counter to increment the number of times a valid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, true)); - // Log the result of a valid input - LOGGER.info("Compute fibonacci(" + n + ") = " + result); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - // Counter to increment the number of times an invalid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, false)); - // Log when no output was recorded - LOGGER.info("Failed to compute fibonacci(" + n + ")"); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - - - #### アプリを実行してトラフィックを生成する [#exercise-app] - - New Relic にデータを送信する準備ができました! - - 1. ディレクトリ`getting-started-guides/java`に移動し、次のコマンドでアプリをビルドして実行します: - - * マックOS: - - ```bash - ./gradlew bootRun - ``` - - * パワーシェル: - - ```bash - .\gradlew.bat build - ``` - - - 端末に Spring ASCII が表示された場合は、アプリが正常にビルドされ、実行されていることを意味します。 - - Screenshot showing Spring Boot ASCII logo - - - 2. `getting-started-guides/java/Uninstrumented`ディレクトリで新しいターミナルを開き、ロード ジェネレータを実行して、アプリケーションからトラフィックを生成します。 - - * マックOS: - - ```bash - ./load-generator.sh - ``` - - * パワーシェル: - - ```bash - .\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 でデータを見つけるための以下のヒントに従うことができます。 - -1. **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services** - - に移動します。 - -2. `getting-started-java`という名前の新しいエンティティ (サービス) (または任意の名前) をクリックします。 - -3. 各データ型のセクションで詳細を確認してください。 - - - Windows を使用していて、New Relic アカウントにデータが表示されない場合は、ファイアウォールを通過するトラフィックが許可されていることを確認してください。 - - -### トレース [#traces] - -New Relic で`getting-started-java`エンティティに到達したら: - -1. 左側のペインの - - **Monitor** - - セクションで、 - - **Distributed tracing** - - をクリックし、 - - **Fibonacci** - - トレース グループをクリックします。 - - Screenshot showing the main distributed tracing page - -2. そこから、エラーのあるトレースを探し、クリックして開きます。 - - OpenTelemetry Java エージェントでは、 New Relic APM Java エージェントとは異なる結果が表示される場合があります。これは、2 つのエージェント タイプ間でエラー処理に違いがあるためです。詳細については、 [OpenTelemetryおよびNew Relicでのエラー率の処理」を](https://newrelic.com/blog/how-to-relic/error-rate-opentelemetry-and-new-relic)参照してください。 - - 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 - -スパン属性、スパン名、ステータス コードなど、設定した追加の詳細を表示するには、 **Attributes**タブをクリックします。 このペインには、このガイドで使用したインストゥルメンテーション ライブラリによって自動的に収集された追加のメタデータや、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-java`エンティティに到達すると、ランタイム メトリック (JVM) やカスタム カウンター属性など、収集されたすべてのメトリックのリストが表示されます。 - -#### メトリクスエクスプローラー [#metrics-explorer] - -これは、メトリックのリストを表示できるツールです。 - -1. 左側のペインで、 **Data > Metrics explorer**を選択し、次に`fibonacci.invocations`を選択します。 - - Screenshot showing metrics explorer - -2. **Dimensions**で、収集した属性とカスタムメトリックを表示し、 **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)に関するドキュメントをご覧ください。 - -#### JVM [#jvms] - -また、JVM ページに移動して、スループット、メモリ使用量、1 分あたりのガベージ コレクション時間など、Java ランタイム メトリックの視覚化を表示することもできます。 - -Screenshot of the main JVMs page - -単一のインスタンスのメトリックを表示するか、複数のインスタンスを選択して比較できます。 - -Screenshot of how to compare JVM instances - -インスタンスを選択して**Compare**をクリックすると、次のような内容が表示されます。各インスタンスは簡単に識別できるように色分けされています。 - -Screenshot showing the color-coded JVM comparison - -詳細については、 [JVM ビュー](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-jvms-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/best-practices/opentelemetry-best-practices-logs)ご覧ください。 - -## 参考:環境変数 [#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` (米国の場合) `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.eu01.nr-data.net` (EU の場合) - - * これは、アプリケーション テレメトリのエクスポート先となるエンドポイントです。New Relic の OTLP エンドポイントにデータをエクスポートします。 -
- `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` - - * これは、New Relic が推奨する OTLP `http/protobuf`を使用することを指定します。 -
- `OTEL_SERVICE_NAME=getting-started-java` - - * これは、アプリケーション テレメトリを New Relic のエンティティに関連付ける名前です。このチュートリアルでは`getting-started-java`と呼んでいますが、任意の名前にすることができます。 -
- `OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_OWN_ID_HERE` - - * `INSERT_YOUR_OWN_ID_HERE`一意のインスタンス ID に置き換えます。たとえば、 `1234`を使用できます。詳細については、「OpenTelemetry の[リソース セマンティック規則」](https://github.com/open-telemetry/semantic-conventions/blob/main/docs/resource/README.md#service-experimental)を参照してください。 -
- `OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT=4095` - - * 属性値の最大長に制限を設定すると、 [属性制限](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/#attribute-limits)を超えた場合にスパン データがドロップされなくなります。 -
- `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=DELTA` - - * New Relic は、デフォルトの累積ではなく、デルタ一時性のメトリクスをサポートします。 -
- `OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=BASE2_EXPONENTIAL_BUCKET_HISTOGRAM` - - * (推奨) ヒストグラム集約: データ圧縮を向上させるために、既定の明示的なバケット ヒストグラムの代わりに指数ヒストグラムを使用します。 -
- `OTEL_LOGS_EXPORTER=otlp` - - * OTLP 経由のログ エクスポートを有効にします。ログのエクスポートはデフォルトで無効になっています。 -
- `OTEL_EXPORTER_OTLP_COMPRESSION=gzip` - - * (推奨) gzip 圧縮を設定すると、リクエストごとに送信できるデータ量を最大化できます。最大許容ペイロード サイズは 1MB (10^6 バイト) です。Gzip 圧縮はパフォーマンスが高く、データ出力が低くなります。 -
- `OTEL_EXPERIMENTAL_EXPORTER_OTLP_RETRY_ENABLED=true` - - * (推奨) 実験的なエクスポートの再試行を有効にして、インターネットの信頼性の低さに対処します。 -
- `OTEL_EXPERIMENTAL_RESOURCE_DISABLED_KEYS=process.command_line` - - * (推奨) これにより、多くの場合、New Relic の最大属性長制限を超え、機密情報が含まれている可能性がある`process.command_line`リソース属性が無効になります。 -
-
-
- -上記のコラプスにリストされている環境変数を作成したら、チュートリアルに戻ってセットアップを完了します。 - -* [チュートリアル 2 (OpenTelemetry Java エージェントを使用してデモ アプリを監視する)](#java-agent) -* [チュートリアル 3 (デモ アプリを手動でセットアップする)](#auto-config-ext) - -## 次は何ですか? [#what-next] - -OpenTelemetryインストゥルメンテーションと SDK 設定を試したので、学んだことを応用して、 OpenTelemetryとNew Relicを使用して独自のアプリまたはサービスをセットアップできます。 詳細については、 [「OpenTelemetry を使用して独自のアプリまたはサービスをセットアップする」](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro)を参照してください。 \ No newline at end of file diff --git a/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx b/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx deleted file mode 100644 index 4af6fe0a38e..00000000000 --- a/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx +++ /dev/null @@ -1,907 +0,0 @@ ---- -title: 'OpenTelemetry チュートリアル: サンプル Python アプリをインストゥルメントする' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: 'To test out OpenTelemetry on a sample Pythyon app instead of your own app, consider these three 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' - -これらの Python チュートリアルのいずれかを試して、New Relic プラットフォームが OTLP データで何ができるかを確認してください。 選択できる 3 つのチュートリアルがあり、それぞれ同じデモ Flask アプリを使用しています。 アプリはフィボナッチ数列の n 番目の数値を計算し、トレース、メトリクス、ログを生成します。 - -これらのチュートリアルのいずれかを進めることで、OpenTelemetry と New Relic を使用して独自のアプリをセットアップするのに役立つスキルを学ぶことができます。 - -Screenshot showing response time, throughput, and error rate - -
- これらのチュートリアルのいずれかを完了すると、次のようなグラフでスパン メトリックを表示できるようになります。 -
- -## 要件 [#requirements] - -開始する前に、次のものが揃っていることを確認してください。 - -* New Relic アカウント:[無料アカウント](https://newrelic.com/signup)をまだお持ちでない場合は、サインアップしてください。 -* Python 3.8 以降、および pip (Python バージョン 3.4 以降に含まれる): これらをまだお持ちでない場合は、これらの [ダウンロード オプション](https://www.python.org/downloads/)を参照してください。 - -## チュートリアル [#tutorials] - -各チュートリアルでは同じデモ アプリを使用しますが、OpenTelemetry と New Relic に慣れるのに役立つ異なるアプローチが用意されています。 - -* [プレインストゥルメント化されたアプリ](#pre-instrumented-tutorial): プレインストゥルメント化されたデモ アプリを実行すると、UI でデータを簡単に確認できます。 -* [OpenTelemetry Python エージェント](#python-agent-tutorial): OpenTelemetry Python エージェントを使用してデモ アプリを監視します。 -* [手動セットアップ](#manual-setup-tutorial): デモアプリを手動でインストルメントしました。 - -完了したいチュートリアルに応じて、下のタブをクリックしてください。 - - - OpenTelemetry を使用する場合、OTLP 経由でアプリケーションから New Relic にデータをエクスポートするには 2 つの選択肢があります。 - - * アプリから New Relic に直接 - * アプリは OpenTelemetry Collector にデータを送信し、そこで New Relic にエクスポートされます。 - - これらのチュートリアルでは、最初のオプションについて説明します。 コレクター経由でデータをエクスポートする場合は、この[コレクターのドキュメント](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/collector-processing/opentelemetry-collector-processing-intro)で詳細を確認してください。 - - - - - - 事前にインストルメント化されたアプリ - - - - OpenTelemetry Python エージェント - - - - 手動セットアップ - - - - - - ### 事前にインストルメント化されたデモ アプリを実行する [#pre-instrum] - - New Relic にデータを送信し、UI で表示するのがどのようなものかをすばやく確認できるように、インストルメンテーションを行う場合は、これが最適なオプションです。 - - 1. ターミナルで次のコマンドを実行してデモ アプリのクローンを作成し、Getting Started Guides の`python/Instrumented`ディレクトリに移動します。 - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/python/Instrumented - ``` - - 2. New Relic アカウントにデータを送信するには、次の環境変数を設定します。 - - * 必ずを使用してください。 - - * New Relic データセンターのリージョンが EU で US ではない場合、エンドポイントを次のように設定します。 `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](https://otlp.nr-data.net) - - 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 > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services**に移動します。 - - 7. `getting-started-python`という新しいエンティティ (サービス) をクリックして、UI を調べます。UI で何を探すべきかについてのその他のヒントについて[は、New Relic でデータを表示する](#view-data)を参照してください。 - - 8. UI でデータを確認し終わったら、両方のターミナル セッションで `CONTROL+C` を押してアプリケーションをシャットダウンします。 - - - - ### 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` を押してアプリケーションをシャットダウンします。 - - - - ### デモアプリを手動でセットアップする [#manual-instrum] - - 前のチュートリアルは、OpenTelemetry Python エージェントを使用した自動インストゥルメンテーションを探索するのに役立ちました。 このチュートリアルでは、カスタムインストゥルメンテーションを使用して、収集したテレメトリーをより詳細に制御する方法を説明します。 次に、OpenTelemetry SDK を設定してデータを New Relic にエクスポートする方法を説明します。 - - - - ### デモアプリケーションをダウンロードする [#download] - - 以下を実行してデモ アプリをダウンロードします。 - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - ``` - - - - ### 必要なライブラリをインストールする [#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 - ``` - - - - ### SDKを設定する [#config-sdk] - - 1. `app.py`で、以下の強調表示された行を**top of the file**に追加します。 必要に応じて、カスタムアトリビュート`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) に移動して、エクスポートする必要がある変数を確認してから、インストルメンテーション ライブラリを追加する次の手順に進みます。 - - - - ### インストルメンテーション ライブラリの追加: トレース [#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.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 - # 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())) - ``` - - - - ### インストルメンテーション ライブラリの追加: メトリクス [#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.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 - 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.") - ``` - - - - ### インストルメンテーション ライブラリの追加: ログ [#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.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' - _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())))) - ``` - - - - ### 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) - ``` - - - - ### カスタム トレース インストルメンテーション: カスタム スパンの作成 [#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) - ``` - - - - ### カスタム トレース インストルメンテーション: 例外を記録する [#span-exception] - - 例外が発生したときに、例外を記録したい場合があります。スパンステータスの設定と併せてこれを行うことをお勧めします。 - - 1. 例外が発生したときにスパンのステータス コードを`ERROR`に設定するには、手順[D](#library-traces)で追加した`opentelemetry.trace.status package`の`Status`モジュールと`StatusCode`モジュールを使用します。 - - ```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.http.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) - ``` - - - - ### カスタム メトリック インストルメンテーション: カスタム メトリック カウンターを追加します。 [#cust-metrics] - - メトリックは、個々の測定値を集計に結合し、システム負荷の関数として一定のデータを生成するため、非常に役立つテレメトリ データ タイプです。このデータをスパンと組み合わせて使用すると、傾向を特定し、アプリケーションのランタイム テレメトリを提供できます。また、メトリクスが表す測定値の下位区分を説明するのに役立つ属性でメトリクスに注釈を付けることもできます。 - - OpenTelemetry メトリクス API は、メトリクス SDK によって集計され、アウト オブ プロセスでエクスポートされる測定値を記録する多数の計測器を定義します。器具には次の 2 種類があります。 - - * 同期: これらの計測器は、発生時に測定値を記録します。 - * 非同期: これらの計測器はコールバックを登録します。これはコレクションごとに 1 回だけ呼び出され、関連付けられたコンテキストはありません。 - - 1. ステップ[E](#library-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.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 - 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) - ``` - - - - ### カスタムログ計測 [#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) - ``` - - - - ### アプリを実行してトラフィックを生成する [#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 > All capabilities](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 - -スパン属性、スパン名、ステータス コードなど、設定した追加の詳細を表示するには、 **Attributes**タブをクリックします。 このペインには、このガイドで使用したインストゥルメンテーション ライブラリによって自動的に収集された追加のメタデータや、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. **Dimensions**で、収集した属性とカスタムメトリックを表示し、 **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/best-practices/opentelemetry-best-practices-logs)ご覧ください。 - -## 参考:環境変数 [#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](https://otlp.nr-data.net) (米国の場合) - - * これは、アプリケーション テレメトリのエクスポート先となるエンドポイントです。New Relic の OTLP エンドポイントにデータをエクスポートします。EU 内にいる場合は、次のエンドポイントを使用します: OTEL_EXPORTER_OTLP_ENDPOINT= [https://otlp.eu01.nr-data.net](https://otlp.eu01.nr-data.net) -
- 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 - - * 属性値の最大長に制限を設定すると、 [属性制限](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/#attribute-limits)を超えた場合にスパン データがドロップされなくなります。 -
- OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=デルタ - - * New Relic は、デフォルトの累積ではなく、デルタ一時性のメトリクスをサポートします。 -
- OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=base2_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/apm-monitoring/opentelemetry-apm-intro)を参照してください。 \ No newline at end of file diff --git a/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx b/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx deleted file mode 100644 index 15606d2319a..00000000000 --- a/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx +++ /dev/null @@ -1,1198 +0,0 @@ ---- -title: 'OpenTelemetry 튜토리얼: 샘플 Java 앱 계측' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: 'To test out OpenTelemetry on a sample app instead of your own app, consider these three tutorials.' -freshnessValidatedDate: never -translationType: human ---- - -import opentelemetrySpringBootASCIIDisplay from 'images/opentelemetry_screenshot-crop_Spring-Boot-ASCII-display.webp' - -import opentelemetryMainDistributedTracingPage from 'images/opentelemetry_screenshot-crop_main-distributed-tracing-page.webp' - -import opentelemetryDistributedTracingError from 'images/opentelemetry_screenshot-crop_distributed-tracing-error.webp' - -import opentelemetryInProcessSpans from 'images/opentelemetry_screenshot-crop_in-process-spans.webp' - -import opentelemetryExceptiononSpanEvent from 'images/opentelemetry_screenshot-crop_exception-on-span-event.webp' - -import opentelemetryAttributesTab from 'images/opentelemetry_screenshot-crop_attributes-tab.webp' - -import opentelemetryMetricsExplorerMain from 'images/opentelemetry_screenshot-crop_metrics-explorer-main.webp' - -import opentelemetryMetricsExplorerDimensions from 'images/opentelemetry_screenshot-crop_metrics-explorer-dimensions.webp' - -import opentelemetryJvmsPageMain from 'images/opentelemetry_screenshot-crop_jvms-page-main.webp' - -import opentelemetryCompareJvmInstances from 'images/opentelemetry_screenshot-full_compare-jvm-instances.webp' - -import opentelemetryJvmColorCodedComparison from 'images/opentelemetry_screenshot-full_jvm-color-coded-comparison.webp' - -import opentelemetryMainLogsPage from 'images/opentelemetry_screenshot-full_main-logs-page.webp' - -import opentelemetryLogsinTerminal from 'images/opentelemetry_screenshot-full_logs-in-terminal.webp' - -import opentelemetryLogDetailsWithTrace from 'images/opentelemetry_screenshot-full_log-details-with-trace.webp' - -import opentelemetryTraceRelatedtoLog from 'images/opentelemetry_screenshot-full_trace-related-to-log.webp' - -import opentelemetryTraceWaterfallFromLog from 'images/opentelemetry_screenshot-full_trace-waterfall-from-log.webp' - -import opentelemetryLogCapturedinTraceSpan from 'images/opentelemetry_screenshot-full_log-captured-in-trace-span.webp' - -import opentelemetryTraceDurationDemoChart from 'images/opentelemetry_screenshot-crop_jvm-metric-charts.webp' - -이 Java 튜토리얼을 통해 뉴렐릭 플랫폼이 OTLP 데이터로 무엇을 할 수 있는지 알아볼 수 있습니다. 세 가지 튜토리얼 중 선택할 수 있으며, 각 튜토리얼은 동일한 데모 Spring 앱을 사용합니다. 앱은 피보나치 수열의 n번째 숫자를 계산하고 트레이스, 메트릭 및 로그를 생성합니다. - -이 튜토리얼을 통해 OpenTelemetry과 뉴렐릭을 사용하여 자신만의 앱을 설정하는 데 도움이 되는 기술을 배울 수 있습니다. - -Screenshot showing various JVM metric charts - -
- 이 튜토리얼을 마친 후에는 차트에서 다음과 같은 JVM 메트릭를 볼 수 있습니다. -
- -## 요구 사항 [#requirements] - -시작하려면 다음을 먼저 확인하십시오. - -* 뉴렐릭 계정: 아직 계정이 없다면 [무료 계정](https://newrelic.com/signup)을 신청합니다. -* Java 17 이상: 아직 설치하지 않은 경우 [다운로드 옵션](https://www.java.com/en/download/manual.jsp)을 확인합니다. - -## 튜토리얼 [#tutorials] - -각 튜토리얼은 동일한 데모 앱을 사용하지만 OpenTelemetry와 뉴렐릭에 익숙해지는 데 도움이 되는 다양한 접근 방식을 제공합니다. - -* [사전 계측된 앱](#pre-instrumented-tutorial): UI에서 데이터를 빠르게 확인하려면 사전 계측된 데모 앱을 실행합니다. -* [OpenTelemetry Java 에이전트](#java-agent-tutorial): OpenTelemetry Java 에이전트로 데모 앱을 모니터링합니다. -* [수동 설정](#manual-setup-tutorial): 데모 앱을 수동으로 다운로드했습니다. - -완료하려는 튜토리얼의 탭을 클릭하십시오. - - - OpenTelemetry를 사용할 때 OTLP를 통해 애플리케이션에서 뉴렐릭으로 데이터를 내보내는 두 가지 방식 중 선택할 수 있습니다. - - * 앱에서 뉴렐릭으로 직접 내보내기 - * 앱이 데이터를 OpenTelemetry 컬렉터(수집기)로 보낸 후 뉴렐릭으로 내보내기 - - 이 튜토리얼에서는 첫 번째 옵션을 다룹니다. 컬렉터를 통해 데이터를 내보내려면 이 [컬렉터 문서](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/collector-processing/opentelemetry-collector-processing-intro)에서 보다 자세한 내용을 확인하십시오. - - - - - - 사전 계측된 앱 - - - - OpenTelemetry Java 에이전트 - - - - 수동 설정 - - - - - - ### 사전 계측된 데모 앱 실행 [#pre-instrum] - - 이는 뉴렐릭이 계측을 수행하도록 하여 뉴렐릭으로 어떻게 데이터를 보내고 UI에서 볼 수 있는지 빠르게 확인하려는 경우에 좋은 옵션입니다. - - 1. 터미널에서 다음을 실행하여 데모 앱을 복제하고 시작 가이드의 `java` 디렉터리로 이동합니다. - - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/java - ``` - - 2. 뉴렐릭 계정으로 데이터를 보내려면 다음 두 가지 환경 변수를 설정해야 합니다. - - * 반드시 를 사용해야 합니다. - - * 뉴렐릭 데이터센터 지역이 미국이 아닌 EU인 경우 엔드포인트를 다음으로 설정합니다: `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_PROTOCOL=http/protobuf` - - 3. 아래의 첫 번째 환경 변수를 설정하여 서비스 이름을 지정하고, 두 번째 환경 변수를 서비스 인스턴스 ID로 설정하여 특정 플랫폼 기능을 활성화합니다. 마지막으로 로깅은 기본적으로 꺼져 있으므로 로그를 활성화합니다. - - * `OTEL_SERVICE_NAME=getting-started-java` - - * `OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_ID_HERE` - - * `INSERT_YOUR_OWN_ID_HERE`를 고유한 인스턴스 ID로 바꿉니다. 예: 1234 - - * `OTEL_LOGS_EXPORTER=otlp` - - 4. 동일한 `getting-started-guides/java` 디렉터리에서 애플리케이션을 빌드하고 실행합니다. - - * MacOS: - - ```bash - ./gradlew bootRun - ``` - - * PowerShell: - - ```bash - .\gradlew.bat build - ``` - - 5. 새 터미널 탭을 열고 `getting-started-guides/java/Instrumented` 디렉터리로 전환한 후 다음 명령을 실행하여 애플리케이션에 대한 일부 트래픽을 생성합니다. - - * MacOS: - - ```bash - ./load-generator.sh - ``` - - * PowerShell: - - ```bash - .\load-generator.ps1 - ``` - - - 또는 브라우저의 URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`에서 엔드포인트에 도달할 수 있습니다. `INSERT_A_VALUE`를 1에서 90 사이의 값으로 바꿉니다. 오류를 생성하려면 유효한 범위 밖의 정수를 삽입합니다. - - - 6. **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services**으로 이동합니다. - - 7. `getting-started-java`라는 새 엔터티(서비스)를 클릭하고 UI를 탐색합니다. UI에서 찾아야 할 사항에 대한 자세한 내용은 [뉴렐릭에서 데이터 보기](#view-data)를 참조하십시오. - - 8. UI에서 데이터 확인을 마쳤으면 두 터미널 세션 모두에서 Control+C를 눌러 애플리케이션을 종료합니다. - - - - ### OpenTelemetry Java 에이전트를 통한 데모 앱 모니터링 [#java-agent] - - 다음은 동일한 데모 앱을 사용하는 다른 방법을 설명하는 튜토리얼입니다. 이 경우 OpenTelemetry Java 에이전트를 사용하여 데모 앱을 자동으로 모니터링하게 됩니다. Java 소스 코드를 수정할 필요가 없습니다. 에이전트를 사용하면 샘플 데이터를 뉴렐릭으로 빠르게 내보내기할 수 있습니다. - - 자동 계측 에이전트는 널리 사용되는 라이브러리 및 프레임워크에서 텔메트리를 캡처하기 위해 바이트코드를 동적으로 삽입하는 JAR 파일입니다. 또한 이를 사용하여 인바운드 요청, 아웃바운드 HTTP 호출 및 데이터베이스 호출과 같은 데이터를 캡처할 수 있습니다. 모든 Java 8+ 애플리케이션에 첨부할 수 있습니다. - - - 추가 구성 옵션은 [공식 Java 에이전트 문서](https://opentelemetry.io/docs/instrumentation/java/automatic/)를 참조하십시오. - - - OpenTelemetry Java 에이전트를 사용하여 데모 앱을 모니터링하려면: - - 1. 에이전트 및 계측 라이브러리가 포함된 [에이전트 JAR 파일](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/latest/download/opentelemetry-javaagent.jar)을 다운로드합니다. 원하는 디렉터리에 배치하고 나중에 사용할 수 있도록 경로를 기록해 둡니다. - - 2. 아직 다운로드하지 않았다면 데모 애플리케이션 저장소를 다운로드하고 다음 디렉터리로 전환합니다. - - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/java - ``` - - 3. 다음 명령을 사용하여 데모 앱을 빌드합니다. - - * MacOS: - - ```bash - ./gradlew build - ``` - - * PowerShell: - - ```bash - .\gradlew.bat build - ``` - - - 성공적으로 빌드되면 `Uninstrumented/build/libs`에서 `uninstrumented.jar`라는 애플리케이션 JAR 파일을 찾을 수 있습니다. - - - 4. 아래의 [환경 변수 참조 섹션](#ref-env-vars)으로 이동하여 내보내야 하는 변수를 확인한 후 이 단계로 돌아옵니다. - - 5. 앱으로 에이전트를 시작하려면 `getting-started-guides/java/Uninstrumented`에서 계속합니다. - - - `path/to`를 다운로드해 둔 JAR 파일의 위치로 교체합니다. - - - ```bash - java -javaagent:path/to/opentelemetry-javaagent.jar \ - -jar ./build/libs/uninstrumented.jar - ``` - - 6. `getting-started-guides/java/Uninstrumented` 디렉터리에서 새 터미널을 열고 로드 생성기를 실행하여 애플리케이션에 대한 트래픽을 생성합니다. - - * MacOS: - - ```bash - ./load-generator.sh - ``` - - * PowerShell: - - ```bash - .\load-generator.ps1 - ``` - - - 또는 브라우저의 URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`에서 엔드포인트에 도달할 수 있습니다. `INSERT_A_VALUE`를 1에서 90 사이의 값으로 바꿉니다. 오류를 생성하려면 유효한 범위 밖의 정수를 삽입합니다. - - - 7. 이제 일부 데이터를 뉴렐릭으로 보냈으므로 [UI에서 데이터를 보는 방법에 대한 지침을](#view-data)을 참조합니다. - - 8. UI에서 데이터 확인을 마쳤으면 두 터미널 세션 모두에서 Control+C를 눌러 애플리케이션을 종료합니다. - - - - ### 데모 앱 수동 설정 [#manual-instrum] - - 이전 튜토리얼에서는 OpenTelemetry Java 에이전트를 사용한 자동 계측에 대해 설명했습니다. 이 튜토리얼에서는 커스텀 계측을 사용해 수집한 텔레메트리를 더 효과적으로 제어하는 방법을 설명합니다. 계측을 데모 앱에 수동으로 삽입하여 텔레메트리를 캡처하고, 해당 데이터를 뉴렐릭으로 내보내도록 SDK를 구성할 수 있습니다. - - - SDK를 수동으로 구성할 수도 있지만 환경 변수와 시스템 속성을 사용하여 프로세스를 간소화하는 [자동 구성 옵션](https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/autoconfigure)을 사용해 SDK를 구성하는 방법을 보여 드리겠습니다. - - - - - #### 데모 애플리케이션 다운로드 [#download] - - 아직 데모 앱을 다운로드하지 않았다면 다음을 실행합니다. - - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - ``` - - - - #### 종속성(dependencies) 설치 [#dependencies] - - 종속성을 추가하려면: - - 1. 애플리케이션 디렉터리로 이동합니다. - - ```bash - cd newrelic-opentelemetry-examples/getting-started-guides/java/uninstrumented - ``` - - 2. `build.gradle`을 엽니다. - - 3. 다음 강조 표시된 항목을 `dependencies` 블록에 추가합니다. (코드 블록 내에서 아래로 스크롤해야 할 수도 있음) - - ```gradle lineHighlight=29-42 - plugins { - id 'org.springframework.boot' version '2.7.5' - id 'io.spring.dependency-management' version '1.1.0' - id 'java' - } - - java { - toolchain { - languageVersion = JavaLanguageVersion.of(17) - } - } - - repositories { - mavenCentral() - } - - bootRun { - mainClass.set 'com.example.demo.Application' - } - - configurations.all { - exclude module: 'spring-boot-starter-logging' - } - - dependencies { - implementation 'org.springframework.boot:spring-boot-starter-web' - implementation 'org.springframework.boot:spring-boot-starter-log4j2' - - // OpenTelemetry core - implementation platform('io.opentelemetry:opentelemetry-bom:1.22.0') - implementation platform('io.opentelemetry:opentelemetry-bom-alpha:1.22.0-alpha') - implementation 'io.opentelemetry:opentelemetry-api' - implementation 'io.opentelemetry:opentelemetry-sdk' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp-logs' - implementation 'io.opentelemetry:opentelemetry-sdk-extension-autoconfigure' - - // OpenTelemetry instrumentation - implementation platform('io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom-alpha:1.22.1-alpha') - implementation 'io.opentelemetry.instrumentation:opentelemetry-runtime-metrics' - implementation 'io.opentelemetry.instrumentation:opentelemetry-log4j-appender-2.17' - implementation 'io.opentelemetry.instrumentation:opentelemetry-spring-webmvc-6.0' - } - ``` - - 참고: - - * `bom`(자재 명세서) 종속성은 특정 생태계를 위한 종속성 버전을 동기화하는 데 사용됩니다. OpenTelemetry는 많은 Java 구성 요소를 게시하므로 사용 개수에 관계없이 모든 버전을 동기화하는 데 도움이 됩니다. - * 나머지 종속성은 SDK, API, OTLP 엑스포터, 계측 라이브러리에 대한 액세스를 제공합니다. - * spring-boot-starter-logging 모듈을 제외하는 추가 설정이 있습니다. 이렇게 하면 `log4j-slf4j-impl cannot be present with log4j-to-slf4j`와 관련된 빌드 오류 메시지가 표시되지 않습니다. - - - - #### 자동 구성 확장을 사용한 SDK 구성 [#auto-config-ext] - - SDK를 수동으로 구성할 수도 있지만 프로세스를 간소화하는 자동 구성 확장을 사용하는 것이 좋습니다. - - 1. 앱의 소스 코드 디렉터리로 이동합니다. - - ```bash - cd newrelic-opentelemetry-examples/getting-started-guides/java/uninstrumented/src/main/java/com/example/demo - ``` - - 2. `Application.java`을 엽니다. - - 3. 강조 표시된 줄을 삽입합니다. - - ```java lineHighlight=7-12,17-20 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - } - ``` - - 4. 아래의 [환경 변수 참조 섹션](#ref-env-vars)으로 이동하여 내보내야 하는 변수를 확인한 후 이 단계로 돌아옵니다. - - - - #### 계측 라이브러리 추가: 트레이스 [#library-traces] - - `Application.java`에서 추적 필터를 등록하여 Spring Web MVC에 대해 강조 표시된 계측을 추가합니다. - - ```java lineHighlight=22-26 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - - - - #### 계측 라이브러리 추가: 메트릭 [#library-metrics] - - `Application.java` 파일에 다음을 등록하여 Java 런타임에 대한 메트릭를 생성하고 수집합니다. 아래에 강조 표시된 줄을 삽입합니다. - - ```java lineHighlight=14-20 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - // Register runtime metrics instrumentation - BufferPools.registerObservers(openTelemetrySdk); - Classes.registerObservers(openTelemetrySdk); - Cpu.registerObservers(openTelemetrySdk); - GarbageCollector.registerObservers(openTelemetrySdk); - MemoryPools.registerObservers(openTelemetrySdk); - Threads.registerObservers(openTelemetrySdk); - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - - - - #### 계측 라이브러리 추가: 로그 [#library-logs] - - 이 데모 애플리케이션은 `GlobalLoggerProvider`를 사용하는 `OpenTelemetryAppender`( `log4j.xml`을 통해)을 사용하도록 구성되었습니다. `GlobalLoggerProvider`를 설정하면 여기에서 자동 구성을 사용하여 구성된 로그 SDK에 `OpenTelemetryAppender`가 연결됩니다. - - 1. `Application.java`을 엽니다. - - 2. 다음 강조 표시된 줄을 삽입합니다. - - ```java lineHighlight=14-15 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - // Set GlobalLoggerProvider, which is used by Log4j2 appender - GlobalLoggerProvider.set(openTelemetrySdk.getSdkLoggerProvider()); - - // Register runtime metrics instrumentation - BufferPools.registerObservers(openTelemetrySdk); - Classes.registerObservers(openTelemetrySdk); - Cpu.registerObservers(openTelemetrySdk); - GarbageCollector.registerObservers(openTelemetrySdk); - MemoryPools.registerObservers(openTelemetrySdk); - Threads.registerObservers(openTelemetrySdk); - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - - 3. `Uninstrumented/src/main`에 `resources`라는 디렉터리를 만듭니다. - - 4. 이 새 디렉터리에서 다음 콘텐츠로 `log4j2.xml`이라는 파일을 만듭니다. - - ```xml - - - - - - - - - - - - - - - - ``` - - - 이 줄의 `packages=...` 섹션을 사용하면 Log4J가 `OpenTelemetryAppender`를 찾고 구성할 수 있습니다. 소스 코드는 [OpenTelemetry 저장소](https://github.com/open-telemetry/opentelemetry-java-instrumentation/tree/main/instrumentation/log4j/log4j-appender-2.17/library)에 있으며, `io.opentelemetry.instrumentation:opentelemetry-log4j-appender-2.17` 통해 하나의 종속성으로 추가되었습니다. - - - - - #### 커스텀 트레이스 계측: 스팬 속성 상수 생성 [#custom-attribs] - - 각 트레이스는 논리적 작업 단위 또는 특정 요청 내의 작업을 나타내는 스팬(span)으로 구성됩니다. 아래 코드는 다음을 보여줍니다. - - * 스팬에서 요청 수준 인사이트를 제공하는 데 사용할 속성 키를 보유하는 정적 상수 - * 스팬을 생성하는 [트레이서](https://opentelemetry.io/docs/concepts/signals/traces/#tracer) 초기화 방법 - - 강조 표시된 다음 줄을 `Controller.java`에 삽입합니다. - - ```java lineHighlight=4-14 - @RestController - public class Controller { - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - - private final Tracer tracer; - - @Autowired - Controller(OpenTelemetry openTelemetry) { - // Initialize tracer - tracer = openTelemetry.getTracer(Controller.class.getName()); - } - - @GetMapping(value = "/fibonacci") - . . . - } - ``` - - - - #### 커스텀 트레이스 계측: 커스텀 스팬 생성 [#cust-span] - - 원하는 모든 스팬을 생성할 수 있으며, 특정 작업에 대한 속성으로 스팬에 주석을 추가할 수도 있습니다. 설정한 속성은 결과나 작업 속성 등 추적 중인 특정 작업에 대한 추가 컨텍스트를 제공합니다. - - 1. `Controller.java`에서 강조 표시된 줄을 삽입하여 다음을 수행하는 `fibonacci`라는 새 스팬을 시작합니다. - - * 이 메소드 실행에 대한 데이터를 캡처합니다. - * 사용자 요청의 n 값을 저장하는 속성을 설정합니다. - - ```java lineHighlight=2-3 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - . . . - } - ``` - - 2. 성공적인 요청에 대한 정보를 저장하기 위해 스팬에 속성을 추가하여 코드에 세부적인 세부 정보를 추가합니다. - - ```java lineHighlight=20-21 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - try { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, last); - return last; - } catch (IllegalArgumentException e) { - throw e; - } - } - ``` - - - - #### 커스텀 트레이스 계측: 예외 기록 [#span-exception] - - 예외가 발생하는 대로 기록하길 원할 수 있습니다. 스팬 상태 설정과 함께 이 작업을 수행하는 것이 좋습니다. 먼저 스팬을 현재 스팬으로 설정하고, 예외 발생 시 상태 코드를 오류로 설정한 후 스팬을 종료합니다. - - ```java lineHighlight=5-6,26-27,29-32 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - 사용자가 잘못된 입력을 제공하는 경우 이 메서드는 `IllegalArgumentException`을 발생시킵니다. 이 경우 예외는 스팬에 이벤트로 기록되고 스팬의 상태는 `ERROR`로 설정됩니다. 예외 메시지는 상태 설명으로 캡처됩니다. 예외는 발생한 스팬에서 이벤트로 기록됩니다. - - 마지막으로 `ErrorHandler` 클래스의 `handleException()`에서 다음과 같이 강조 표시된 줄을 사용하여 스팬 상태를 `ERROR`로 설정합니다. - - ```java lineHighlight=10-11 - @ControllerAdvice - private static class ErrorHandler { - - @ExceptionHandler({ - IllegalArgumentException.class, - MissingServletRequestParameterException.class, - HttpRequestMethodNotSupportedException.class - }) - public ResponseEntity handleException(Exception e) { - // Set the span status and description - Span.current().setStatus(StatusCode.ERROR, e.getMessage()); - return new ResponseEntity<>(Map.of("message", e.getMessage()), HttpStatus.BAD_REQUEST); - } - } - ``` - - 이전 단계와 마찬가지로, 이렇게 하면 사용자가 잘못된 숫자를 입력하는 경우 스팬의 상태 코드가 설정됩니다. 그러나 이는 `fibonacci()`가 아닌 예외 핸들러에서 발생하므로 현재 스팬은 요청에 대한 상위 스팬입니다. 이 상위 스팬은 Spring Web MVC 계측에서 가져온 것으로, 애플리케이션 클래스의 필터를 통해 추가되었습니다. 이제 애플리케이션 엔드포인트에서 예외가 발생하면 상위 스팬과 하위 스팬 모두 스팬 상태가 `ERROR`가 됩니다. - - - - #### 커스텀 메트릭 계측: 커스텀 메트릭 카운터 추가 [#metrics-cust] - - 메트릭은 개별 측정을 집계로 결합하고 시스템 로드에 따라 일정한 데이터를 생성하기 때문에 매우 유용한 텔레메트리 데이터 유형입니다. 스팬과 함께 이 데이터를 사용하여 추세를 파악하고 애플리케이션 런타임 텔레메트리를 제공할 수 있습니다. 또한 메트릭가 나타내는 측정의 하위 구분을 설명하는 데 도움이 되는 속성으로 메트릭에 주석을 달 수 있습니다. - - OpenTelemetry 메트릭 API는 메트릭 SDK에 의해 집계되고 프로세스 외부로 내보내진 측정을 기록하는 계측 개수를 정의합니다. 다음과 같은 두 가지 유형이 있습니다. - - * 동기: 이러한 계측은 발생 시에 측정 값을 기록합니다. - * 비동기: 컬렉션당 한 번만 호출되고 관련 컨텍스트가 없는 콜백을 등록합니다. - - - OpenTelemetry 프로젝트의 메트릭 상태에 대해 질문이 있는 경우 [신호 상태](https://opentelemetry.io/docs/instrumentation/java/#status-and-releases)를 참조하십시오. - - - 커스텀 카운터를 추가하려면 다음을 완료해야 합니다. - - 1. 커스텀 메트릭에 대한 부울 속성을 인스턴스화하고 메트릭 리소스를 초기화합니다. 이 경우에는 양수 값만 기록하고 네트워크를 통해 전송된 바이트 수와 같은 항목을 계산하는 데 유용한 [LongCounter](https://opentelemetry.io/docs/instrumentation/java/manual/#metrics)를 사용하고 있습니다. 기본적으로 카운터 측정은 항상 증가하는 합계로 집계됩니다. - - ```java lineHighlight=7,10,16-21 - @RestController - public class Controller { - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - private static final AttributeKey ATTR_VALID_N = AttributeKey.booleanKey("fibonacci.valid.n"); - - private final Tracer tracer; - private final LongCounter fibonacciInvocations; - - @Autowired - Controller(OpenTelemetry openTelemetry) { - // Initialize tracer - tracer = openTelemetry.getTracer(Controller.class.getName()); - // Initialize instrument - Meter meter = openTelemetry.getMeter(Controller.class.getName()); - fibonacciInvocations = meter - .counterBuilder("fibonacci.invocations") - .setDescription("Measures the number of times the fibonacci method is invoked.") - .build(); - } - . . . - } - ``` - - 2. 커스텀 카운터가 유효한 입력과 유효하지 않은 입력은 물론 각각의 발생 횟수를 캡처할 수 있도록 다음과 같이 강조 표시된 줄을 삽입합니다. - - ```java lineHighlight=24-25,30-31 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - // Counter to increment the number of times a valid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, true)); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - // Counter to increment the number of times an invalid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, false)); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - - - #### 커스텀 로그 계측 [#cust-log] - - OpenTelemetry Java의 로그 신호 상태는 현재 [실험 중](https://opentelemetry.io/docs/instrumentation/java/#status-and-releases) 입니다. 로그 메시지는 루트 핸들러에 의해 관리되며, 기본적으로 `INFO` 수준 이상의 로그를 콘솔로 보냅니다. 그러나 특정 클래스를 포함하여 로깅 수준을 변경하거나 커스텀 핸들러 또는 필터를 설치하여 로거 동작을 변경할 수 있습니다. - - ##### 로거 초기화 [#initialize-logger] - - 이전에 설명한 대로 이는 `java.util.logging` 라이브러리에서 가져온 것입니다. 로거는 OpenTelemetry 구성 요소가 아니지만 애플리케이션은 Log4j 로그를 OpenTelemetry SDK로 보내도록 구성되었습니다. - - ```java lineHighlight=4-5 - @RestController - public class Controller { - - // Logger (note that this is not an OTel component) - private static final Logger LOGGER = LogManager.getLogger(Controller.class); - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - private static final AttributeKey ATTR_VALID_N = AttributeKey.booleanKey("fibonacci.valid.n"); - . . . - } - ``` - - ##### 커스텀 로그 메시지 추가 [#cust-log-messages] - - 로거를 초기화한 후에는 로거를 사용하여 다음을 기록할 수 있습니다. - - * 유효한 입력의 결과와 해당 결과의 값 - * 출력이 기록되지 않은 경우 - - 강조 표시된 다음 줄을 삽입합니다. - - ```java lineHighlight=26-27,34-35 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - // Counter to increment the number of times a valid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, true)); - // Log the result of a valid input - LOGGER.info("Compute fibonacci(" + n + ") = " + result); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - // Counter to increment the number of times an invalid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, false)); - // Log when no output was recorded - LOGGER.info("Failed to compute fibonacci(" + n + ")"); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - - - #### 앱을 실행하여 트래픽을 생성합니다. [#exercise-app] - - 뉴렐릭으로 데이터를 보낼 준비가 되었습니다! - - 1. `getting-started-guides/java` 디렉터리로 이동하고 다음 명령을 사용하여 앱을 빌드하고 실행합니다. - - * MacOS: - - ```bash - ./gradlew bootRun - ``` - - * PowerShell: - - ```bash - .\gradlew.bat build - ``` - - - 터미널에 Spring ASCII가 표시되면 앱이 성공적으로 빌드되어 실행 중임을 의미합니다. - - Screenshot showing Spring Boot ASCII logo - - - 2. `getting-started-guides/java/Uninstrumented` 디렉터리에서 새 터미널을 열고 로드 생성기를 실행하여 애플리케이션에서 트래픽을 생성합니다. - - * MacOS: - - ```bash - ./load-generator.sh - ``` - - * PowerShell: - - ```bash - .\load-generator.ps1 - ``` - - - 또는 브라우저의 URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`에서 엔드포인트에 도달할 수 있습니다. `INSERT_A_VALUE`를 1에서 90 사이의 값으로 바꿉니다. 오류를 생성하려면 유효한 범위 밖의 정수를 삽입합니다. - - - 3. 이제 일부 데이터를 뉴렐릭으로 보냈으므로 [UI에서 데이터를 보는 방법에 대한 지침을](#view-data)을 참조합니다. - - - - - - -## 뉴렐릭에서 데모 데이터 보기 [#view-data] - -어떤 튜토리얼을 완료했는지에 관계없이 아래 팁에 따라 뉴렐릭 UI에서 데이터를 발견할 수 있습니다. - -1. **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services** - - 으로 이동합니다. - -2. `getting-started-java` (또는 제공한 이름)이라는 새 엔터티(서비스)를 클릭합니다. - -3. 각 데이터 유형에 대한 섹션의 세부정보를 확인합니다. - - - Windows를 사용 중이고 뉴렐릭 계정에 데이터가 표시되지 않는 경우, 방화벽이 트래픽을 허용하고 있는지 확인하시기 바랍니다. - - -### 트레이스 [#traces] - -뉴렐릭의 `getting-started-java` 엔터티에 도달하면: - -1. 왼쪽 창의 - - **Monitor** - - 섹션에서 - - **Distributed tracing** - - 을 클릭한 다음, - - **Fibonacci** - - 트레이스 그룹을 클릭합니다. - - Screenshot showing the main distributed tracing page - -2. 거기에서 오류가 있는 트레이스를 찾아 클릭하여 엽니다. - - OpenTelemetry Java 에이전트를 사용하면 뉴렐릭 APM Java 에이전트와 다른 결과가 나타날 수 있습니다. 이는 두 에이전트 유형이 다르게 오류를 처리하기 때문입니다. 자세한 내용은 [OpenTelemetry 및 뉴렐릭에서 오류를 처리하는 방법](https://newrelic.com/blog/how-to-relic/error-rate-opentelemetry-and-new-relic)을 참조하십시오. - - Screenshot showing an error in distributed tracing - -3. 트레이스가 열려 있으면 `Show in-process spans`을 클릭한 후, 표시되는 스팬을 클릭하면 오른쪽에 세부 정보 패널이 열립니다. 사용자 입력이 유효하지 않을 때 기록된 예외를 보려면 `View span events`를 클릭합니다. - - Screenshot of in-process spans - -수동 계측 튜토리얼을 완료한 경우 스팬으로 기록된 예외가 뉴렐릭에 다음과 같이 표시됩니다. - -Screenshot showing an exception as a span event - -스팬 속성, 스팬 이름, 상태 코드 등 설정한 추가 세부 정보를 보려면 **Attributes** 탭을 클릭합니다. 이 창에서는 이 가이드에서 사용한 계측 라이브러리에서 자동으로 수집된 추가 메타데이터와 뉴렐릭에 의해 첨부된 메타데이터를 볼 수도 있습니다. - -Screenshot of the attributes tab - -데이터 보기에 대한 자세한 내용은 [뉴렐릭 UI의 OpenTelemetry](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page)를 참조하십시오. - -### 메트릭 [#metrics] - -뉴렐릭의 `getting-started-java` 엔터티에 도달하면 런타임 메트릭(JVM) 및 커스텀 카운터 속성 같이 수집된 모든 메트릭 목록을 볼 수 있습니다. - -#### 메트릭 탐색기 [#metrics-explorer] - -설정된 메트릭 목록을 볼 수 있게 해주는 도구입니다. - -1. 왼쪽 창에서 **Data > Metrics explorer**를 선택한 다음, `fibonacci.invocations`를 선택합니다. - - Screenshot showing metrics explorer - -2. **Dimensions** 아래에서 커스텀 메트릭과 함께 수집한 속성을 확인한 다음 **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)에 대한 문서를 참조하십시오. - -#### JVM [#jvms] - -JVM 페이지로 이동하여 처리량, 메모리 사용량, 분당 가비지 수집 시간 등 Java 런타임 메트릭을 시각화해 볼 수도 있습니다. - -Screenshot of the main JVMs page - -단일 인스턴스에 대한 메트릭를 보거나 여러 인스턴스를 선택하여 비교할 수 있습니다. - -Screenshot of how to compare JVM instances - -인스턴스를 선택하고 **Compare**를 클릭하면 다음과 같이 표시됩니다. 각 인스턴스는 쉽게 식별할 수 있도록 색상으로 구분되어 있습니다. - -Screenshot showing the color-coded JVM comparison - -보다 자세한 내용은 [JVM 뷰](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-jvms-page/)에 대한 문서를 참조하십시오. - -### 로그 [#logs] - -로그에 액세스할 수 있는 위치는 다음과 같습니다. - -Screenshot showing the main logs page - -터미널에서도 로그를 확인할 수 있습니다. - -Screenshot showing logs in a terminal - -로그 뷰로 돌아가서 로그를 선택하면, 로그 메시지와 수집된 추가 속성(예: 관련 스팬과 트레이스 ID)은 물론 뉴렐릭이 삽입한 메타데이터가 포함된 창이 열립니다. - -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` - - * 헤더: 데이터가 어느 계정으로 전송될지 결정합니다. `YOUR_LICENSE_KEY` - - - - 로 교체합니다. -
- `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net` (미국의 경우) `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.eu01.nr-data.net` (EU의 경우) - - * 이는 애플리케이션 텔레메트리를 내보낼 엔드포인트입니다. 뉴렐릭의 OTLP 엔드포인트로 데이터를 내보냅니다. -
- `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` - - * 뉴렐릭이 선호하는 OTLP `http/protobuf`를 사용해야 한다는 것을 지정합니다. -
- `OTEL_SERVICE_NAME=getting-started-java` - - * 이는 애플리케이션을 뉴렐릭의 엔터티와 연관시켜 주는 이름입니다. 이 튜토리얼에서는 이를 `getting-started-java`라고 부르지만, 원하는 대로 이름을 지정할 수 있습니다. -
- `OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_OWN_ID_HERE` - - * `INSERT_YOUR_OWN_ID_HERE`를 고유한 인스턴스 ID로 바꿉니다. 예를 들어, `1234`를 사용할 수 있습니다. 보다 자세한 내용은 OpenTelemetry의 [리소스 의미 체계 규칙](https://github.com/open-telemetry/semantic-conventions/blob/main/docs/resource/README.md#service-experimental)을 참조하십시오. -
- `OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT=4095` - - * 최대 속성 값 길이에 한도를 설정하면 스팬 데이터가 [속성 한도](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/#attribute-limits)를 초과하는 경우 삭제되는 것을 방지할 수 있습니다. -
- `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=DELTA` - - * 뉴렐릭은 누적 기본값 대신 델타 시간성 메트릭을 지원합니다. -
- `OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=BASE2_EXPONENTIAL_BUCKET_HISTOGRAM` - - * (권장) 히스토그램 집계: 더 나은 데이터 압축을 위해 기본 제공되는 명시적 버킷 히스토그램 대신 지수 히스토그램을 사용합니다. -
- `OTEL_LOGS_EXPORTER=otlp` - - * OTLP를 통한 로그 내보내기를 활성화합니다. 로그 내보내기는 기본적으로 비활성화되어 있습니다. -
- `OTEL_EXPORTER_OTLP_COMPRESSION=gzip` - - * (권장) gzip 압축을 설정하면 요청당 전송할 수 있는 데이터 양을 극대화할 수 있습니다. 허용되는 최대 페이로드 크기는 1MB(10^6바이트)입니다. Gzip 압축은 성능이 뛰어나고 데이터 유출이 적습니다. -
- `OTEL_EXPERIMENTAL_EXPORTER_OTLP_RETRY_ENABLED=true` - - * (권장) 인터넷의 불안정성에 대처하는 데 도움이 되도록 실험적인 내보내기 재시도를 활성화합니다. -
- `OTEL_EXPERIMENTAL_RESOURCE_DISABLED_KEYS=process.command_line` - - * (권장) 이렇게 하면 뉴렐릭의 최대 속성 길이 한도를 자주 초과하고 민감한 정보가 포함될 수 있는 `process.command_line` 리소스 속성이 비활성화됩니다. -
-
-
- -위의 축소기에 나열된 환경 변수를 생성한 후 튜토리얼로 돌아가 설정을 완료합니다. - -* [튜토리얼 2 (OpenTelemetry Java 에이전트를 통한 데모 앱 모니터링)](#java-agent) -* [튜토리얼 3(데모 앱 수동 설정)](#auto-config-ext) - -## 다음 단계는? [#what-next] - -이제 OpenTelemetry 계측 및 SDK 구성을 실험해보았으므로 배운 내용을 기반으로 OpenTelemetry 및 뉴렐릭을 사용하여 자체 앱이나 서비스를 설정할 수 있습니다. 보다 자세한 내용은 [OpenTelemetry를 사용한 앱 또는 서비스 설정](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro)을 참조하십시오. \ No newline at end of file diff --git a/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx b/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx deleted file mode 100644 index ad74d8ce017..00000000000 --- a/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx +++ /dev/null @@ -1,907 +0,0 @@ ---- -title: 'OpenTelemetry 자습서: 샘플 Python 앱 계측' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: 'To test out OpenTelemetry on a sample Pythyon app instead of your own app, consider these three 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' - -뉴렐릭 플랫폼이 OTLP 데이터로 무엇을 할 수 있는지 알아보려면 다음 Python 튜토리얼을 시도해 보세요. 선택할 수 있는 세 가지 튜토리얼이 있으며 각 튜토리얼은 동일한 데모 Flask 앱을 사용합니다. 앱은 피보나치 수열의 n번째 숫자를 계산하고 트레이스, 지수 및 로그를 생성합니다. - -이러한 튜토리얼을 통해 OpenTelemetry 및 뉴렐릭을 사용하여 자신만의 앱을 설정하는 데 도움이 되는 기술을 배울 수 있습니다. - -Screenshot showing response time, throughput, and error rate - -
- 이러한 자습서를 마치면 다음과 같은 차트에서 스팬 메트릭을 볼 수 있습니다. -
- -## 요구 사항 [#requirements] - -시작하기 전에 다음이 있는지 확인하십시오. - -* New Relic 계정: 아직 계정이 없다면 [무료 계정](https://newrelic.com/signup) 에 가입하세요. -* Python 3.8 이상 및 pip(Python 버전 3.4 이상에 포함됨): 아직 가지고 있지 않은 경우 다음 [다운로드 옵션을](https://www.python.org/downloads/)참조하십시오. - -## 튜토리얼 [#tutorials] - -각 튜토리얼은 동일한 데모 앱을 사용하지만 OpenTelemetry 및 뉴렐릭에 익숙해지는 데 도움이 되는 다양한 접근 방식을 제공합니다. - -* [사전 계측된 앱](#pre-instrumented-tutorial): UI에서 데이터를 빠르게 확인하려면 사전 계측된 데모 앱을 실행하세요. -* [OpenTelemetry Python 에이전트](#python-agent-tutorial): OpenTelemetry Python 에이전트를 사용하여 데모 앱을 모니터링합니다. -* [수동 설정](#manual-setup-tutorial): 데모 앱을 수동으로 다운로드했습니다. - -완료하려는 튜토리얼에 대해 아래 탭을 클릭하세요. - - - OpenTelemetry를 사용할 때 OTLP를 통해 애플리케이션에서 New Relic으로 데이터를 내보내는 두 가지 선택 사항이 있습니다. - - * 앱에서 New Relic으로 직접 - * 앱이 OpenTelemetry Collector로 데이터를 보낸 다음 New Relic으로 내보냅니다. - - 이 튜토리얼에서는 첫 번째 옵션을 다룹니다. 컬렉터를 통해 데이터를 내보내려면 이 [컬렉터 문서](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/collector-processing/opentelemetry-collector-processing-intro)에서 보다 자세한 내용을 확인하십시오. - - - - - - 사전 계측된 앱 - - - - OpenTelemetry Python 에이전트 - - - - 수동 설정 - - - - - - ### 사전 계측된 데모 앱 실행 [#pre-instrum] - - New Relic에 데이터를 보내고 UI에서 보는 것이 어떤 것인지 빠르게 확인할 수 있도록 계측 작업을 수행하려는 경우에 유용한 옵션입니다. - - 1. 터미널에서 다음을 실행하여 데모 앱을 복제하고 시작 안내서의 `python/Instrumented` 디렉토리로 이동합니다. - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/python/Instrumented - ``` - - 2. New Relic 계정으로 데이터를 보내도록 다음 환경 변수를 설정합니다. - - * 을(를) 사용하세요. - - * New Relic 데이터 센터 지역이 US가 아닌 EU인 경우 끝점을 다음으로 설정합니다. `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](https://otlp.nr-data.net) - - 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 > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services** 으)로 이동합니다. - - 7. `getting-started-python` 라는 새 항목(서비스)을 클릭하고 UI를 탐색합니다. UI에서 무엇을 찾아야 하는지에 대한 추가 팁은 [New Relic에서 데이터 보기](#view-data) 를 참조하십시오. - - 8. UI에서 데이터 확인을 마치면 두 터미널 세션에서 `CONTROL+C` 눌러 애플리케이션을 종료합니다. - - - - ### 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` 눌러 애플리케이션을 종료합니다. - - - - ### 데모 앱을 수동으로 설정 [#manual-instrum] - - 이전 자습서에서는 OpenTelemetry Python 에이전트를 사용하여 자동 측정, 트랜잭션을 탐색하는 데 도움이 되었습니다. 이 튜토리얼에서는 사용자 정의 측정을 사용하여 수집한 텔넷리를 더 효과적으로 제어하는 방법을 보여줍니다. 그런 다음 데이터를 뉴렐릭으로 내보내도록 OpenTelemetry SDK를 구성하는 방법을 살펴보겠습니다. - - - - ### 데모 애플리케이션 다운로드 [#download] - - 데모 앱을 다운로드하려면 다음을 실행하십시오. - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - ``` - - - - ### 필수 라이브러리 설치 [#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 - ``` - - - - ### SDK 구성 [#config-sdk] - - 1. `app.py` 에서 아래 강조표시된 줄을 **top of the file** 에 추가합니다. 필요에 따라 사용자 정의 속성 `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) 으로 이동하여 내보내야 하는 변수를 확인한 후 다음 단계로 이동하여 계측 라이브러리를 추가하십시오. - - - - ### 계측 라이브러리 추가: 추적 [#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.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 - # 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())) - ``` - - - - ### 계측 라이브러리 추가: 측정항목 [#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.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 - 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.") - ``` - - - - ### 계측 라이브러리 추가: 로그 [#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.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' - _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())))) - ``` - - - - ### 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) - ``` - - - - ### 커스텀 추적 계측: 커스텀 범위 만들기 [#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) - ``` - - - - ### 사용자 정의 추적 계측: 예외 기록 [#span-exception] - - 예외가 발생하면 기록할 수 있습니다. 스팬 상태 설정과 함께 이 작업을 수행하는 것이 좋습니다. - - 1. 예외가 발생할 때 스팬의 상태 코드를 `ERROR` 으로 설정하려면 [D](#library-traces) 단계에서 추가한 `opentelemetry.trace.status package` 의 `Status` 및 `StatusCode` 모듈을 사용합니다. - - ```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.http.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) - ``` - - - - ### 사용자 정의 메트릭 계측: 사용자 정의 메트릭 카운터 추가 [#cust-metrics] - - 메트릭은 개별 측정을 집계로 결합하고 시스템 부하의 함수로 일정한 데이터를 생성하기 때문에 정말 유용한 원격 분석 데이터 유형입니다. 이 데이터를 스팬과 함께 사용하여 추세를 파악하고 애플리케이션 런타임 원격 분석을 제공할 수 있습니다. 메트릭이 나타내는 측정의 하위 구분을 설명하는 데 도움이 되는 속성으로 메트릭에 주석을 달 수도 있습니다. - - OpenTelemetry 메트릭 API는 메트릭 SDK에서 집계하고 외부 프로세스로 내보낸 측정값을 기록하는 여러 계측기를 정의합니다. 악기에는 두 가지 유형이 있습니다. - - * 동기식: 이 계측기는 측정이 발생하는 대로 기록합니다. - * 비동기식: 이러한 도구는 컬렉션당 한 번만 호출되고 관련 컨텍스트가 없는 콜백을 등록합니다. - - 1. [E](#library-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.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 - 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) - ``` - - - - ### 사용자 정의 로그 계측 [#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) - ``` - - - - ### 앱을 실행하여 트래픽을 생성하세요. [#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 > All capabilities](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 - -범위 속성, 범위 이름, 상태 코드 등 설정한 추가 세부정보를 보려면 **Attributes** 탭을 클릭하세요. 이 창에서는 측정에 의해 자동으로 수집된 추가 메타데이터, 이 가이드에서 사용한 추가 라이브러리 및 뉴렐릭에 의해 첨부된 메타데이터를 볼 수도 있습니다. - -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. **Dimensions** 아래에서 맞춤 지표와 함께 수집한 속성을 확인한 다음 **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/best-practices/opentelemetry-best-practices-logs) 로그 보기에 대해 자세히 알아보세요. - -## 참조: 환경 변수 [#ref-env-vars] - -튜토리얼 2 또는 3을 수행하는 경우 내보내야 하는 환경 변수 목록입니다. 변수 내보내기를 완료한 후 변수 목록 다음에 오는 링크를 사용하여 자습서로 돌아갑니다. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- OTEL_EXPORTER_OTLP_HEADERS=api-key=YOUR_LICENSE_KEY - - * 헤더: 귀하의 데이터가 어느 계정으로 전송될지 결정합니다. `YOUR_LICENSE_KEY` - - - - 로 바꾸세요. -
- OTEL_EXPORTER_OTLP_ENDPOINT=[https://otlp.nr-data.net](https://otlp.nr-data.net) (미국의 경우) - - * 이는 애플리케이션 원격 분석을 내보낼 엔드포인트입니다. New Relic의 OTLP 엔드포인트로 데이터를 내보냅니다. EU에 거주하는 경우 다음 엔드포인트를 사용하세요. OTEL_EXPORTER_OTLP_ENDPOINT=[https://otlp.eu01.nr-data.net](https://otlp.eu01.nr-data.net) -
- 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 - - * 최대 속성 값 길이에 대한 제한을 설정하면 범위 데이터가 [속성 제한을](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/#attribute-limits) 초과하는 경우 삭제되는 것을 방지할 수 있습니다. -
- OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=델타 - - * New Relic은 누적의 기본값 대신 델타 시간성의 메트릭을 지원합니다. -
- OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=base2_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 및 뉴렐릭을 사용하여 자체 앱이나 서비스를 설정할 수 있습니다. 보다 자세한 내용은 [OpenTelemetry를 사용한 앱 또는 서비스 설정](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro)을 참조하십시오. \ No newline at end of file diff --git a/src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx b/src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx deleted file mode 100644 index a9193c4597c..00000000000 --- a/src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java.mdx +++ /dev/null @@ -1,1200 +0,0 @@ ---- -title: 'Tutoriais OpenTelemetry: instrumento um exemplo de aplicativo Java' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: 'To test out OpenTelemetry on a sample app instead of your own app, consider these three tutorials.' -freshnessValidatedDate: never -translationType: machine ---- - -import opentelemetrySpringBootASCIIDisplay from 'images/opentelemetry_screenshot-crop_Spring-Boot-ASCII-display.webp' - -import opentelemetryMainDistributedTracingPage from 'images/opentelemetry_screenshot-crop_main-distributed-tracing-page.webp' - -import opentelemetryDistributedTracingError from 'images/opentelemetry_screenshot-crop_distributed-tracing-error.webp' - -import opentelemetryInProcessSpans from 'images/opentelemetry_screenshot-crop_in-process-spans.webp' - -import opentelemetryExceptiononSpanEvent from 'images/opentelemetry_screenshot-crop_exception-on-span-event.webp' - -import opentelemetryAttributesTab from 'images/opentelemetry_screenshot-crop_attributes-tab.webp' - -import opentelemetryMetricsExplorerMain from 'images/opentelemetry_screenshot-crop_metrics-explorer-main.webp' - -import opentelemetryMetricsExplorerDimensions from 'images/opentelemetry_screenshot-crop_metrics-explorer-dimensions.webp' - -import opentelemetryJvmsPageMain from 'images/opentelemetry_screenshot-crop_jvms-page-main.webp' - -import opentelemetryCompareJvmInstances from 'images/opentelemetry_screenshot-full_compare-jvm-instances.webp' - -import opentelemetryJvmColorCodedComparison from 'images/opentelemetry_screenshot-full_jvm-color-coded-comparison.webp' - -import opentelemetryMainLogsPage from 'images/opentelemetry_screenshot-full_main-logs-page.webp' - -import opentelemetryLogsinTerminal from 'images/opentelemetry_screenshot-full_logs-in-terminal.webp' - -import opentelemetryLogDetailsWithTrace from 'images/opentelemetry_screenshot-full_log-details-with-trace.webp' - -import opentelemetryTraceRelatedtoLog from 'images/opentelemetry_screenshot-full_trace-related-to-log.webp' - -import opentelemetryTraceWaterfallFromLog from 'images/opentelemetry_screenshot-full_trace-waterfall-from-log.webp' - -import opentelemetryLogCapturedinTraceSpan from 'images/opentelemetry_screenshot-full_log-captured-in-trace-span.webp' - -import opentelemetryTraceDurationDemoChart from 'images/opentelemetry_screenshot-crop_jvm-metric-charts.webp' - -Experimente estes tutoriais Java para ver o que a plataforma New Relic pode fazer com seus dados OTLP. Temos três tutoriais para você escolher, cada um usando o mesmo aplicativo Spring de demonstração. O aplicativo irá calcular o enésimo número na sequência de Fibonacci e gerar rastreamento, métrica e log. - -Ao trabalhar com esses tutoriais, você pode aprender habilidades para ajudá-lo a configurar seu próprio aplicativo com OpenTelemetry e New Relic. - -Screenshot showing various JVM metric charts - -
- Depois de concluir qualquer um desses tutoriais, você poderá visualizar as métricas da JVM em gráficos como estes. -
- -## Requisitos [#requirements] - -Para começar, certifique-se de ter o seguinte: - -* Uma conta New Relic: Cadastre-se para obter uma [conta gratuita](https://newrelic.com/signup) se ainda não tiver uma. -* Java 17 ou superior: se você ainda não o possui, consulte [estas opções de download](https://www.java.com/en/download/manual.jsp). - -## Tutoriais [#tutorials] - -Embora cada tutorial use o mesmo aplicativo de demonstração, eles têm abordagens diferentes para ajudá-lo a se familiarizar com o OpenTelemetry e o New Relic. - -* [Aplicativo de pré-instrumento](#pre-instrumented-tutorial): Execute nosso aplicativo de demonstração de pré-instrumento para ver rapidamente os dados em nossa interface. -* [OpenTelemetry agente Java](#java-agent-tutorial): monitor nosso aplicativo de demonstração com o agente OpenTelemetry Java. -* [Configuração manual](#manual-setup-tutorial): instrumento nosso aplicativo de demonstração manualmente. - -Clique na guia abaixo do tutorial que deseja concluir. - - - Ao usar o OpenTelemetry, você terá duas opções para exportar dados do seu aplicativo para o New Relic via OTLP: - - * Diretamente do seu aplicativo para o New Relic - * Seu aplicativo envia dados para um coletor OpenTelemetry, onde são exportados para o New Relic - - Esses tutoriais cobrem a primeira opção. Se você deseja exportar seus dados por meio de um coletor, consulte a [documentação do coletor](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/collector-processing/opentelemetry-collector-processing-intro) para obter detalhes. - - - - - - Aplicativo pré-instrumento - - - - Agente OpenTelemetry Java - - - - Configuração manual - - - - - - ### Execute o aplicativo de demonstração pré-instrumento [#pre-instrum] - - Esta é uma ótima opção se você deseja que façamos a instrumentação para que possa ver rapidamente como é enviar dados para o New Relic e visualizá-los em nossa interface. - - 1. Em seu terminal, execute o seguinte para clonar o aplicativo de demonstração e navegue até o diretório `java` dos Guias de primeiros passos. - - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/java - ``` - - 2. Defina estas duas variáveis de ambiente para enviar dados para sua conta New Relic: - - * Certifique-se de usar seu . - - * Se a região do seu data center New Relic for a UE e não os EUA, defina o endpoint como: `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_PROTOCOL=http/protobuf` - - 3. Defina a primeira variável de ambiente abaixo para nomear o serviço, depois defina a segunda para o ID da instância do serviço, que ativa determinado recurso da plataforma. Por fim, habilite os logs, já que o log está desativado por padrão: - - * `OTEL_SERVICE_NAME=getting-started-java` - - * `OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_ID_HERE` - - * Substitua `INSERT_YOUR_OWN_ID_HERE` por um ID de instância exclusivo. Por exemplo, você poderia usar 1234. - - * `OTEL_LOGS_EXPORTER=otlp` - - 4. No mesmo diretório `getting-started-guides/java` , crie e execute o aplicativo: - - * Mac OS: - - ```bash - ./gradlew bootRun - ``` - - * PowerShell: - - ```bash - .\gradlew.bat build - ``` - - 5. Abra uma nova guia do terminal, alterne para o diretório `getting-started-guides/java/Instrumented` e execute o seguinte comando para gerar tráfego para o aplicativo: - - * Mac OS: - - ```bash - ./load-generator.sh - ``` - - * PowerShell: - - ```bash - .\load-generator.ps1 - ``` - - - Alternativamente, você pode acessar o endpoint no browser neste URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Substitua `INSERT_A_VALUE` por um valor de 1 a 90. Para gerar um erro, insira um número inteiro fora do intervalo válido. - - - 6. Vá para **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services**. - - 7. Clique na sua nova entidade (serviço) chamada `getting-started-java` e explore a interface. Para obter mais dicas sobre o que procurar na interface, consulte [Visualizar seus dados no New Relic](#view-data). - - 8. Quando terminar de visualizar seus dados na interface, encerre o aplicativo pressionando CONTROL+C em ambas as sessões do terminal. - - - - ### Monitor o aplicativo de demonstração com o agente OpenTelemetry Java [#java-agent] - - Aqui está um tutorial diferente que também usa o mesmo aplicativo de demonstração. Nesse caso, você usará o agente OpenTelemetry Java para monitor automaticamente o aplicativo de demonstração. Você não precisa modificar o código-fonte Java. Ao usar o agente, você pode começar rapidamente a exportar dados de amostra para o New Relic. - - O agente de instrumentação automática é um arquivo JAR que injeta bytecode dinamicamente para capturar telemetria de bibliotecas e estruturas populares. Você também pode usá-lo para capturar dados como solicitações de entrada, chamadas HTTP de saída e chamadas de banco de dados. Ele pode ser anexado a qualquer aplicativo Java 8+. - - - Consulte a [documentação oficial do agente Java](https://opentelemetry.io/docs/instrumentation/java/automatic/) para opções de configuração adicionais. - - - Para monitor nosso aplicativo de demonstração com o agente OpenTelemetry Java: - - 1. Faça download do [arquivo JAR do agente](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/latest/download/opentelemetry-javaagent.jar), que contém a biblioteca de agente e instrumentação. Coloque-o no diretório de sua preferência e anote o caminho que você usará posteriormente. - - 2. Caso ainda não tenha feito isso, baixe o repositório do aplicativo de demonstração e mude para o seguinte diretório: - - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/java - ``` - - 3. Crie o aplicativo de demonstração com este comando: - - * Mac OS: - - ```bash - ./gradlew build - ``` - - * PowerShell: - - ```bash - .\gradlew.bat build - ``` - - - Após uma compilação bem-sucedida, você encontrará o arquivo JAR do aplicativo resultante em `Uninstrumented/build/libs`, chamado `uninstrumented.jar`. - - - 4. Vá para nossa [seção de referência de variáveis de ambiente](#ref-env-vars) abaixo para ver quais variáveis você precisa exportar e depois retorne a estas etapas. - - 5. Continue em `getting-started-guides/java/Uninstrumented` para lançar o agente com o aplicativo: - - - Substitua `path/to` pelo local do arquivo JAR que você baixou anteriormente. - - - ```bash - java -javaagent:path/to/opentelemetry-javaagent.jar \ - -jar ./build/libs/uninstrumented.jar - ``` - - 6. Gere tráfego para o aplicativo abrindo um novo terminal no diretório `getting-started-guides/java/Uninstrumented` e executando o gerador de carga: - - * Mac OS: - - ```bash - ./load-generator.sh - ``` - - * PowerShell: - - ```bash - .\load-generator.ps1 - ``` - - - Alternativamente, você pode acessar o endpoint no browser neste URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Substitua `INSERT_A_VALUE` por um valor de 1 a 90. Para gerar um erro, insira um número inteiro fora do intervalo válido. - - - 7. Agora que você enviou alguns dados para o New Relic, veja nossas [instruções sobre como visualizar os dados na interface](#view-data). - - 8. Quando terminar de visualizar seus dados na interface, encerre o aplicativo pressionando CONTROL+C em ambas as sessões do terminal. - - - - ### Configure o aplicativo de demonstração manualmente [#manual-instrum] - - O tutorial anterior ajudou você a explorar a instrumentação automática com o agente OpenTelemetry Java. Este tutorial mostrará como usar instrumentação personalizada para ter mais controle sobre a telemetria coletada. Você inserirá manualmente a instrumentação em nosso aplicativo de demonstração para capturar telemetria e, em seguida, configurará o SDK para exportar esses dados para o New Relic. - - - Embora você possa configurar manualmente o SDK, mostraremos como configurá-lo usando a [opção autoconfigure](https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/autoconfigure), que simplifica o processo usando variáveis de ambiente e propriedades do sistema. - - - - - #### Baixe o aplicativo de demonstração [#download] - - Se você ainda não baixou nosso aplicativo de demonstração, execute o seguinte: - - ```bash - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - ``` - - - - #### Instalar dependência [#dependencies] - - Para adicionar dependência: - - 1. Vá para o diretório do aplicativo. - - ```bash - cd newrelic-opentelemetry-examples/getting-started-guides/java/uninstrumented - ``` - - 2. Abra `build.gradle`. - - 3. Adicione os seguintes itens destacados ao bloco `dependencies` (talvez seja necessário rolar para baixo dentro do bloco de código): - - ```gradle lineHighlight=29-42 - plugins { - id 'org.springframework.boot' version '2.7.5' - id 'io.spring.dependency-management' version '1.1.0' - id 'java' - } - - java { - toolchain { - languageVersion = JavaLanguageVersion.of(17) - } - } - - repositories { - mavenCentral() - } - - bootRun { - mainClass.set 'com.example.demo.Application' - } - - configurations.all { - exclude module: 'spring-boot-starter-logging' - } - - dependencies { - implementation 'org.springframework.boot:spring-boot-starter-web' - implementation 'org.springframework.boot:spring-boot-starter-log4j2' - - // OpenTelemetry core - implementation platform('io.opentelemetry:opentelemetry-bom:1.22.0') - implementation platform('io.opentelemetry:opentelemetry-bom-alpha:1.22.0-alpha') - implementation 'io.opentelemetry:opentelemetry-api' - implementation 'io.opentelemetry:opentelemetry-sdk' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp-logs' - implementation 'io.opentelemetry:opentelemetry-sdk-extension-autoconfigure' - - // OpenTelemetry instrumentation - implementation platform('io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom-alpha:1.22.1-alpha') - implementation 'io.opentelemetry.instrumentation:opentelemetry-runtime-metrics' - implementation 'io.opentelemetry.instrumentation:opentelemetry-log4j-appender-2.17' - implementation 'io.opentelemetry.instrumentation:opentelemetry-spring-webmvc-6.0' - } - ``` - - Notas: - - * A dependência `bom` (lista de materiais) é usada para sincronizar versões de dependência para um ecossistema específico. Como o OpenTelemetry publica muitos componentes Java, eles ajudam a garantir que todas as versões sejam sincronizadas, quer você use apenas algumas ou muitas delas. - * As dependências restantes fornecem acesso ao SDK, API, exportador OTLP e biblioteca de instrumentação. - * Há uma configuração adicional para excluir o módulo spring-boot-starter-logging. Isso evita uma mensagem de erro de compilação relacionada a `log4j-slf4j-impl cannot be present with log4j-to-slf4j`. - - - - #### Configure o SDK com a extensão autoconfigure [#auto-config-ext] - - Embora você possa configurar o SDK manualmente, recomendamos usar a extensão autoconfigure, pois ela agiliza o processo. - - 1. Vá para o diretório do código-fonte do aplicativo: - - ```bash - cd newrelic-opentelemetry-examples/getting-started-guides/java/uninstrumented/src/main/java/com/example/demo - ``` - - 2. Abra `Application.java`. - - 3. Insira as linhas destacadas: - - ```java lineHighlight=7-12,17-20 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - } - ``` - - 4. Vá para nossa [seção de referência de variáveis de ambiente](#ref-env-vars) abaixo para ver quais variáveis você precisa exportar e depois retorne a estas etapas. - - - - #### Adicionar biblioteca de instrumentação: trace [#library-traces] - - Em `Application.java`, adicione a instrumentação destacada para Spring Web MVC registrando um filtro de rastreamento: - - ```java lineHighlight=22-26 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - - - - #### Adicionar biblioteca de instrumentação: métrica [#library-metrics] - - Gere e colete métricas sobre seu tempo de execução Java registrando o seguinte no arquivo `Application.java` . Insira as linhas destacadas abaixo: - - ```java lineHighlight=14-20 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - // Register runtime metrics instrumentation - BufferPools.registerObservers(openTelemetrySdk); - Classes.registerObservers(openTelemetrySdk); - Cpu.registerObservers(openTelemetrySdk); - GarbageCollector.registerObservers(openTelemetrySdk); - MemoryPools.registerObservers(openTelemetrySdk); - Threads.registerObservers(openTelemetrySdk); - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - - - - #### Adicionar biblioteca de instrumentação: log [#library-logs] - - Este aplicativo de demonstração está configurado para usar o `OpenTelemetryAppender` (via `log4j.xml`), que usa `GlobalLoggerProvider`. A configuração de `GlobalLoggerProvider` conecta o `OpenTelemetryAppender` ao SDK log que é configurado usando autoconfigure aqui: - - 1. Abra `Application.java`. - - 2. Insira as seguintes linhas destacadas. - - ```java lineHighlight=14-15 - @SpringBootApplication - public class Application { - - private static volatile OpenTelemetry openTelemetry = OpenTelemetry.noop(); - - public static void main(String[] args) { - // Build the SDK auto-configuration extension module - OpenTelemetrySdk openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - Application.openTelemetry = openTelemetrySdk; - - // Set GlobalLoggerProvider, which is used by Log4j2 appender - GlobalLoggerProvider.set(openTelemetrySdk.getSdkLoggerProvider()); - - // Register runtime metrics instrumentation - BufferPools.registerObservers(openTelemetrySdk); - Classes.registerObservers(openTelemetrySdk); - Cpu.registerObservers(openTelemetrySdk); - GarbageCollector.registerObservers(openTelemetrySdk); - MemoryPools.registerObservers(openTelemetrySdk); - Threads.registerObservers(openTelemetrySdk); - - SpringApplication.run(Application.class, args); - } - - @Bean - public OpenTelemetry openTelemetry() { - return openTelemetry; - } - - // Add Spring WebMVC instrumentation by registering a tracing filter - @Bean - public Filter webMvcTracingFilter(OpenTelemetry openTelemetry) { - return SpringWebMvcTelemetry.create(openTelemetry).createServletFilter(); - } - } - ``` - - 3. Crie um diretório chamado `resources` em `Uninstrumented/src/main`. - - 4. Neste novo diretório, crie um arquivo chamado `log4j2.xml` com o seguinte conteúdo: - - ```xml - - - - - - - - - - - - - - - - ``` - - - A seção `packages=...` desta linha permite que o Log4J encontre e configure o `OpenTelemetryAppender`. O código-fonte está [no repositório OpenTelemetry](https://github.com/open-telemetry/opentelemetry-java-instrumentation/tree/main/instrumentation/log4j/log4j-appender-2.17/library) e foi adicionado como uma dependência via `io.opentelemetry.instrumentation:opentelemetry-log4j-appender-2.17`) - - - - - #### Instrumentação trace customizada: Criar constantes de atributo de span [#custom-attribs] - - Cada trace é composto por spans, que representam uma unidade lógica de trabalho ou uma operação dentro de uma solicitação específica. O código abaixo demonstra: - - * Constantes estáticas para armazenar chaves de atributo que podem ser usadas para fornecer insights em nível de solicitação em seus períodos - * Como inicializar um [Tracer](https://opentelemetry.io/docs/concepts/signals/traces/#tracer), que cria spans - - Insira as seguintes linhas destacadas em `Controller.java`: - - ```java lineHighlight=4-14 - @RestController - public class Controller { - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - - private final Tracer tracer; - - @Autowired - Controller(OpenTelemetry openTelemetry) { - // Initialize tracer - tracer = openTelemetry.getTracer(Controller.class.getName()); - } - - @GetMapping(value = "/fibonacci") - . . . - } - ``` - - - - #### Instrumentação trace customizada: Crie um intervalo customizado [#cust-span] - - Você pode criar os spans que desejar e cabe a você anotar seus spans com atributos em operações específicas. O atributo definido fornecerá contexto adicional sobre a operação específica que você está acompanhando, como resultados ou propriedades da operação. - - 1. Em `Controller.java`, insira essas linhas destacadas para iniciar um novo intervalo chamado `fibonacci` que faz o seguinte: - - * Captura dados sobre a execução deste método - * Define um atributo que armazena o valor de n da solicitação do usuário - - ```java lineHighlight=2-3 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - . . . - } - ``` - - 2. Adicione detalhes granulares ao seu código adicionando um atributo ao seu intervalo para armazenar informações sobre solicitações bem-sucedidas: - - ```java lineHighlight=20-21 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - try { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, last); - return last; - } catch (IllegalArgumentException e) { - throw e; - } - } - ``` - - - - #### Instrumentação trace customizada: Registrar uma exceção [#span-exception] - - Você pode querer registrar as exceções à medida que elas acontecem. Recomendamos que você faça isso em conjunto com a configuração do status do intervalo. Primeiro, defina seu intervalo como o intervalo atual, defina o código de status como erro no caso de uma exceção e, em seguida, encerre o intervalo: - - ```java lineHighlight=5-6,26-27,29-32 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - Este método gera um `IllegalArgumentException` se um usuário fornecer uma entrada inválida. Quando isso acontece, a exceção é registrada como um evento no intervalo e o status do intervalo será definido como `ERROR`. A mensagem de exceção é capturada como a descrição do status. A exceção será registrada como um evento no intervalo onde ocorre. - - Por fim, em `handleException()` na classe `ErrorHandler` , defina o status do intervalo como `ERROR` com estas linhas destacadas: - - ```java lineHighlight=10-11 - @ControllerAdvice - private static class ErrorHandler { - - @ExceptionHandler({ - IllegalArgumentException.class, - MissingServletRequestParameterException.class, - HttpRequestMethodNotSupportedException.class - }) - public ResponseEntity handleException(Exception e) { - // Set the span status and description - Span.current().setStatus(StatusCode.ERROR, e.getMessage()); - return new ResponseEntity<>(Map.of("message", e.getMessage()), HttpStatus.BAD_REQUEST); - } - } - ``` - - Como na etapa anterior, isso define o código de status do intervalo se o usuário inserir um número inválido. No entanto, como isso acontece no manipulador de exceções, e não em `fibonacci()`, o intervalo atual é o intervalo pai da solicitação. Esse span pai vem da instrumentação Spring Web MVC adicionada por meio do filtro na classe aplicativo. Agora, quando o endpoint do seu aplicativo gerar uma exceção, tanto o span pai quanto o span filho terão um status de span de `ERROR`. - - - - #### Instrumentação métrica personalizada: Adicionar um contador de métrica personalizado [#metrics-cust] - - Métricas são um tipo de dados de telemetria realmente úteis porque combinam medições individuais em agregações e produzem dados constantes em função da carga do sistema. Você pode usar esses dados em conjunto com períodos para ajudar a identificar tendências e fornecer telemetria de tempo de execução do aplicativo. Você também pode anotar qualquer métrica com um atributo para ajudar a descrever qual subdivisão das medidas a métrica representa. - - A API OpenTelemetry métrica define uma série de instrumentos, que registram medidas que são agregadas pelo SDK métrica e exportadas fora do processo. Existem dois tipos de instrumento: - - * Síncrono: Este instrumento registra as medições à medida que ocorrem - * Assíncrono: Este instrumento registra um retorno de chamada, que é invocado apenas uma vez por coleta e não possui contexto associado - - - Se você tiver alguma dúvida sobre o status da métrica no projeto OpenTelemetry, consulte os [status do sinal](https://opentelemetry.io/docs/instrumentation/java/#status-and-releases). - - - Conclua o seguinte para adicionar um contador personalizado: - - 1. Instancie um atributo booleano para sua métrica personalizada e inicialize um instrumento métrico. Nesse caso, estamos usando um [LongCounter](https://opentelemetry.io/docs/instrumentation/java/manual/#metrics), que registra apenas valores positivos e é útil para contar coisas, como o número de bytes enviados por uma rede. Por padrão, as medidas do contador são agregadas em somas monotônicas (sempre crescentes). - - ```java lineHighlight=7,10,16-21 - @RestController - public class Controller { - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - private static final AttributeKey ATTR_VALID_N = AttributeKey.booleanKey("fibonacci.valid.n"); - - private final Tracer tracer; - private final LongCounter fibonacciInvocations; - - @Autowired - Controller(OpenTelemetry openTelemetry) { - // Initialize tracer - tracer = openTelemetry.getTracer(Controller.class.getName()); - // Initialize instrument - Meter meter = openTelemetry.getMeter(Controller.class.getName()); - fibonacciInvocations = meter - .counterBuilder("fibonacci.invocations") - .setDescription("Measures the number of times the fibonacci method is invoked.") - .build(); - } - . . . - } - ``` - - 2. Insira as seguintes linhas destacadas para que seu contador personalizado possa capturar entradas válidas e inválidas, bem como o número de vezes que cada uma ocorre. - - ```java lineHighlight=24-25,30-31 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - // Counter to increment the number of times a valid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, true)); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - // Counter to increment the number of times an invalid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, false)); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - - - #### Instrumentação de log customizada [#cust-log] - - O status do sinal de log no OpenTelemetry Java é atualmente [experimental](https://opentelemetry.io/docs/instrumentation/java/#status-and-releases). mensagem do log são gerenciados pelo manipulador raiz em seu aplicativo, que enviará log de nível `INFO` e superior para o console por padrão. No entanto, você pode modificar o comportamento do agente alterando o nível de log, inclusive para classes específicas, ou instalando um manipulador ou filtro customizado. - - ##### Inicialize o agente [#initialize-logger] - - Conforme afirmado anteriormente, isso é da biblioteca `java.util.logging` . O agente não é um componente do OpenTelemetry, mas o aplicativo foi configurado para enviar o Log4j para o SDK log do OpenTelemetry: - - ```java lineHighlight=4-5 - @RestController - public class Controller { - - // Logger (note that this is not an OTel component) - private static final Logger LOGGER = LogManager.getLogger(Controller.class); - - // Attribute constants - private static final AttributeKey ATTR_N = AttributeKey.longKey("fibonacci.n"); - private static final AttributeKey ATTR_RESULT = AttributeKey.longKey("fibonacci.result"); - private static final AttributeKey ATTR_VALID_N = AttributeKey.booleanKey("fibonacci.valid.n"); - . . . - } - ``` - - ##### Adicionar mensagem personalizada do log [#cust-log-messages] - - Depois de inicializar o agente, você poderá usá-lo para registrar: - - * O resultado de uma entrada válida, juntamente com o valor desse resultado - * Quando nenhuma saída foi gravada - - Insira as seguintes linhas destacadas: - - ```java lineHighlight=26-27,34-35 - private long fibonacci(long n) { - // Start a new span and set your first attribute - var span = tracer.spanBuilder("fibonacci").setAttribute(ATTR_N, n).startSpan(); - - // Set the span as the current span - try (var scope = span.makeCurrent()) { - if (n < 1 || n > 90) { - throw new IllegalArgumentException("n must be 1 <= n <= 90."); - } - - long result = 1; - if (n > 2) { - long a = 0; - long b = 1; - - for (long i = 1; i < n; i++) { - result = a + b; - a = b; - b = result; - } - } - // Set a span attribute to capture information about successful requests - span.setAttribute(ATTR_RESULT, result); - // Counter to increment the number of times a valid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, true)); - // Log the result of a valid input - LOGGER.info("Compute fibonacci(" + n + ") = " + result); - return result; - } catch (IllegalArgumentException e) { - // Record the exception and set the span status - span.recordException(e).setStatus(StatusCode.ERROR, e.getMessage()); - // Counter to increment the number of times an invalid input is recorded - fibonacciInvocations.add(1, Attributes.of(ATTR_VALID_N, false)); - // Log when no output was recorded - LOGGER.info("Failed to compute fibonacci(" + n + ")"); - throw e; - } finally { - // End the span - span.end(); - } - } - ``` - - - - #### Exercite o aplicativo para gerar algum tráfego [#exercise-app] - - Você está pronto para enviar alguns dados para a New Relic! - - 1. Vá para o diretório `getting-started-guides/java` e crie e execute o aplicativo com este comando: - - * Mac OS: - - ```bash - ./gradlew bootRun - ``` - - * PowerShell: - - ```bash - .\gradlew.bat build - ``` - - - Se o seu terminal exibir o Spring ASCII, significa que seu aplicativo foi compilado com sucesso e está em execução: - - Screenshot showing Spring Boot ASCII logo - - - 2. Gere tráfego do aplicativo abrindo um novo terminal no diretório `getting-started-guides/java/Uninstrumented` e executando o gerador de carga: - - * Mac OS: - - ```bash - ./load-generator.sh - ``` - - * PowerShell: - - ```bash - .\load-generator.ps1 - ``` - - - Alternativamente, você pode acessar o endpoint no browser neste URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Substitua `INSERT_A_VALUE` por um valor de 1 a 90. Para gerar um erro, insira um número inteiro fora do intervalo válido. - - - 3. Agora que você enviou alguns dados para o New Relic, veja nossas [instruções sobre como visualizar os dados na interface](#view-data). - - - - - - -## Veja seus dados de demonstração no New Relic [#view-data] - -Não importa qual tutorial você concluiu, você pode seguir as dicas abaixo para encontrar seus dados na interface do New Relic. - -1. Vá para - - **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services** - - . - -2. Clique na sua nova entidade (serviço) chamada `getting-started-java` (ou qualquer nome que você forneceu). - -3. Confira os detalhes nas seções de cada tipo de dados. - - - Se você estiver usando o Windows e não vir os dados em sua conta New Relic, verifique se permitiu o tráfego através do firewall. - - -### Traces [#traces] - -Depois de chegar à entidade `getting-started-java` no New Relic: - -1. Na seção - - **Monitor** - - do painel esquerdo, clique em - - **Distributed tracing** - - e depois clique no grupo trace - - **Fibonacci** - - . - - Screenshot showing the main distributed tracing page - -2. A partir daí, encontre um trace com erro e clique para abri-lo. - - Com o agente Java OpenTelemetry , você poderá ver resultados diferentes dos que veria com o agente Java New Relic APM . Isso ocorre porque há uma diferença no tratamento de erros entre os dois tipos de agentes. Para obter mais informações, consulte [Tratamento de taxa de erros no OpenTelemetry e New Relic](https://newrelic.com/blog/how-to-relic/error-rate-opentelemetry-and-new-relic). - - Screenshot showing an error in distributed tracing - -3. Depois de abrir o trace , clique em `Show in-process spans` e, em seguida, clique no intervalo resultante, que abrirá um painel de detalhes à direita. Para ver a exceção que você registrou quando uma entrada do usuário é inválida, clique em `View span events`: - - Screenshot of in-process spans - -Se você concluiu o tutorial de instrumentação manual, veja como será a aparência da exceção registrada como um intervalo no New Relic: - -Screenshot showing an exception as a span event - -Para visualizar detalhes adicionais definidos, como o atributo do intervalo, o nome do intervalo e o código de status, clique na guia **Attributes** . Este painel também é onde você pode visualizar metadados adicionais que são coletados automaticamente pela biblioteca de instrumentação usada neste guia, bem como metadados anexados pela New Relic: - -Screenshot of the attributes tab - -Para obter mais detalhes sobre como visualizar seus dados, consulte [OpenTelemetry na interface do New Relic](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page) - -### Métrica [#metrics] - -Depois de chegar à entidade `getting-started-java` no New Relic, você poderá ver uma lista de todas as métricas coletadas, como métricas de tempo de execução (JVMs) e seu atributo de contador personalizado. - -#### Explorador de métricas [#metrics-explorer] - -Esta é uma ferramenta que permite ver uma lista das suas métricas. - -1. No painel esquerdo, selecione **Data > Metrics explorer** e selecione `fibonacci.invocations`. - - Screenshot showing metrics explorer - -2. Em **Dimensions**, visualize o atributo que você coletou junto com sua métrica personalizada e clique em **fibonacci.valid.n**. - - Screenshot showing the total number of invocations of fibonacci function - -Saiba mais em nossa documentação sobre a [visualização do explorador métrico](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-metrics-explorer-page). - -#### JVMs [#jvms] - -Você também pode visualizar visualizações de suas métricas de tempo de execução Java, incluindo taxas de transferência, uso de memória e tempo de coleta de lixo por minuto, acessando a página da JVM: - -Screenshot of the main JVMs page - -Você pode visualizar a métrica para uma única instância ou selecionar múltiplas instâncias para compará-las: - -Screenshot of how to compare JVM instances - -Aqui está o que você verá após selecionar suas instâncias e clicar em **Compare**, onde cada instância é codificada por cores para facilitar a identificação: - -Screenshot showing the color-coded JVM comparison - -Para saber mais, consulte nossa documentação sobre a [visualização de JVMs](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-jvms-page/). - -### Registro [#logs] - -Aqui é onde acessar seu log: - -Screenshot showing the main logs page - -Você também verá o login em seu terminal: - -Screenshot showing logs in a terminal - -De volta à sua visualização de logs, selecione um log e você verá um painel aberto com a mensagem do log e atributos adicionais que foram coletados, como os span e trace ids associados, bem como os metadados injetados pelo New Relic: - -Screenshot showing log details with trace - -Você pode navegar até o distributed trace correlacionado clicando neste pequeno ícone azul: - -Screenshot showing how to find correlated trace - -Isso abrirá um painel que exibe o trace correlacionado, onde você poderá visualizar mais detalhes sobre o trace. Para obter mais informações sobre esta página, consulte [OpenTelemetry na interface: página distributed tracing ](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page/)e [Compreenda e use a interface distributed tracing ](/docs/distributed-tracing/ui-data/understand-use-distributed-tracing-ui/): - -Screenshot showing the trace waterfall from the logs section - -Você também pode localizar o log correlacionado na visualização de rastreio distribuído. Ao selecionar um trace que possui um log correspondente, você o verá indicado como uma guia e poderá visualizar o log diretamente do trace sem precisar alternar as visualizações: - -Screenshot showing how to see log details from a trace span - -Saiba mais sobre a visualização de log [aqui](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-logs). - -## Referência: Variáveis de ambiente [#ref-env-vars] - -Esta é uma lista de variáveis de ambiente que você deve exportar se estiver fazendo o tutorial 2 ou 3. Após terminar de exportar as variáveis, retorne aos tutoriais usando os links que seguem a lista de variáveis: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- `OTEL_EXPORTER_OTLP_HEADERS=api-key=YOUR_LICENSE_KEY` - - * Cabeçalhos: determina para qual conta New Relic seus dados serão enviados. Substitua `YOUR_LICENSE_KEY` pelo seu - - - - . -
- `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net` (Para os EUA) `OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.eu01.nr-data.net` (Para a UE) - - * Este é o endpoint para o qual a telemetria do seu aplicativo será exportada. Exporte dados para o endpoint OTLP da New Relic. -
- `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` - - * Especifica que OTLP `http/protobuf` deve ser usado, o que é preferido pela New Relic. -
- `OTEL_SERVICE_NAME=getting-started-java` - - * Este é o nome que associa a telemetria do seu aplicativo a uma entidade no New Relic. Neste tutorial vamos chamá-lo de `getting-started-java`, mas você pode chamá-lo do que quiser. -
- `OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_OWN_ID_HERE` - - * Substitua `INSERT_YOUR_OWN_ID_HERE` por um ID de instância exclusivo. Por exemplo, você poderia usar `1234`. Para obter mais detalhes, consulte [Convenções semânticas de recursos](https://github.com/open-telemetry/semantic-conventions/blob/main/docs/resource/README.md#service-experimental) do OpenTelemetry. -
- `OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT=4095` - - * Definir um limite para o comprimento máximo do valor do atributo impedirá que os dados do intervalo sejam descartados se excederem o [limite do atributo](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/#attribute-limits). -
- `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=DELTA` - - * A New Relic suporta métrica na temporalidade delta em vez do padrão cumulativo. -
- `OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=BASE2_EXPONENTIAL_BUCKET_HISTOGRAM` - - * Agregação de histograma (recomendada): use o histograma exponencial em vez do histograma de intervalo explícito padrão para melhor compactação de dados. -
- `OTEL_LOGS_EXPORTER=otlp` - - * Habilite a exportação de log por OTLP. A exportação de log está desabilitada por padrão. -
- `OTEL_EXPORTER_OTLP_COMPRESSION=gzip` - - * (Recomendado) Definir a compactação gzip permite maximizar a quantidade de dados que você pode enviar por solicitação. Nosso tamanho máximo de carga útil permitido é 1 MB (10 ^ 6 bytes). A compactação Gzip tem bom desempenho e reduz a saída de dados. -
- `OTEL_EXPERIMENTAL_EXPORTER_OTLP_RETRY_ENABLED=true` - - * (Recomendado) Ative a nova tentativa de exportação experimental para ajudar a lidar com a falta de confiabilidade da Internet. -
- `OTEL_EXPERIMENTAL_RESOURCE_DISABLED_KEYS=process.command_line` - - * (Recomendado) Isso desativa o atributo de recurso `process.command_line` , que geralmente excede o limite máximo de comprimento do atributo New Relic e pode conter informações confidenciais. -
-
-
- -Depois de criar as variáveis de ambiente listadas no recolhido acima, retorne ao tutorial e conclua a configuração: - -* [Tutorial 2 (monitor o aplicativo de demonstração com o agente OpenTelemetry Java)](#java-agent) -* [Tutorial 3 (Configurar o aplicativo de demonstração manualmente)](#auto-config-ext) - -## Qual é o próximo? [#what-next] - -Agora que você experimentou a instrumentação do OpenTelemetry e a configuração do SDK, você pode aplicar o que aprendeu para configurar seu próprio aplicativo ou serviço com o OpenTelemetry e o New Relic. Para saber mais, consulte [Configurar seu próprio aplicativo ou serviço com OpenTelemetry](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro). \ No newline at end of file diff --git a/src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx b/src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx deleted file mode 100644 index 58495a0d172..00000000000 --- a/src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python.mdx +++ /dev/null @@ -1,909 +0,0 @@ ---- -title: 'Tutoriais OpenTelemetry: instrumento um exemplo de aplicativo Python' -tags: - - Integrations - - Open source telemetry integrations - - OpenTelemetry -metaDescription: 'To test out OpenTelemetry on a sample Pythyon app instead of your own app, consider these three 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' - -Experimente qualquer um desses tutoriais Python para ver o que a plataforma New Relic pode fazer com seus dados OTLP. Temos três tutoriais para você escolher, cada um usando o mesmo aplicativo de demonstração Flask. O aplicativo calcula o enésimo número na sequência de Fibonacci e gera rastreamento, métrica e log. - -Ao trabalhar em qualquer um desses tutoriais, você pode aprender habilidades para ajudá-lo a configurar seu próprio aplicativo com OpenTelemetry e New Relic. - -Screenshot showing response time, throughput, and error rate - -
- Depois de concluir qualquer um desses tutoriais, você poderá visualizar a métrica de amplitude em gráficos como estes. -
- -## Requisitos [#requirements] - -Antes de começar, certifique-se de ter o seguinte: - -* Uma conta New Relic: Cadastre-se para obter uma [conta gratuita](https://newrelic.com/signup) se ainda não tiver uma. -* Python 3.8 ou superior e pip (incluído no Python versão 3.4 e posterior): se você ainda não os possui, consulte estas [opções de download](https://www.python.org/downloads/). - -## Tutoriais [#tutorials] - -Embora cada tutorial use o mesmo aplicativo de demonstração, eles têm abordagens diferentes para ajudá-lo a se familiarizar com o OpenTelemetry e o New Relic. - -* [Aplicativo de pré-instrumento](#pre-instrumented-tutorial): Execute nosso aplicativo de demonstração de pré-instrumento para ver rapidamente os dados em nossa interface. -* [Agente OpenTelemetry Python](#python-agent-tutorial): monitor nosso aplicativo de demonstração com o agente OpenTelemetry Python. -* [Configuração manual](#manual-setup-tutorial): instrumento nosso aplicativo de demonstração manualmente. - -Clique na guia abaixo do tutorial que deseja concluir. - - - Ao usar o OpenTelemetry, você terá duas opções para exportar dados do seu aplicativo para o New Relic via OTLP: - - * Diretamente do seu aplicativo para o New Relic - * Seu aplicativo envia dados para um coletor OpenTelemetry, onde são exportados para o New Relic - - Esses tutoriais cobrem a primeira opção. Se você deseja exportar seus dados por meio de um coletor, consulte a [documentação do coletor](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/collector-processing/opentelemetry-collector-processing-intro) para obter detalhes. - - - - - - Aplicativo pré-instrumento - - - - Agente OpenTelemetry Python - - - - Configuração manual - - - - - - ### Execute o aplicativo de demonstração pré-instrumento [#pre-instrum] - - Esta é uma ótima opção se você deseja que façamos a instrumentação para que você possa ver rapidamente como é enviar dados para o New Relic e visualizá-los em nossa interface. - - 1. Em seu terminal, execute o seguinte para clonar o aplicativo de demonstração e navegue até o diretório `python/Instrumented` dos Guias de primeiros passos. - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/python/Instrumented - ``` - - 2. Defina estas variáveis de ambiente para enviar dados para sua conta New Relic: - - * Certifique-se de usar seu . - - * Se a região do seu data center New Relic for a UE e não os EUA, defina o endpoint como: `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](https://otlp.nr-data.net) - - 3. Defina esta variável de ambiente para nomear o serviço; é assim que você identificará seu serviço em sua conta New Relic: - - * OTEL_SERVICE_NAME=getting-started-python - - 4. No mesmo diretório `getting-started-guides/python/Instrumented/` , crie e ative um ambiente virtual, instale a biblioteca necessária e execute o aplicativo: - - * Mac OS: - - ``` - 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 - ``` - - 5. Abra uma nova guia do terminal, alterne para o diretório `getting-started-guides/python/Instrumented` e execute o seguinte comando para gerar tráfego para o aplicativo: - - * Mac OS: - - ``` - ./load-generator.sh - ``` - - * PowerShell: - - ``` - .\load-generator.ps1 - ``` - - - Alternativamente, você pode acessar o endpoint no browser neste URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Substitua `INSERT_A_VALUE` por um valor de 1 a 90. Para gerar um erro, insira um número inteiro fora do intervalo válido. - - - 6. Vá para **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services**. - - 7. Clique na sua nova entidade (serviço) chamada `getting-started-python` e explore a interface. Para obter mais dicas sobre o que procurar na interface, consulte [Visualizar seus dados no New Relic](#view-data). - - 8. Quando terminar de visualizar seus dados na interface, encerre o aplicativo pressionando `CONTROL+C` em ambas as sessões do terminal. - - - - ### Monitor o aplicativo de demonstração com o agente OpenTelemetry Python [#python-agent] - - Aqui está um tutorial diferente que também usa o mesmo aplicativo de demonstração, mas neste caso, você usará o agente OpenTelemetry Python para monitor automaticamente o aplicativo de demonstração. Você não precisa modificar o código-fonte do Python. Ao usar o agente, você pode começar rapidamente a exportar dados de amostra para o New Relic. - - Observe, entretanto, que você precisará adicionar instrumentação personalizada para capturar níveis mais profundos de informações sobre o aplicativo, como log e métrica personalizada. - - O agente de instrumentação automática é um pacote PyPI em série que injeta bytecode dinamicamente para capturar telemetria de bibliotecas e estruturas populares. Você também pode usá-lo para capturar dados como solicitações de entrada, chamadas HTTP de saída e chamadas de banco de dados. Ele pode ser anexado a qualquer aplicativo Python 3. - - - Consulte a [documentação oficial do agente OpenTelemetry Python](https://opentelemetry.io/docs/instrumentation/python/automatic/) para opções de configuração adicionais. - - - Para monitor nosso aplicativo de demonstração com o agente OpenTelemetry Python: - - 1. Execute estes dois comandos para baixar o repositório do aplicativo de demonstração e mudar para o seguinte diretório: - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` - - 2. Vá para nossa [seção de referência de variáveis de ambiente](#ref-env-vars) abaixo para ver quais variáveis você precisa exportar e depois retorne a estas etapas. - - 3. Em seguida, no mesmo diretório `getting-started-guides/python/Uninstrumented/` , crie e ative um ambiente virtual: - - * Mac OS: - - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * PowerShell: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` - - 4. Agora você está pronto para instalar a biblioteca necessária: - - ``` - pip install flask - pip install opentelemetry-instrumentation-flask - pip install opentelemetry-exporter-otlp - pip install opentelemetry-distro - ``` - - 5. Continue em `getting-started-guides/python/Uninstrumented/` para lançar o agente com o aplicativo: - - * Mac OS: - - ``` - opentelemetry-instrument python3 app.py - ``` - - * PowerShell: - - ``` - opentelemetry-instrument python app.py - ``` - - 6. Gere tráfego para o aplicativo abrindo um novo terminal no diretório `getting-started-guides/python/Uninstrumented` e executando o gerador de carga: - - * Mac OS: - - ``` - ./load-generator.sh - ``` - - * PowerShell: - - ``` - .\load-generator.ps1 - ``` - - - Alternativamente, você pode acessar o endpoint no browser neste URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Substitua `INSERT_A_VALUE` por um valor de 1 a 90. Para gerar um erro, insira um número inteiro fora do intervalo válido. - - - 7. Agora que você enviou alguns dados para o New Relic, veja nossas [instruções sobre como visualizar os dados na interface](#view-data). - - 8. Quando terminar de visualizar seus dados na interface, encerre o aplicativo pressionando `CONTROL+C` em ambas as sessões do terminal. - - - - ### Configure o aplicativo de demonstração manualmente [#manual-instrum] - - O tutorial anterior ajudou você a explorar a instrumentação automática com o agente OpenTelemetry Python. Este tutorial mostrará como usar instrumentação personalizada para ter mais controle sobre a telemetria coletada. A seguir, você verá como configurar o OpenTelemetry SDK para exportar os dados para o New Relic. - - - - ### Baixe o aplicativo de demonstração [#download] - - Execute o seguinte para baixar nosso aplicativo de demonstração: - - ``` - git clone https://github.com/newrelic/newrelic-opentelemetry-examples.git - ``` - - - - ### Instale a biblioteca necessária [#libraries] - - Para adicionar a biblioteca necessária: - - 1. Acesse o diretório do aplicativo não instrumentado como ponto de partida para este tutorial. Ao final deste tutorial, o código deverá ser semelhante ao do diretório `Instrumented` . - - ``` - cd newrelic-opentelemetry-examples/getting-started-guides/python/Uninstrumented - ``` - - 2. Crie e ative um ambiente virtual no diretório `Uninstrumented` : - - * Mac OS: - - ``` - python3 -m venv venv - source venv/bin/activate - ``` - - * PowerShell: - - ``` - python -m venv venv - .\venv\Scripts\Activate.ps1 - ``` - - 3. Instale o seguinte: - - ``` - 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 - ``` - - - - ### Configurar o SDK [#config-sdk] - - 1. Em `app.py`, adicione as linhas destacadas abaixo ao **top of the file**. Altere o valor do atributo personalizado `environment` conforme necessário. - - ```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. Vá para nossa [seção de referência de variáveis de ambiente](#ref-env-vars) abaixo para ver quais variáveis você precisa exportar e, em seguida, avance para a próxima etapa para adicionar a biblioteca de instrumentação. - - - - ### Adicionar biblioteca de instrumentação: trace [#library-traces] - - Em `app.py`, insira o seguinte após o `OpenTelemetry Settings` que você adicionou: - - ```python - ########## - # Traces # - ########## - from opentelemetry import trace - from opentelemetry.sdk.trace import TracerProvider - from opentelemetry.sdk.trace.export import BatchSpanProcessor - 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 - # 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())) - ``` - - - - ### Adicionar biblioteca de instrumentação: métrica [#library-metrics] - - Em `app.py` adicione o seguinte após a seção `Traces` adicionada na Etapa 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.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 - 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.") - ``` - - - - ### Adicionar biblioteca de instrumentação: log [#library-logs] - - Em `app.py`, adicione o seguinte após a seção `Metrics` . Isso importará o módulo de registro e definirá o nível de registro `basicConfig` como `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.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' - _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())))) - ``` - - - - ### Adicionar instrumentação Flask [#flask-instrum] - - Em `app.py` adicione as linhas destacadas abaixo, após a seção `Logs` . Isso ajuda a vincular períodos para distributed tracing e contexto de login: - - ```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) - ``` - - - - ### Instrumentação trace customizada: Crie um intervalo customizado [#cust-span] - - Você pode criar os spans que desejar e cabe a você anotar seus spans com atributos em operações específicas. O atributo definido fornecerá contexto adicional sobre a operação específica que você está acompanhando, como resultados ou propriedades da operação. - - Em `app.py`, insira as linhas destacadas abaixo para iniciar um novo intervalo chamado `/fibonacci` que faz o seguinte: - - * Captura dados sobre a execução deste método - - * Define um atributo que armazena o valor de n da solicitação do usuário - - ```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) - ``` - - - - ### Instrumentação trace customizada: Registrar uma exceção [#span-exception] - - Você pode querer registrar as exceções à medida que elas acontecem. Recomendamos que você faça isso em conjunto com a configuração do status do intervalo. - - 1. Para definir o código de status do intervalo como `ERROR` quando ocorrer uma exceção, você usará os módulos `Status` e `StatusCode` do `opentelemetry.trace.status package` adicionado na etapa [D](#library-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.http.trace_exporter import OTLPSpanExporter - from opentelemetry.trace.status import Status, StatusCode - ``` - - 2. Em seguida, insira as linhas destacadas abaixo para registrar a exceção, que aparecerá como um evento span no New Relic, e defina o status do span como `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) - ``` - - - - ### Instrumentação métrica personalizada: Adicionar um contador de métrica personalizado [#cust-metrics] - - Métricas são um tipo de dados de telemetria realmente úteis porque combinam medições individuais em agregações e produzem dados constantes em função da carga do sistema. Você pode usar esses dados em conjunto com períodos para ajudar a identificar tendências e fornecer telemetria de tempo de execução do aplicativo. Você também pode anotar qualquer métrica com um atributo para ajudar a descrever qual subdivisão das medidas a métrica representa. - - A API OpenTelemetry métrica define uma série de instrumentos, que registram medidas que são agregadas pelo SDK métrica e exportadas fora do processo. Existem dois tipos de instrumento: - - * Síncrono: Este instrumento registra as medições à medida que ocorrem - * Assíncrono: Este instrumento registra um retorno de chamada, que é invocado apenas uma vez por coleta e não possui contexto associado - - 1. Na etapa [E](#library-metrics), você adicionou a linha destacada abaixo, que criará um contador: - - ```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.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 - 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. A seguir, adicione as linhas destacadas abaixo para usar o contador que você acabou de criar para medir: - - * O número de vezes que esta função é executada com sucesso - * O número de vezes que ele falha ao executar - - Observe que o contador será zerado sempre que você reiniciar o aplicativo. - - ```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) - ``` - - - - ### Instrumentação de log customizada [#cust-log] - - O status do sinal de log no OpenTelemetry Python é atualmente [experimental](https://github.com/open-telemetry/opentelemetry-python#project-status). - - Em `app.py`, adicione as linhas destacadas abaixo para: - - * Registre um log de nível `INFO` para os valores de entrada e saída - * Registre um log de nível `ERROR` quando o valor de entrada estiver fora do intervalo válido - - ```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) - ``` - - - - ### Exercite o aplicativo para gerar algum tráfego [#exercise-app] - - Você está pronto para enviar alguns dados para a New Relic! - - 1. No terminal, confirme que você está no diretório `getting-started-guides/python/Uninstrumented` e execute o aplicativo: - - * Mac OS: - - ``` - python3 app.py - ``` - - * PowerShell: - - ``` - python app.py - ``` - - 2. Gere tráfego para o aplicativo abrindo uma nova guia de terminal no diretório `getting-started-guides/python/Uninstrumented` e executando o gerador de carga: - - * Mac OS: - - ``` - ./load-generator.sh - ``` - - * PowerShell: - - ``` - .\load-generator.ps1 - ``` - - - Alternativamente, você pode acessar o endpoint no browser neste URL: `http://localhost:8080/fibonacci?n=INSERT_A_VALUE`. Substitua `INSERT_A_VALUE` por um valor de 1 a 90. Para gerar um erro, insira um número inteiro fora do intervalo válido. - - - 3. Agora que você enviou alguns dados para o New Relic, veja nossas [instruções sobre como visualizar os dados na interface](#view-data). - - - - - - -## Veja seus dados de demonstração no New Relic [#view-data] - -Não importa qual tutorial você concluiu, você pode seguir as dicas abaixo para encontrar seus dados na interface do New Relic. - -Observe que se você seguiu [o Tutorial 2: monitor o aplicativo demo com o agente OpenTelemetry Python:](#python-agent), você não verá os dados personalizados (como a métrica personalizada e o log), pois precisará adicionar manualmente a instrumentação personalizada para capturar dados mais granulares. - -1. Vá para - - **[one.newrelic.com > All capabilities](https://one.newrelic.com/all-capabilities) > APM & services** - - . - -2. Clique na sua nova entidade (serviço) chamada `getting-started-python` (ou qualquer nome que você forneceu). - -3. Confira os detalhes nas seções de cada tipo de dados. - - - Se você estiver usando o Microsoft Windows e não vir os dados em sua conta New Relic, verifique se você permitiu o tráfego através do firewall. - - -### Traces [#traces] - -Depois de chegar à entidade `getting-started-python` no New Relic: - -1. Na seção - - **Monitor** - - do painel esquerdo, clique em - - **Distributed tracing** - - e depois clique no grupo trace `/fibonacci`. - - Screenshot showing how to find your trace group - -2. A partir daí, encontre um trace com erro e clique para abri-lo: - - Screenshot showing an error in distributed tracing - -3. Depois de abrir o trace , clique em `Show in-process spans` e, em seguida, clique no intervalo resultante, que abrirá um painel de detalhes à direita. Para ver a exceção que você registrou quando uma entrada do usuário é inválida, clique em `View span events`: - - Screenshot of in-process spans - -Se você concluiu o tutorial de instrumentação manual, veja como será a aparência da exceção registrada como um intervalo no New Relic: - -Screenshot showing an exception as a span event - -Para visualizar detalhes adicionais definidos, como o atributo do intervalo, o nome do intervalo e o código de status, clique na guia **Attributes** . Este painel também é onde você pode visualizar metadados adicionais que são coletados automaticamente pela biblioteca de instrumentação usada neste guia, bem como metadados anexados pela New Relic: - -Screenshot of the attributes tab - -Para obter mais detalhes sobre como visualizar seus dados, consulte [OpenTelemetry na interface do New Relic](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page) - -### Métrica [#metrics] - -Depois de chegar à entidade `getting-started-python` no New Relic, você poderá ver uma lista de todas as métricas coletadas, como seu atributo de contador personalizado. - -#### Explorador de métricas [#metrics-explorer] - -Esta é uma ferramenta que permite ver uma lista das suas métricas. - -1. No painel esquerdo, selecione **Data > Metrics explorer** e selecione `fibonacci.invocations`. - - Screenshot showing metrics explorer - -2. Em **Dimensions**, visualize o atributo que você coletou junto com sua métrica personalizada e clique em **fibonacci.valid.n**. - - Screenshot showing the total number of invocations of fibonacci function - -Saiba mais em nossa documentação sobre a [visualização do explorador métrico](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-metrics-explorer-page). - -### Registro [#logs] - -Aqui é onde acessar seu log: - -Screenshot showing the main logs page - -Você também verá o login em seu terminal: - -Screenshot showing logs in a terminal - -De volta à sua visualização de logs, selecione um log e você verá um painel aberto com a mensagem do log e atributos adicionais que foram coletados, como os span e trace ids associados, bem como os metadados injetados pelo New Relic: - -Screenshot showing log details with trace - -Você pode navegar até o distributed trace correlacionado clicando neste pequeno ícone azul: - -Screenshot showing how to find correlated trace - -Isso abrirá um painel que exibe o trace correlacionado, onde você poderá visualizar mais detalhes sobre o trace. Para obter mais informações sobre esta página, consulte [OpenTelemetry na interface: página distributed tracing ](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-distributed-tracing-page/)e [Compreenda e use a interface distributed tracing ](/docs/distributed-tracing/ui-data/understand-use-distributed-tracing-ui/): - -Screenshot showing the trace waterfall from the logs section - -Você também pode localizar o log correlacionado na visualização de rastreio distribuído. Ao selecionar um trace que possui um log correspondente, você o verá indicado como uma guia e poderá visualizar o log diretamente do trace sem precisar alternar as visualizações: - -Screenshot showing how to see log details from a trace span - -Saiba mais sobre a visualização de log [aqui](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-logs). - -## Referência: Variáveis de ambiente [#ref-env-vars] - -Esta é uma lista de variáveis de ambiente que você deve exportar se estiver fazendo o tutorial 2 ou 3. Após terminar de exportar as variáveis, retorne aos tutoriais usando os links que seguem a lista de variáveis: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- OTEL_EXPORTER_OTLP_HEADERS=api-key=YOUR_LICENSE_KEY - - * Cabeçalhos: determina para qual conta New Relic seus dados serão enviados. Substitua `YOUR_LICENSE_KEY` pelo seu - - - - . -
- OTEL_EXPORTER_OTLP_ENDPOINT=[https://otlp.nr-data.net](https://otlp.nr-data.net) (Para os EUA) - - * Este é o endpoint para o qual a telemetria do seu aplicativo será exportada. Exporte dados para o endpoint OTLP da New Relic. Se você estiver na UE, use este endpoint: OTEL_EXPORTER_OTLP_ENDPOINT=[https://otlp.eu01.nr-data.net](https://otlp.eu01.nr-data.net) -
- OTEL_SERVICE_NAME=getting-started-python - - * Este é o nome que associa a telemetria do seu aplicativo a uma entidade no New Relic. Neste tutorial vamos chamá-lo de `getting-started-python`, mas você pode chamá-lo do que quiser. -
- OTEL_RESOURCE_ATTRIBUTES=service.instance.id=INSERT_YOUR_OWN_ID_HERE - - * Substitua `INSERT_YOUR_OWN_ID_HERE` por um ID de instância exclusivo. Por exemplo, você poderia usar `1234`. Para obter mais detalhes, consulte [Convenções semânticas de recursos](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service) do OpenTelemetry. -
- OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT=4095 - - * Definir um limite para o comprimento máximo do valor do atributo impedirá que os dados do intervalo sejam descartados se excederem o [limite do atributo](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp/#attribute-limits). -
- OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=Delta - - * A New Relic suporta métrica na temporalidade delta em vez do padrão cumulativo. -
- OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=base2_exponential_bucket_histogram - - * Agregação de histograma (recomendada): use o histograma exponencial em vez do histograma de intervalo explícito padrão para melhor compactação de dados. -
- OTEL_LOGS_EXPORTER=otlp - - * Habilite a exportação de log por OTLP. A exportação de log está desabilitada por padrão. -
- OTEL_EXPORTER_OTLP_COMPRESSION=gzip - - * (Recomendado) Definir a compactação gzip permite maximizar a quantidade de dados que você pode enviar por solicitação. Nosso tamanho máximo de carga útil permitido é 1 MB (10 ^ 6 bytes). A compactação Gzip tem bom desempenho e reduz a saída de dados. -
- OTEL_EXPERIMENTAL_EXPORTER_OTLP_RETRY_ENABLED=true - - * (Recomendado) Ative a nova tentativa de exportação experimental para ajudar a lidar com a falta de confiabilidade da Internet. -
- OTEL_EXPERIMENTAL_RESOURCE_DISABLED_KEYS=process.command_line - - * (Recomendado) Isso desativa o atributo de recurso `process.command_line` , que geralmente excede o limite máximo de comprimento do atributo New Relic e pode conter informações confidenciais. -
-
-
- -Depois de exportar as variáveis de ambiente listadas no recolhido acima, retorne ao tutorial e conclua a configuração: - -* [Tutorial 2: monitor o aplicativo de demonstração com o agente OpenTelemetry Python](#python-agent) -* [Tutorial 3: Configure o aplicativo de demonstração manualmente](#manual-instrum) - -## Qual é o próximo? [#what-next] - -Agora que você experimentou a instrumentação do OpenTelemetry e a configuração do SDK, você pode aplicar o que aprendeu para configurar seu próprio aplicativo ou serviço com o OpenTelemetry e o New Relic. Para saber mais, consulte [Configurar seu próprio aplicativo ou serviço com OpenTelemetry](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro). \ No newline at end of file From d7e6fd288d5877074baf63ac35bdcfd5ec4b6628 Mon Sep 17 00:00:00 2001 From: Alan West <3676547+alanwest@users.noreply.github.com> Date: Mon, 3 Jun 2024 14:58:14 -0700 Subject: [PATCH 04/11] Move OpenTelemetry APM UI page --- .../apm-monitoring}/opentelemetry-apm-ui.mdx | 0 .../apm-monitoring}/opentelemetry-apm-ui.mdx | 0 .../apm-monitoring}/opentelemetry-apm-ui.mdx | 0 .../apm-monitoring}/opentelemetry-apm-ui.mdx | 0 .../apm-monitoring}/opentelemetry-apm-ui.mdx | 0 src/nav/opentelemetry.yml | 4 ++-- 6 files changed, 2 insertions(+), 2 deletions(-) rename src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/{best-practices => get-started/apm-monitoring}/opentelemetry-apm-ui.mdx (100%) rename src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/{best-practices => get-started/apm-monitoring}/opentelemetry-apm-ui.mdx (100%) rename src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/{best-practices => get-started/apm-monitoring}/opentelemetry-apm-ui.mdx (100%) rename src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/{best-practices => get-started/apm-monitoring}/opentelemetry-apm-ui.mdx (100%) rename src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/{best-practices => get-started/apm-monitoring}/opentelemetry-apm-ui.mdx (100%) diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-apm-ui.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx similarity index 100% rename from src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-apm-ui.mdx rename to src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx diff --git a/src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-apm-ui.mdx b/src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx similarity index 100% rename from src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-apm-ui.mdx rename to src/i18n/content/es/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx diff --git a/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-apm-ui.mdx b/src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx similarity index 100% rename from src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-apm-ui.mdx rename to src/i18n/content/jp/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx diff --git a/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-apm-ui.mdx b/src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx similarity index 100% rename from src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-apm-ui.mdx rename to src/i18n/content/kr/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx diff --git a/src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-apm-ui.mdx b/src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx similarity index 100% rename from src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-apm-ui.mdx rename to src/i18n/content/pt/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx diff --git a/src/nav/opentelemetry.yml b/src/nav/opentelemetry.yml index 79d23633ba9..b23ca2465a0 100644 --- a/src/nav/opentelemetry.yml +++ b/src/nav/opentelemetry.yml @@ -17,6 +17,8 @@ pages: pages: - title: Overview path: /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro + - title: OpenTelemetry APM UI + path: /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui - title: Collector for infrastructure monitoring pages: - title: Overview @@ -63,8 +65,6 @@ pages: path: /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-resources - title: Traces path: /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-traces - - title: OpenTelemetry APM UI - path: /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-apm-ui - title: Create custom queries path: /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-data-explorer-query-builder - title: Alerts From a96f6843843a7f5732159b489a50e45406ef2f44 Mon Sep 17 00:00:00 2001 From: Alan West <3676547+alanwest@users.noreply.github.com> Date: Mon, 3 Jun 2024 15:22:20 -0700 Subject: [PATCH 05/11] Add some links --- .../apm-monitoring/opentelemetry-apm-intro.mdx | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx index 4a7e8c0ec91..ed290db0403 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx @@ -47,7 +47,8 @@ languages. For each language, the application is built using web framework popul to that language. The examples demonstrate how to configure: 1. The service name which will display in New Relic. -2. The OpenTelemetry Protocol (OTLP) exporter to send data to New Relic. +2. The OpenTelemetry Protocol (OTLP) exporter to send data to the + [New Relic OTLP endpoint](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp). 3. Additional recommended settings to optimize OpenTelemetry for the best New Relic experience. @@ -101,7 +102,12 @@ scenarios, please see the relevant With your app instrumented and configured to export data to New Relic, you should be able to find your data in the New Relic UI: -- Find your entity at **All entities -> Services - OpenTelemetry**. The entity name is set to the value of the app's `service.name` resource attribute. +- Find your entity at **All entities -> Services - OpenTelemetry**. The entity + name is set to the value of the app's `service.name` resource attribute. + Refer to this + [documentation](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-resources/#services) + for more information on how New Relic service entities are derived from + OpenTelemetry resource attributes. - Use [NRQL](/docs/nrql/get-started/introduction-nrql-new-relics-query-language/) to query directly for [traces](https://one.newrelic.com/launcher/nr1-core.explorer?overlay=eyJuZXJkbGV0SWQiOiJkYXRhLWV4cGxvcmF0aW9uLnF1ZXJ5LWJ1aWxkZXIiLCJpbml0aWFsQWN0aXZlSW50ZXJmYWNlIjoibnJxbEVkaXRvciIsImluaXRpYWxOcnFsVmFsdWUiOiIiLCJpbml0aWFsUXVlcmllcyI6W3sibnJxbCI6IkZST00gU3BhbiBTRUxFQ1QgY291bnQoKikgd2hlcmUgbmV3cmVsaWMuc291cmNlPSclb3RscCUnIFRJTUVTRVJJRVMifV0sImluaXRpYWxDaGFydFNldHRpbmdzIjp7ImNoYXJ0VHlwZSI6IkNIQVJUX0xJTkUiLCJsaW1pdCI6NzU0MiwibGlua2VkRW50aXR5R3VpZCI6bnVsbCwibGlua2VkRGFzaGJvYXJkSWQiOm51bGwsInlTY2FsZSI6eyJzdGF0aWMiOmZhbHNlLCJkb21haW4iOltudWxsLG51bGxdfSwieVplcm8iOnRydWV9fQo=), [metrics](https://one.newrelic.com/launcher/nr1-core.explorer?overlay=eyJuZXJkbGV0SWQiOiJkYXRhLWV4cGxvcmF0aW9uLnF1ZXJ5LWJ1aWxkZXIiLCJpbml0aWFsQWN0aXZlSW50ZXJmYWNlIjoibnJxbEVkaXRvciIsImluaXRpYWxOcnFsVmFsdWUiOiIiLCJpbml0aWFsUXVlcmllcyI6W3sibnJxbCI6IkZST00gTWV0cmljIFNFTEVDVCBjb3VudCgqKSB3aGVyZSBuZXdyZWxpYy5zb3VyY2UgTElLRSAnJW90bHAlJyBUSU1FU0VSSUVTIn1dLCJpbml0aWFsQ2hhcnRTZXR0aW5ncyI6eyJjaGFydFR5cGUiOiJDSEFSVF9MSU5FIiwibGltaXQiOjc1NDIsImxpbmtlZEVudGl0eUd1aWQiOm51bGwsImxpbmtlZERhc2hib2FyZElkIjpudWxsLCJ5U2NhbGUiOnsic3RhdGljIjpmYWxzZSwiZG9tYWluIjpbbnVsbCxudWxsXX0sInlaZXJvIjp0cnVlfX0K), and [logs](https://one.newrelic.com/launcher/nr1-core.explorer?overlay=eyJuZXJkbGV0SWQiOiJkYXRhLWV4cGxvcmF0aW9uLnF1ZXJ5LWJ1aWxkZXIiLCJpbml0aWFsQWN0aXZlSW50ZXJmYWNlIjoibnJxbEVkaXRvciIsImluaXRpYWxOcnFsVmFsdWUiOiIiLCJpbml0aWFsUXVlcmllcyI6W3sibnJxbCI6IkZST00gTG9nIFNFTEVDVCBjb3VudCgqKSB3aGVyZSBuZXdyZWxpYy5zb3VyY2U9JyVvdGxwJScgVElNRVNFUklFUyJ9XSwiaW5pdGlhbENoYXJ0U2V0dGluZ3MiOnsiY2hhcnRUeXBlIjoiQ0hBUlRfTElORSIsImxpbWl0Ijo3NTQyLCJsaW5rZWRFbnRpdHlHdWlkIjpudWxsLCJsaW5rZWREYXNoYm9hcmRJZCI6bnVsbCwieVNjYWxlIjp7InN0YXRpYyI6ZmFsc2UsImRvbWFpbiI6W251bGwsbnVsbF19LCJ5WmVybyI6dHJ1ZX19Cg==). - See [Overview of OpenTelemetry data in the UI](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-view-your-data) for more information. From f2a93c81e3b533b2f9045470da149dcfa1f62629 Mon Sep 17 00:00:00 2001 From: Alan West <3676547+alanwest@users.noreply.github.com> Date: Mon, 3 Jun 2024 15:32:13 -0700 Subject: [PATCH 06/11] Link to APM UI --- .../get-started/apm-monitoring/opentelemetry-apm-intro.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx index ed290db0403..68c931bb22d 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx @@ -109,7 +109,7 @@ With your app instrumented and configured to export data to New Relic, you shoul for more information on how New Relic service entities are derived from OpenTelemetry resource attributes. - Use [NRQL](/docs/nrql/get-started/introduction-nrql-new-relics-query-language/) to query directly for [traces](https://one.newrelic.com/launcher/nr1-core.explorer?overlay=eyJuZXJkbGV0SWQiOiJkYXRhLWV4cGxvcmF0aW9uLnF1ZXJ5LWJ1aWxkZXIiLCJpbml0aWFsQWN0aXZlSW50ZXJmYWNlIjoibnJxbEVkaXRvciIsImluaXRpYWxOcnFsVmFsdWUiOiIiLCJpbml0aWFsUXVlcmllcyI6W3sibnJxbCI6IkZST00gU3BhbiBTRUxFQ1QgY291bnQoKikgd2hlcmUgbmV3cmVsaWMuc291cmNlPSclb3RscCUnIFRJTUVTRVJJRVMifV0sImluaXRpYWxDaGFydFNldHRpbmdzIjp7ImNoYXJ0VHlwZSI6IkNIQVJUX0xJTkUiLCJsaW1pdCI6NzU0MiwibGlua2VkRW50aXR5R3VpZCI6bnVsbCwibGlua2VkRGFzaGJvYXJkSWQiOm51bGwsInlTY2FsZSI6eyJzdGF0aWMiOmZhbHNlLCJkb21haW4iOltudWxsLG51bGxdfSwieVplcm8iOnRydWV9fQo=), [metrics](https://one.newrelic.com/launcher/nr1-core.explorer?overlay=eyJuZXJkbGV0SWQiOiJkYXRhLWV4cGxvcmF0aW9uLnF1ZXJ5LWJ1aWxkZXIiLCJpbml0aWFsQWN0aXZlSW50ZXJmYWNlIjoibnJxbEVkaXRvciIsImluaXRpYWxOcnFsVmFsdWUiOiIiLCJpbml0aWFsUXVlcmllcyI6W3sibnJxbCI6IkZST00gTWV0cmljIFNFTEVDVCBjb3VudCgqKSB3aGVyZSBuZXdyZWxpYy5zb3VyY2UgTElLRSAnJW90bHAlJyBUSU1FU0VSSUVTIn1dLCJpbml0aWFsQ2hhcnRTZXR0aW5ncyI6eyJjaGFydFR5cGUiOiJDSEFSVF9MSU5FIiwibGltaXQiOjc1NDIsImxpbmtlZEVudGl0eUd1aWQiOm51bGwsImxpbmtlZERhc2hib2FyZElkIjpudWxsLCJ5U2NhbGUiOnsic3RhdGljIjpmYWxzZSwiZG9tYWluIjpbbnVsbCxudWxsXX0sInlaZXJvIjp0cnVlfX0K), and [logs](https://one.newrelic.com/launcher/nr1-core.explorer?overlay=eyJuZXJkbGV0SWQiOiJkYXRhLWV4cGxvcmF0aW9uLnF1ZXJ5LWJ1aWxkZXIiLCJpbml0aWFsQWN0aXZlSW50ZXJmYWNlIjoibnJxbEVkaXRvciIsImluaXRpYWxOcnFsVmFsdWUiOiIiLCJpbml0aWFsUXVlcmllcyI6W3sibnJxbCI6IkZST00gTG9nIFNFTEVDVCBjb3VudCgqKSB3aGVyZSBuZXdyZWxpYy5zb3VyY2U9JyVvdGxwJScgVElNRVNFUklFUyJ9XSwiaW5pdGlhbENoYXJ0U2V0dGluZ3MiOnsiY2hhcnRUeXBlIjoiQ0hBUlRfTElORSIsImxpbWl0Ijo3NTQyLCJsaW5rZWRFbnRpdHlHdWlkIjpudWxsLCJsaW5rZWREYXNoYm9hcmRJZCI6bnVsbCwieVNjYWxlIjp7InN0YXRpYyI6ZmFsc2UsImRvbWFpbiI6W251bGwsbnVsbF19LCJ5WmVybyI6dHJ1ZX19Cg==). -- See [Overview of OpenTelemetry data in the UI](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-view-your-data) for more information. +- See [OpenTelemetry APM UI](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui) for more information. If you can't find your entity and don't see your data with NRQL, see [OTLP Troubleshooting](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp-troubleshooting). From db28e498eb3baa1eb6ab18728bf944be83abe346 Mon Sep 17 00:00:00 2001 From: a-sassman Date: Tue, 4 Jun 2024 12:57:33 -0700 Subject: [PATCH 07/11] fix(OTEL): add redirect links for deleted/moved pages --- .../get-started/apm-monitoring/opentelemetry-apm-intro.mdx | 2 ++ .../get-started/apm-monitoring/opentelemetry-apm-ui.mdx | 1 + 2 files changed, 3 insertions(+) diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx index 68c931bb22d..859f7c21b10 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx @@ -10,6 +10,8 @@ metaDescription: Set up OpenTelemetry-based APM monitoring with New Relic. freshnessValidatedDate: 2024-05-14 redirects: - /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/opentelemetry-set-up-your-app/ + - /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-java + - /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-python --- import moreintegrationsNativeOtlpNoCollector from 'images/more-integrations_diagram_native-otlp-no-collector.webp' diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx index efcadda6306..438549407cb 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui.mdx @@ -23,6 +23,7 @@ redirects: - /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-errors-page - /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-errors-inbox-page - /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/view-your-data/opentelemetry-metrics-explorer-page + - /docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-apm-ui/ --- import opentelemetryViewSpanEvents from 'images/opentelemetry_screenshot-crop_view-span-events.webp' From 0ee2e98bb2396129cd3bfc210febbf33144504ec Mon Sep 17 00:00:00 2001 From: a-sassman Date: Tue, 4 Jun 2024 13:08:15 -0700 Subject: [PATCH 08/11] fix(OTEL): minor formatting updates, add doNotTranslate tags to UI elements --- .../opentelemetry-apm-intro.mdx | 25 ++++++++----------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx index 859f7c21b10..a444f272921 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx @@ -46,12 +46,12 @@ for popular libraries and frameworks. To help you get started, we offer a simple example application in a variety of languages. For each language, the application is built using web framework popular -to that language. The examples demonstrate how to configure: +to that language. The examples below demonstrate how to configure: -1. The service name which will display in New Relic. -2. The OpenTelemetry Protocol (OTLP) exporter to send data to the +* The service name which will display in New Relic. +* The OpenTelemetry Protocol (OTLP) exporter to send data to the [New Relic OTLP endpoint](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp). -3. Additional recommended settings to optimize OpenTelemetry for the best New +* Additional recommended settings to optimize OpenTelemetry for the best New Relic experience. @@ -94,7 +94,7 @@ to that language. The examples demonstrate how to configure: For more information about what instrumentation is available and more advanced -scenarios, please see the relevant +scenarios, see the relevant [OpenTelemetry language documentation](https://opentelemetry.io/docs/languages/). @@ -102,18 +102,13 @@ scenarios, please see the relevant ## View your data in the New Relic UI [#view-data] -With your app instrumented and configured to export data to New Relic, you should be able to find your data in the New Relic UI: +Onec your app is instrumented and configured to export data to New Relic, you should be able to find your data in the New Relic UI: -- Find your entity at **All entities -> Services - OpenTelemetry**. The entity - name is set to the value of the app's `service.name` resource attribute. - Refer to this - [documentation](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-resources/#services) - for more information on how New Relic service entities are derived from - OpenTelemetry resource attributes. -- Use [NRQL](/docs/nrql/get-started/introduction-nrql-new-relics-query-language/) to query directly for [traces](https://one.newrelic.com/launcher/nr1-core.explorer?overlay=eyJuZXJkbGV0SWQiOiJkYXRhLWV4cGxvcmF0aW9uLnF1ZXJ5LWJ1aWxkZXIiLCJpbml0aWFsQWN0aXZlSW50ZXJmYWNlIjoibnJxbEVkaXRvciIsImluaXRpYWxOcnFsVmFsdWUiOiIiLCJpbml0aWFsUXVlcmllcyI6W3sibnJxbCI6IkZST00gU3BhbiBTRUxFQ1QgY291bnQoKikgd2hlcmUgbmV3cmVsaWMuc291cmNlPSclb3RscCUnIFRJTUVTRVJJRVMifV0sImluaXRpYWxDaGFydFNldHRpbmdzIjp7ImNoYXJ0VHlwZSI6IkNIQVJUX0xJTkUiLCJsaW1pdCI6NzU0MiwibGlua2VkRW50aXR5R3VpZCI6bnVsbCwibGlua2VkRGFzaGJvYXJkSWQiOm51bGwsInlTY2FsZSI6eyJzdGF0aWMiOmZhbHNlLCJkb21haW4iOltudWxsLG51bGxdfSwieVplcm8iOnRydWV9fQo=), [metrics](https://one.newrelic.com/launcher/nr1-core.explorer?overlay=eyJuZXJkbGV0SWQiOiJkYXRhLWV4cGxvcmF0aW9uLnF1ZXJ5LWJ1aWxkZXIiLCJpbml0aWFsQWN0aXZlSW50ZXJmYWNlIjoibnJxbEVkaXRvciIsImluaXRpYWxOcnFsVmFsdWUiOiIiLCJpbml0aWFsUXVlcmllcyI6W3sibnJxbCI6IkZST00gTWV0cmljIFNFTEVDVCBjb3VudCgqKSB3aGVyZSBuZXdyZWxpYy5zb3VyY2UgTElLRSAnJW90bHAlJyBUSU1FU0VSSUVTIn1dLCJpbml0aWFsQ2hhcnRTZXR0aW5ncyI6eyJjaGFydFR5cGUiOiJDSEFSVF9MSU5FIiwibGltaXQiOjc1NDIsImxpbmtlZEVudGl0eUd1aWQiOm51bGwsImxpbmtlZERhc2hib2FyZElkIjpudWxsLCJ5U2NhbGUiOnsic3RhdGljIjpmYWxzZSwiZG9tYWluIjpbbnVsbCxudWxsXX0sInlaZXJvIjp0cnVlfX0K), and [logs](https://one.newrelic.com/launcher/nr1-core.explorer?overlay=eyJuZXJkbGV0SWQiOiJkYXRhLWV4cGxvcmF0aW9uLnF1ZXJ5LWJ1aWxkZXIiLCJpbml0aWFsQWN0aXZlSW50ZXJmYWNlIjoibnJxbEVkaXRvciIsImluaXRpYWxOcnFsVmFsdWUiOiIiLCJpbml0aWFsUXVlcmllcyI6W3sibnJxbCI6IkZST00gTG9nIFNFTEVDVCBjb3VudCgqKSB3aGVyZSBuZXdyZWxpYy5zb3VyY2U9JyVvdGxwJScgVElNRVNFUklFUyJ9XSwiaW5pdGlhbENoYXJ0U2V0dGluZ3MiOnsiY2hhcnRUeXBlIjoiQ0hBUlRfTElORSIsImxpbWl0Ijo3NTQyLCJsaW5rZWRFbnRpdHlHdWlkIjpudWxsLCJsaW5rZWREYXNoYm9hcmRJZCI6bnVsbCwieVNjYWxlIjp7InN0YXRpYyI6ZmFsc2UsImRvbWFpbiI6W251bGwsbnVsbF19LCJ5WmVybyI6dHJ1ZX19Cg==). -- See [OpenTelemetry APM UI](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui) for more information. +* Find your entity at **All entities -> Services - OpenTelemetry**. The entity name is set to the value of the app's `service.name` resource attribute. For more information on how New Relic service entities are derived from OpenTelemetry resource attributes, see [Services](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-best-practices-resources/#services) +* Use [NRQL](/docs/nrql/get-started/introduction-nrql-new-relics-query-language/) to query directly for [traces](https://one.newrelic.com/launcher/nr1-core.explorer?overlay=eyJuZXJkbGV0SWQiOiJkYXRhLWV4cGxvcmF0aW9uLnF1ZXJ5LWJ1aWxkZXIiLCJpbml0aWFsQWN0aXZlSW50ZXJmYWNlIjoibnJxbEVkaXRvciIsImluaXRpYWxOcnFsVmFsdWUiOiIiLCJpbml0aWFsUXVlcmllcyI6W3sibnJxbCI6IkZST00gU3BhbiBTRUxFQ1QgY291bnQoKikgd2hlcmUgbmV3cmVsaWMuc291cmNlPSclb3RscCUnIFRJTUVTRVJJRVMifV0sImluaXRpYWxDaGFydFNldHRpbmdzIjp7ImNoYXJ0VHlwZSI6IkNIQVJUX0xJTkUiLCJsaW1pdCI6NzU0MiwibGlua2VkRW50aXR5R3VpZCI6bnVsbCwibGlua2VkRGFzaGJvYXJkSWQiOm51bGwsInlTY2FsZSI6eyJzdGF0aWMiOmZhbHNlLCJkb21haW4iOltudWxsLG51bGxdfSwieVplcm8iOnRydWV9fQo=), [metrics](https://one.newrelic.com/launcher/nr1-core.explorer?overlay=eyJuZXJkbGV0SWQiOiJkYXRhLWV4cGxvcmF0aW9uLnF1ZXJ5LWJ1aWxkZXIiLCJpbml0aWFsQWN0aXZlSW50ZXJmYWNlIjoibnJxbEVkaXRvciIsImluaXRpYWxOcnFsVmFsdWUiOiIiLCJpbml0aWFsUXVlcmllcyI6W3sibnJxbCI6IkZST00gTWV0cmljIFNFTEVDVCBjb3VudCgqKSB3aGVyZSBuZXdyZWxpYy5zb3VyY2UgTElLRSAnJW90bHAlJyBUSU1FU0VSSUVTIn1dLCJpbml0aWFsQ2hhcnRTZXR0aW5ncyI6eyJjaGFydFR5cGUiOiJDSEFSVF9MSU5FIiwibGltaXQiOjc1NDIsImxpbmtlZEVudGl0eUd1aWQiOm51bGwsImxpbmtlZERhc2hib2FyZElkIjpudWxsLCJ5U2NhbGUiOnsic3RhdGljIjpmYWxzZSwiZG9tYWluIjpbbnVsbCxudWxsXX0sInlaZXJvIjp0cnVlfX0K), and [logs](https://one.newrelic.com/launcher/nr1-core.explorer?overlay=eyJuZXJkbGV0SWQiOiJkYXRhLWV4cGxvcmF0aW9uLnF1ZXJ5LWJ1aWxkZXIiLCJpbml0aWFsQWN0aXZlSW50ZXJmYWNlIjoibnJxbEVkaXRvciIsImluaXRpYWxOcnFsVmFsdWUiOiIiLCJpbml0aWFsUXVlcmllcyI6W3sibnJxbCI6IkZST00gTG9nIFNFTEVDVCBjb3VudCgqKSB3aGVyZSBuZXdyZWxpYy5zb3VyY2U9JyVvdGxwJScgVElNRVNFUklFUyJ9XSwiaW5pdGlhbENoYXJ0U2V0dGluZ3MiOnsiY2hhcnRUeXBlIjoiQ0hBUlRfTElORSIsImxpbWl0Ijo3NTQyLCJsaW5rZWRFbnRpdHlHdWlkIjpudWxsLCJsaW5rZWREYXNoYm9hcmRJZCI6bnVsbCwieVNjYWxlIjp7InN0YXRpYyI6ZmFsc2UsImRvbWFpbiI6W251bGwsbnVsbF19LCJ5WmVybyI6dHJ1ZX19Cg==). +* See [OpenTelemetry APM UI](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-ui) for more information. -If you can't find your entity and don't see your data with NRQL, see [OTLP Troubleshooting](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp-troubleshooting). +If you can't find your entity and don't see your data with NRQL, see [OTLP troubleshooting](/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/best-practices/opentelemetry-otlp-troubleshooting). From adafd8405082e6d474b3fac254fb1cae5bbfa67c Mon Sep 17 00:00:00 2001 From: Alan West <3676547+alanwest@users.noreply.github.com> Date: Tue, 4 Jun 2024 13:38:05 -0700 Subject: [PATCH 09/11] We support all the languages --- .../apm-monitoring/opentelemetry-apm-intro.mdx | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx index 68c931bb22d..7b790d68ad3 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx @@ -95,6 +95,14 @@ For more information about what instrumentation is available and more advanced scenarios, please see the relevant [OpenTelemetry language documentation](https://opentelemetry.io/docs/languages/). + + You can use any language that OpenTelemetry supports to send data to New Relic. + Though, the examples above reflect only a subset of the + [supported languages](https://opentelemetry.io/docs/languages/). + + If there's a language you'd like to see an example for, please submit a request! + + From d2aa864b9ec517dc93c57d711508e7505c3e3058 Mon Sep 17 00:00:00 2001 From: Alan West <3676547+alanwest@users.noreply.github.com> Date: Tue, 4 Jun 2024 13:44:45 -0700 Subject: [PATCH 10/11] Update src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx Co-authored-by: ally sassman <42753584+ally-sassman@users.noreply.github.com> --- .../get-started/apm-monitoring/opentelemetry-apm-intro.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx index 480733cde17..e8fe53c6d5f 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx @@ -102,7 +102,7 @@ scenarios, see the relevant Though, the examples above reflect only a subset of the [supported languages](https://opentelemetry.io/docs/languages/). - If there's a language you'd like to see an example for, please submit a request! + If there's a language you'd like to see an example for, please [submit a request](https://github.com/newrelic/newrelic-opentelemetry-examples/issues/new?assignees=&labels=enhancement%2C+needs-triage&projects=&template=enhancement.md&title= )! From ff6e871dd3e1e8e730828497878ff2dbd48bd5a2 Mon Sep 17 00:00:00 2001 From: a-sassman Date: Tue, 4 Jun 2024 13:59:40 -0700 Subject: [PATCH 11/11] fix(OTEL): phrasing of callout --- .../apm-monitoring/opentelemetry-apm-intro.mdx | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx index e8fe53c6d5f..fe6e2913fa6 100644 --- a/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx +++ b/src/content/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/get-started/apm-monitoring/opentelemetry-apm-intro.mdx @@ -98,11 +98,9 @@ scenarios, see the relevant [OpenTelemetry language documentation](https://opentelemetry.io/docs/languages/). - You can use any language that OpenTelemetry supports to send data to New Relic. - Though, the examples above reflect only a subset of the - [supported languages](https://opentelemetry.io/docs/languages/). - - If there's a language you'd like to see an example for, please [submit a request](https://github.com/newrelic/newrelic-opentelemetry-examples/issues/new?assignees=&labels=enhancement%2C+needs-triage&projects=&template=enhancement.md&title= )! + You can use any language that OpenTelemetry supports to send data to New Relic. However, the examples above reflect only a subset of the [supported languages](https://opentelemetry.io/docs/languages/). + + Missing your language? Request an example by [opening an issue on GitHub](https://github.com/newrelic/newrelic-opentelemetry-examples/issues/new?assignees=&labels=enhancement%2C+needs-triage&projects=&template=enhancement.md&title=)!