Before you can view the trace data of your application in the Tracing Analysis console, you must use a client to submit the trace data to Tracing Analysis. This topic describes how to instrument an application and submit trace data.

Prerequisites

To obtain an endpoint of OpenTelemetry, perform the following steps:
  1. Log on to the Tracing Analysis console. In the top navigation bar, select a region.
  2. In the left-side navigation pane, click Cluster Configurations. Then, click the Access point information tab.
  3. In the Cluster Information section of the Access point information tab, turn on Show Token.
  4. In the Client section, click OpenTelemetry.
    Obtain an endpoint of OpenTelemetry in the Related Information column of the table in the lower part. Endpoint of OpenTelemetry
    Note
    • If your application is deployed in an Alibaba Cloud production environment, use a private endpoint. Otherwise, use a public endpoint.

Use the OpenTelemetry Java Agent to perform automatic instrumentation on an application

The OpenTelemetry Java Agent supports dozens of frameworks and allows you to connect OpenTelemetry to Tracing Analysis in a non-intrusive manner. For more information, see Manual Instrumentation.

  1. Download the OpenTelemetry Java Agent.
  2. Modify the VM parameters in the Java startup configuration to submit trace data.
    -javaagent:/path/to/opentelemetry-javaagent.jar    // Replace the path with the URL that you use to download the OpenTelemetry Java Agent. 
    -Dotel.resource.attributes=service.name=<appName>     // Replace <appName> with an actual application name. 
    -Dotel.exporter.otlp.headers=Authentication=<token>
    -Dotel.exporter.otlp.endpoint=<endpoint>
    • If you want to directly submit trace data, replace <token> with the token that you obtained in the "Connect to Tracing Analysis and authenticate clients" topic. Then, replace <endpoint> with the endpoint of the region to which you want to submit the trace data.

      Sample code:

      -javaagent:/Users/carpela/Downloads/opentelemetry-javaagent.jar
      -Dotel.resource.attributes=service.name=ot-java-agent-sample
      -Dotel.exporter.otlp.headers=Authentication=b590xxxxuqs@3a75d95xxxxx9b_b59xxxxguqs@53dxxxx2afe8301
      -Dotel.exporter.otlp.endpoint=http://tracing-analysis-dc-bj:8090
    • If you want to use the OpenTelemetry Collector to forward trace data, remove -Dotel.exporter.otlp.headers=Authentication=<token> and replace <endpoint> with the URL of the service that is deployed on an on-premises host.

Use OpenTelemetry SDK for Java to manually instrument an application

The OpenTelemetry Java Agent is implemented based on OpenTelemetry SDK for Java. The SDK provides various custom features. If the tracking points that are configured by using the OpenTelemetry Java Agent no longer meet your scenarios or you want to create custom tracking points, perform the following steps:

  1. Add the following dependencies to the pom.xml file of a Maven project:
    <dependencies>
            <dependency>
                <groupId>io.opentelemetry</groupId>
                <artifactId>opentelemetry-api</artifactId>
            </dependency>
            <dependency>
                <groupId>io.opentelemetry</groupId>
                <artifactId>opentelemetry-sdk-trace</artifactId>
            </dependency>
            <dependency>
                <groupId>io.opentelemetry</groupId>
                <artifactId>opentelemetry-exporter-otlp</artifactId>
            </dependency>
            <dependency>
                <groupId>io.opentelemetry</groupId>
                <artifactId>opentelemetry-sdk</artifactId>
            </dependency>
        </dependencies>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>io.opentelemetry</groupId>
                    <artifactId>opentelemetry-bom</artifactId>
                    <version>1.9.0</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
  2. Obtain an OpenTelemetry tracer.
    SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder()
                    .addSpanProcessor(BatchSpanProcessor.builder(OtlpGrpcSpanExporter.builder()
                            .setEndpoint("<endpoint>")
                            .addHeader("Authentication", "<token>")
                            .build()).build())
                    .build();
    
    OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
                    .setTracerProvider(sdkTracerProvider)
                    .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance()))
                    .buildAndRegisterGlobal();
    
    Tracer tracer = openTelemetry.getTracer("instrumentation-library-name", "1.0.0");
  3. Modify the following code. For more information, see Manual Instrumentation.
    package com.alibaba.arms.brightroar.console.controller;
    
    import com.alibaba.arms.brightroar.console.service.UserService;
    import com.alibaba.arms.brightroar.console.util.OpenTelemetrySupport;
    import io.opentelemetry.api.GlobalOpenTelemetry;
    import io.opentelemetry.api.OpenTelemetry;
    import io.opentelemetry.api.trace.Span;
    import io.opentelemetry.api.trace.SpanContext;
    import io.opentelemetry.api.trace.StatusCode;
    import io.opentelemetry.api.trace.Tracer;
    import io.opentelemetry.context.Context;
    import io.opentelemetry.context.Scope;
    import io.opentelemetry.extension.annotations.SpanAttribute;
    import io.opentelemetry.extension.annotations.WithSpan;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    /**
     * References:
     * 1. https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/docs/manual-instrumentation.md#creating-spans-manually-with-a-tracer
     * 2. https://opentelemetry.io/docs/java/manual_instrumentation/
     */
    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        private ExecutorService es = Executors.newFixedThreadPool(5);
    
        // Method 3: Use a tracer to obtain a custom tracking point.
        private void biz() {
            Tracer tracer = OpenTelemetrySupport.getTracer();
            Span span = tracer.spanBuilder("biz (manual)")
                    .setParent(Context.current().with(Span.current())) // Optional. The system automatically configures the settings
                    .startSpan();
    
            try (Scope scope = span.makeCurrent()) {
                span.setAttribute("biz-id", "111");
    
                es.submit(new Runnable() {
                    @Override
                    public void run() {
                        Span asyncSpan = tracer.spanBuilder("async")
                                .setParent(Context.current().with(span))
                                .startSpan();
    
                        try {
                            Thread.sleep(1000L); // some async jobs
                        } catch (Throwable e) {
                        }
                        asyncSpan.end();
                    }
                });
    
                Thread.sleep(1000); // fake biz logic
                System.out.println("biz done");
                OpenTelemetry openTelemetry = GlobalOpenTelemetry.get();
                openTelemetry.getPropagators();
            } catch (Throwable t) {
                span.setStatus(StatusCode.ERROR, "handle biz error");
            } finally {
                span.end();
            }
        }
    
    
    
    }
                            
  4. Modify the VM parameters in the Java startup configuration to submit trace data.
    -javaagent:/path/to/opentelemetry-javaagent.jar    // Replace the path with the URL that you use to download the OpenTelemetry Java Agent. 
    -Dotel.resource.attributes=service.name=<appName>     // Replace <appName> with an actual application name. 
    -Dotel.exporter.otlp.headers=Authentication=<token>
    -Dotel.exporter.otlp.endpoint=<endpoint>
    • If you want to directly submit trace data, replace <token> with the token that you obtained in the "Connect to Tracing Analysis and authenticate clients" topic. Then, replace <endpoint> with the endpoint of the region to which you want to submit the trace data.

      Sample code:

      -javaagent:/Users/carpela/Downloads/opentelemetry-javaagent.jar
      -Dotel.resource.attributes=service.name=ot-java-agent-sample
      -Dotel.exporter.otlp.headers=Authentication=b590xxxxuqs@3a75d95xxxxx9b_b59xxxxguqs@53dxxxx2afe8301
      -Dotel.exporter.otlp.endpoint=http://tracing-analysis-dc-bj:8090
    • If you want to use the OpenTelemetry Collector to forward trace data, remove -Dotel.exporter.otlp.headers=Authentication=<token> and replace <endpoint> with the URL of the service that is deployed on an on-premises host.
  5. Start the application.

    On the Applications page in the Tracing Analysis console, click the name of the application and view the trace data.

Use the OpenTelemetry Java Agent and OpenTelemetry SDK for Java to instrument applications

You can use the OpenTelemetry Java Agent to perform automatic instrumentation and use OpenTelemetry SDK for Java to create custom tracking points.

  1. Use the OpenTelemetry Java Agent to collect the trace data of an application.
  2. Add the following dependencies to the pom.xml file of the Maven project based on the dependencies of OpenTelemetry SDK for Java:
    <dependency>
                <groupId>io.opentelemetry</groupId>
                <artifactId>opentelemetry-extension-annotations</artifactId>
            </dependency>
            <dependency>
                <groupId>io.opentelemetry</groupId>
                <artifactId>opentelemetry-sdk-extension-autoconfigure</artifactId>
                <version>1.9.0-alpha</version>
            </dependency>
    Note In the preceding code, the opentelemetry-sdk-extension-autoconfigure dependency is used to automatically configure OpenTelemetry SDK for Java and transfer the settings of OpenTelemetry Java Agent to the SDK.
  3. Obtain an OpenTelemetry tracer.
    OpenTelemetry openTelemetry = GlobalOpenTelemetry.get();
    Tracer tracer = openTelemetry.getTracer("instrumentation-library-name", "1.0.0");
  4. Modify the following code. We recommend that you use Method 1 and Method 2 in the code. For more information, see Manual Instrumentation.
    package com.alibaba.arms.brightroar.console.controller;
    
    import com.alibaba.arms.brightroar.console.service.UserService;
    import com.alibaba.arms.brightroar.console.util.OpenTelemetrySupport;
    import io.opentelemetry.api.GlobalOpenTelemetry;
    import io.opentelemetry.api.OpenTelemetry;
    import io.opentelemetry.api.trace.Span;
    import io.opentelemetry.api.trace.SpanContext;
    import io.opentelemetry.api.trace.StatusCode;
    import io.opentelemetry.api.trace.Tracer;
    import io.opentelemetry.context.Context;
    import io.opentelemetry.context.Scope;
    import io.opentelemetry.extension.annotations.SpanAttribute;
    import io.opentelemetry.extension.annotations.WithSpan;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    /**
     * References:
     * 1. https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/docs/manual-instrumentation.md#creating-spans-manually-with-a-tracer
     * 2. https://opentelemetry.io/docs/java/manual_instrumentation/
     */
    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        private ExecutorService es = Executors.newFixedThreadPool(5);
    
        // Method 3: Use a tracer to obtain a custom tracking point.
        private void biz() {
            Tracer tracer = OpenTelemetrySupport.getTracer();
            Span span = tracer.spanBuilder("biz (manual)")
                    .setParent(Context.current().with(Span.current())) // Optional. The system automatically configures the settings.
                    .startSpan();
    
            try (Scope scope = span.makeCurrent()) {
                span.setAttribute("biz-id", "111");
    
                es.submit(new Runnable() {
                    @Override
                    public void run() {
                        Span asyncSpan = tracer.spanBuilder("async")
                                .setParent(Context.current().with(span))
                                .startSpan();
    
                        try {
                            Thread.sleep(1000L); // some async jobs
                        } catch (Throwable e) {
                        }
                        asyncSpan.end();
                    }
                });
    
                Thread.sleep(1000); // fake biz logic
                System.out.println("biz done");
                OpenTelemetry openTelemetry = GlobalOpenTelemetry.get();
                openTelemetry.getPropagators();
            } catch (Throwable t) {
                span.setStatus(StatusCode.ERROR, "handle biz error");
            } finally {
                span.end();
            }
        }
    
        // Method 2: Instrument an application based on tags.
        @WithSpan
        private void child(@SpanAttribute("user.type") String userType) {
            System.out.println(userType);
            biz();
        }
    
        // Method 1: Perform automatic instrumentation on an application. Call an API operation to add information.
        @RequestMapping("/async")
        public String async() {
            System.out.println("UserController.async -- " + Thread.currentThread().getId());
            Span span = Span.current();
            span.setAttribute("user.id", "123456");
            userService.async();
            child("vip");
            return "async";
        }
    
    }
                            
  5. Modify the VM parameters in the Java startup configuration to submit trace data.
    -javaagent:/path/to/opentelemetry-javaagent.jar    // Replace the path with the URL that you use to download the OpenTelemetry Java Agent. 
    -Dotel.resource.attributes=service.name=<appName>     // Replace <appName> with an actual application name. 
    -Dotel.exporter.otlp.headers=Authentication=<token>
    -Dotel.exporter.otlp.endpoint=<endpoint>
    • If you want to directly submit trace data, replace <token> with the token that you obtained in the "Connect to Tracing Analysis and authenticate clients" topic. Then, replace <endpoint> with the endpoint of the region to which you want to submit the trace data.

      Examples:

      -javaagent:/Users/carpela/Downloads/opentelemetry-javaagent.jar
      -Dotel.resource.attributes=service.name=ot-java-agent-sample
      -Dotel.exporter.otlp.headers=Authentication=b590xxxxuqs@3a75d95xxxxx9b_b59xxxxguqs@53dxxxx2afe8301
      -Dotel.exporter.otlp.endpoint=http://tracing-analysis-dc-bj:8090
    • If you want to use the OpenTelemetry Collector to forward trace data, remove -Dotel.exporter.otlp.headers=Authentication=<token> and replace <endpoint> with the URL of the service that is deployed on an on-premises host.
  6. Starts the application.

    On the Applications page in the Tracing Analysis console, click the name of the application and view the trace data.