All Products
Search
Document Center

Managed Service for OpenTelemetry:Use OpenTelemetry to report the trace data of Android applications

Last Updated:Jun 25, 2023

Before you can view the trace data of your application in the Managed Service for OpenTelemetry console, you must report the trace data to Managed Service for OpenTelemetry. This topic describes how to instrument an Android application and report the trace data of the Android application.

Prerequisites

To obtain an endpoint of OpenTelemetry, perform the following steps:
  1. Log on to the Tracing Analysis console.
  2. In the left-side navigation pane, click Cluster Configurations. Then, click the Access point information tab.
  3. In the top navigation bar, select a region. In the Cluster Information section, 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 an access point of Alibaba Cloud VPC. Otherwise, use a public endpoint.

Sample code

In this example, OpenTelemetry is used to report the trace data of an Android application. The method used in this example also applies to applications written in Java or Kotlin.

You can download the sample code from opentelemetry-android-demo.

Step 1: Create and configure an application

  1. Create an application.

    1. Create an application in Android Studio. Select Basic Views Activity and click Next.image..png

    2. Select Java or Kotlin as Language, select API 24: Android 7.0 (Nougat) as Minimum SDK, and then click Finish.

  2. Add dependencies.

    Add the following dependencies to the build.gradle file of a module or project.

    In this example, the version of OpenTelemetry SDK for Java is 1.25.0. For more information about the SDK versions, see Releases of opentelemetry-java. To obtain the complete sample code, see build.gradle.

    implementation platform('io.opentelemetry:opentelemetry-bom:1.25.0')
    implementation "io.opentelemetry:opentelemetry-api"
    implementation "io.opentelemetry:opentelemetry-context"
    implementation 'io.opentelemetry:opentelemetry-exporter-otlp'
    implementation 'io.opentelemetry:opentelemetry-exporter-logging'
    implementation 'io.opentelemetry:opentelemetry-extension-kotlin'
    implementation 'io.opentelemetry:opentelemetry-sdk'
    implementation 'io.opentelemetry:opentelemetry-semconv'
  3. Configure network settings.

    1. Create a file named network_security_config.xml in the app/res/xml directory and add the following content to the file:

      <!-- To view the complete content of the file, visit https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidJavaDemo/app/src/main/res/xml/network_security_config.xml. -->
      
      <?xml version="1.0" encoding="utf-8"?>
      <network-security-config>
        <domain-config cleartextTrafficPermitted="true">
          <!-- Replace the domain name with the endpoint that you have obtained as instructed in the "Prerequisites" section of this topic. The endpoint cannot contain "http://", a port number, or a URL path. -->
          <domain includeSubdomains="true">tracing-analysis-dc-hz.aliyuncs.com</domain>
        </domain-config>
      </network-security-config>
    2. Modify the app/src/main/AndroidManifest.xml file by adding the following content to allow the application to access the network:

      <!-- To view the complete content of the file, visit https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidJavaDemo/app/src/main/AndroidManifest.xml. -->
      
      <?xml version="1.0" encoding="utf-8"?>
      <manifest ...>
        <!-- Add the following line to grant network access permissions. -->
        <uses-permission android:name="android.permission.INTERNET" />
      
        <application
          ...
          <!-- Add the following line to configure the network for the domain name to which you want to report data. -->
          android:networkSecurityConfig="@xml/network_security_config"
          ...>
      
          ...
        </application>
      
      </manifest>

Step 2: Initialize OpenTelemetry

  1. Create an OpenTelemetry utility class.

    Create an OpenTelemetryUtil file in the directory in which the MainActivity file resides and add the following content to the OpenTelemetryUtil file.

    • Method 1: Report trace data over gRPC

      /**
       Visit the following link to view the complete code:
       https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidJavaDemo/app/src/main/java/com/example/androidjavademo/OpenTelemetryUtil.java
      */
      
      Resource otelResource = Resource.getDefault().merge(
          Resource.create(
              Attributes.of(
                  // Replace <your-service-name> with the name of your application. 
              	ResourceAttributes.SERVICE_NAME, "<your-service-name>",
                  // Replace <your-host-name> with the name of your host. 
              	ResourceAttributes.HOST_NAME, "<your-host-name>"
              )
          )
      );
      
      SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder()
          .addSpanProcessor(SimpleSpanProcessor.create(LoggingSpanExporter.create())) // Display the trace data in logs or the command line. This line is optional. Comment this line if you do not need it. 
          // Replace <gRPC-endpoint> with the endpoint that you have obtained as instructed in the "Prerequisites" section of this topic and replace <gRPC-token> with the authentication token. 
          .addSpanProcessor(BatchSpanProcessor.builder(
              OtlpGrpcSpanExporter.builder()
                   .setEndpoint("<gRPC-endpoint>") // Example: http://tracing-analysis-dc-hz.aliyuncs.com:8090
                   .addHeader("Authentication", "<gRPC-token>") // Example: xxxx@xxxx_xxxx@xxxx
                   .build()).build()
          )
          .setResource(otelResource)
          .build();
      
      OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
          .setTracerProvider(sdkTracerProvider)
          .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance()))
          .buildAndRegisterGlobal();
      
      // Obtain the tracer that is used to create a span. 
      tracer = openTelemetry.getTracer("android-tracer", "1.0.0");
      /**
       Visit the following link to view the complete code:
       https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidKotlinDemo/app/src/main/java/com/example/androidkotlindemo/OpenTelemetryUtil.kt
      */
      
      val otelResource = Resource.getDefault().merge(
          Resource.create(
              Attributes.of(
                  ResourceAttributes.SERVICE_NAME, "<your-service-name>", // Replace <your-service-name> with the name of your application. 
                  ResourceAttributes.HOST_NAME, "<your-host-name>"    // Replace <your-host-name> with the name of your host. 
              )
          )
      )
      
      /* Report trace data over gRPC. */
      val sdkTracerProvider = SdkTracerProvider.builder()
          .addSpanProcessor(SimpleSpanProcessor.create(LoggingSpanExporter.create())) // Display the trace data in logs or the command line. This line is optional. Comment this line if you do not need it. 
      	// Replace <gRPC-endpoint> with the endpoint that you have obtained as instructed in the "Prerequisites" section of this topic and replace <gRPC-token> with the authentication token. 
          .addSpanProcessor(
              BatchSpanProcessor.builder(
                  OtlpGrpcSpanExporter.builder()
                      .setEndpoint("<gRPC-endpoint>") // Example: http://tracing-analysis-dc-hz.aliyuncs.com:8090
                      .addHeader("Authentication", "<gRPC-token>") // Example: xxxx@xxxx_xxxx@xxxx
                      .build()
              ).build()
          )
          .setResource(otelResource)
          .build()
      
      val openTelemetry: OpenTelemetry = OpenTelemetrySdk.builder()
          .setTracerProvider(sdkTracerProvider)
          .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance()))
          .buildAndRegisterGlobal()
      
      // Obtain the tracer that is used to create a span. 
      tracer = openTelemetry.getTracer("android-tracer", "1.0.0")
    • Method 2: Report trace data over HTTP

      /**
       Visit the following link to view the complete code:
       https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidJavaDemo/app/src/main/java/com/example/androidjavademo/OpenTelemetryUtil.java
      */
      
      Resource otelResource = Resource.getDefault().merge(
          Resource.create(
              Attributes.of(
                  // Replace <your-service-name> with the name of your application. 
                  ResourceAttributes.SERVICE_NAME, "<your-service-name>",
                  // Replace <your-host-name> with the name of your host. 
                  ResourceAttributes.HOST_NAME, "<your-host-name>"
              )
          )
      );
      
      SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder()
          .addSpanProcessor(SimpleSpanProcessor.create(LoggingSpanExporter.create())) // Display the trace data in logs or the command line. This line is optional. Comment this line if you do not need it.
          // Replace <HTTP-endpoint> with the endpoint that you have obtained as instructed in the "Prerequisites" section of this topic. 
          .addSpanProcessor(BatchSpanProcessor.builder(
              OtlpHttpSpanExporter.builder()
                   .setEndpoint("<HTTP-endpoint>") // Example: http://tracing-analysis-dc-hz.aliyuncs.com/adapt_xxxx@xxxx_xxxx@xxxx/api/otlp/traces
                   .build()).build()
          )
          .setResource(otelResource)
          .build();
      
      OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
          .setTracerProvider(sdkTracerProvider)
          .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance()))
          .buildAndRegisterGlobal();
      
      // Obtain the tracer that is used to create a span. 
      tracer = openTelemetry.getTracer("android-tracer", "1.0.0");
      /**
       Visit the following link to view the complete code:
       https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidKotlinDemo/app/src/main/java/com/example/androidkotlindemo/OpenTelemetryUtil.kt
      */
      
      val otelResource = Resource.getDefault().merge(
          Resource.create(
              Attributes.of(
                  ResourceAttributes.SERVICE_NAME, "<your-service-name>", // Replace <your-service-name> with the name of your application. 
                  ResourceAttributes.HOST_NAME, "<your-host-name>"    // Replace <your-host-name> with the name of your host. 
              )
          )
      )
      
      /* Report trace data over HTTP. */
      val sdkTracerProvider = SdkTracerProvider.builder()
          .addSpanProcessor(SimpleSpanProcessor.create(LoggingSpanExporter.create())) // Display the trace data in logs or the command line. This line is optional. Comment this line if you do not need it. 
      	// Replace <HTTP-endpoint> with the endpoint that you have obtained as instructed in the "Prerequisites" section of this topic. 
          .addSpanProcessor(BatchSpanProcessor.builder(
              OtlpHttpSpanExporter.builder()
                  .setEndpoint("<HTTP-endpoint>") // Example: http://tracing-analysis-dc-hz.aliyuncs.com/adapt_xxxx@xxxx_xxxx@xxxx/api/otlp/traces
                  .build()).build()
                           )
          .setResource(otelResource)
          .build();
      
      val openTelemetry: OpenTelemetry = OpenTelemetrySdk.builder()
          .setTracerProvider(sdkTracerProvider)
          .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance()))
          .buildAndRegisterGlobal()
      
      // Obtain the tracer that is used to create a span. 
      tracer = openTelemetry.getTracer("android-tracer", "1.0.0")
  2. Initialize OpenTelemetry during the application initialization.

    Call the OpenTelemetryUtil.init() method in the onCreate method of the MainActivity class.

    /**
     Visit the following link to view the complete code:
     https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidJavaDemo/app/src/main/java/com/example/androidjavademo/MainActivity.java
    */
    
    ...
    public class MainActivity extends AppCompatActivity {
    	...
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Add the following line to initialize OpenTelemetry. 
            OpenTelemetryUtil.init();
            ...
        }
        ...
    }
    /**
     Visit the following link to view the complete code:
     https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidKotlinDemo/app/src/main/java/com/example/androidkotlindemo/MainActivity.kt
    */
    ...
    
    class MainActivity : AppCompatActivity() {
    
        ...
        override fun onCreate(savedInstanceState: Bundle?) {
            WindowCompat.setDecorFitsSystemWindows(window, false)
            super.onCreate(savedInstanceState)
            // Add the following line to initialize OpenTelemetry. 
            OpenTelemetryUtil.init()
    
                ...
        }
    }

Step 3: Create a span to track trace data

  1. Create a span.

    In the method of monitoring button tap events in the FirstFragment file, create a span named First Fragment Button onClick.

    /**
     Visit the following link to view the complete code:
     https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidJavaDemo/app/src/main/java/com/example/androidjavademo/FirstFragment.java
    */
    
    public void onClick(View view) {
        // Obtain the tracer.
        Tracer tracer = OpenTelemetryUtil.getTracer();
    	// Create a span.
        Span span = tracer.spanBuilder("First Fragment Button onClick").startSpan();
    	try (Scope scope = span.makeCurrent()) {
            // Obtain the trace ID.
            System.out.println(span.getSpanContext().getTraceId());
            ...
        } finally {
            span.end();
        }
    }
    /**
     Visit the following link to view the complete code:
     https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidKotlinDemo/app/src/main/java/com/example/androidkotlindemo/FirstFragment.kt
    */
    
    binding.buttonFirst.setOnClickListener {
        // Obtain the tracer.
        val tracer: Tracer = OpenTelemetryUtil.getTracer()!!
        // Create a span.
        val span = tracer.spanBuilder("First Fragment Button onClick").startSpan()
        try {
            span.makeCurrent().use { scope ->
                // Obtain the trace ID.
                println(span.spanContext.traceId)
                // Obtain the span ID.
                println(span.spanContext.spanId)
                
                findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
            }
        } catch (t: Throwable) {
            span.setStatus(StatusCode.ERROR, "Something wrong in onClick")
            throw t
        } finally {
            span.end()
        }
    }
  2. Configure attributes and an event for the span.

    /**
     Visit the following link to view the complete code:
     https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidJavaDemo/app/src/main/java/com/example/androidjavademo/FirstFragment.java
    */
    
    // Configure attributes.
    span.setAttribute("key", "value");
    
    Attributes eventAttributes = Attributes.of(
        AttributeKey.stringKey("key"), "value",
        AttributeKey.longKey("result"), 0L);
    // Add an event.
    span.addEvent("onClick", eventAttributes);
    /**
     Visit the following link to view the complete code:
     https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidKotlinDemo/app/src/main/java/com/example/androidkotlindemo/FirstFragment.kt
    */
    
    // Configure attributes.
    span.setAttribute("key", "value")
    val eventAttributes =
        Attributes.of(
            AttributeKey.stringKey("key"), "value",
            AttributeKey.longKey("result"), 0L
        )
    
    // Add an event.
    span.addEvent("onClick", eventAttributes)
  3. Configure the status of the span.

    /**
     Visit the following link to view the complete code:
     https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidJavaDemo/app/src/main/java/com/example/androidjavademo/FirstFragment.java
    */
    
    ...
    try (Scope scope = span.makeCurrent()) {
        ...
    } catch (Throwable t) {
        // Configure the status of the span.
        span.setStatus(StatusCode.ERROR, "Something wrong in onClick");
        throw t;
    } finally {
        span.end(); 
    }
    /**
     Visit the following link to view the complete code:
     https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidKotlinDemo/app/src/main/java/com/example/androidkotlindemo/FirstFragment.kt
    */
    
    ...
    try {
        ...
    } catch (t: Throwable) {
        // Configure the status of the span.
        span.setStatus(StatusCode.ERROR, "Something wrong in onClick")
        throw t
    } finally {
        span.end()
    }
  4. Create a nested span.

    /**
     Visit the following link to view the complete code:
     https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidJavaDemo/app/src/main/java/com/example/androidjavademo/FirstFragment.java
    */
    
    public void parentSpan() {
        // Obtain the tracer.
        Tracer tracer = OpenTelemetryUtil.getTracer();
        // Create a span.
        Span span = tracer.spanBuilder("Parent Span").startSpan();
        try (Scope scope = span.makeCurrent()) {
            // Obtain the trace ID.
            System.out.println(span.getSpanContext().getTraceId());
            // Obtain the span ID.
            System.out.println(span.getSpanContext().getSpanId());
            childSpan();
        } finally {
            span.end();
        }
    }
    
    public void childSpan() {
        // Obtain the tracer.
        Tracer tracer = OpenTelemetryUtil.getTracer();
        // Create a span.
        Span span = tracer.spanBuilder("Child Span").startSpan();
        try (Scope scope = span.makeCurrent()) {
            // Obtain the trace ID.
            System.out.println(span.getSpanContext().getTraceId());
            // Obtain the span ID.
            System.out.println(span.getSpanContext().getSpanId());
        } finally {
            span.end();
        }
    }
    /**
     Visit the following link to view the complete code:
     https://github.com/alibabacloud-observability/android-demo/blob/master/AndroidKotlinDemo/app/src/main/java/com/example/androidkotlindemo/FirstFragment.kt
    */
    
    // Nested span.
    fun parentSpan() {
        // Obtain the tracer.
        val tracer: Tracer = OpenTelemetryUtil.getTracer()!!
        // Create a span.
        val span = tracer.spanBuilder("Parent Span").startSpan()
        try {
            span.makeCurrent().use { scope ->
                // Obtain the trace ID.
                println(span.spanContext.traceId)
                // Obtain the span ID.
                println(span.spanContext.spanId)
                childSpan()
            }
        } finally {
            span.end()
        }
    }
    
    // Nested span.
    fun childSpan() {
        // Obtain the tracer.
        val tracer: Tracer = OpenTelemetryUtil.getTracer()!!
        // Create a span.
        val span = tracer.spanBuilder("Child Span").startSpan()
        try {
            span.makeCurrent().use { scope ->
                // Obtain the trace ID.
                println(span.spanContext.traceId)
                // Obtain the span ID.
                println(span.spanContext.spanId)
            }
        } finally {
            span.end()
        }
    }

Step 4: Run the project to view the reported trace data

  1. Run the project and simulate a button tap on the application page.image..png

    You can view the logs in Logcat, including the span information that is exported by using LoggingSpanExporter.

    image..png
  2. On the Applications page in the Managed Service for OpenTelemetry console, click the name of the application. On the page that appears, view the trace data.

    image..png