This topic describes how to import trace data from Android apps to Log Service by using Log Service SDK for Android.

Prerequisites

A trace instance is created. For more information, see Create a trace instance.

Step 1: Import library files

Add the following dependencies to the build.gradle file of the related module in Android Studio:
implementation 'com.aliyun.openservices:aliyun-log-android-sdk:bricks_1.0.7'
implementation 'com.aliyun.openservices:alysls-android-trace:1.0.0'
The following table describes the dependency packages that are required to import trace data from Android apps.
Library file Description
aliyun-log-android-sdk Contains the core SDK that is used to import data from Android apps to Log Service.
alysls-android-trace Contains the plug-in that is used to import trace data.

Step 2: Configure a service to import data

  1. Add an Application class to the $PROJECT/app/src/main/AndroidManifest.xml file.

    The following example shows how to add the MyApplication class:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
              package="com.aliyun.sls.android.demo">
        ...
    
        <application
            android:icon="@mipmap/ic_launcher"
            ...
            android:name="com.aliyun.sls.android.demo.SLSDemoApplication"
            ...
            android:theme="@style/AppTheme">
                ...
        </application>
    </manifest>
    Android Studio automatically creates a class named MyApplication based on the MyApplication class that you added, and then adds the new class to the current project.
  2. In the MyApplication.onCreate method, add the following initialization code:
    public class MyApplication extends Application {
    
        @Override
        public void onCreate() {
            super.onCreate();
            SLSAdapter adapter = SLSAdapter.getInstance();
            // Add the Trace plug-in. 
            adapter.addPlugin(SLSTracePlugin.getInstance());
    
            SLSConfig config = new SLSConfig(this);
            config.pluginTraceEndpoint = "endpoint";
            config.pluginTraceLogProject = "project";
            config.pluginTraceLogStore = "store";
            // Enable log debugging based on integration. 
            config.debuggable = true;
    
            adapter.init(config);
        }
    }
    • SLSConfig
      The following table describes the parameters in the SLSConfig class.
      Category Parameter Example Description
      Debugging parameter debuggable true Specifies whether to enable log debugging.
      Note When you publish the app, we recommend that you specify config.debuggable = false to disable log debugging.
      Configuration parameter appVersion None The version number of the app. We recommend that you use the default settings.
      appName None The name of the app. We recommend that you use the default settings.
      Configuration parameter traceEndpoint cn-hangzhou.log.aliyuncs.com The endpoint of the project that is specified when you created the trace instance. For more information, see Public Log Service endpoints.
      Notice Only public Log Service endpoints are supported.
      traceLogProject sls-ayasls-demo The name of the project that is specified when you created the trace instance. For more information, see Create a trace instance.
      traceLogStore sls-d60f-traces The name of the Logstore that is used to store raw trace data in the Trace application. The name of the Logstore is in the {instance}-traces format. The value of the instance variable is the ID of the trace instance that you created. For more information, see Create a trace instance.
      accessKeyId LTAI****eYDw The AccessKey ID of the RAM user that has the permissions to access the Log Service project. For information about how to obtain an AccessKey pair, see AccessKey pair. For information about how to grant the required permissions to a RAM user, see Use the permission assistant to grant permissions.
      accessKeySecret lrRq****GOVM The AccessKey secret of the RAM user that has the permissions to access the Log Service project. For information about how to obtain an AccessKey pair, see AccessKey pair. For information about how to grant the required permissions to a RAM user, see Use the permission assistant to grant permissions.
      securityToken 124f****a369 The Security Token Service (STS) token of the RAM user that has the permissions to access the Log Service project. Before you use STS to access the project, you must obtain an STS token. For more information, see AssumeRole.
      Custom parameter channel Google The custom parameter that specifies the channel identifier of the app.
      channelName Google The custom parameter that specifies the channel name of the app.
      userNick Tom The custom parameter that specifies the nickname of the user.
      longLoginNick Tom The custom parameter that specifies the user nickname used for the last logon.
      userId 423423 The custom parameter that specifies the ID of the user.
      longLoginUserId 423423 The custom parameter that specifies the user ID used for the last logon.
      loginType pswd The custom parameter that specifies the logon type.
      Business parameter slsConfig.addCustom("customKey", "customValue"); slsConfig.addCustom("action_name", "click");slsConfig.addCustom("action_args", "detail_id:243434"); The business parameters in the format of key-value pairs.
      • customKey: the name of the business parameter.
      • customValue: the value of the business parameter.
    • SLSAdapter
      The SLSAdapter class is used to manage plug-ins.
      Method Description
      getInstance() Returns an SLSAdapter singleton instance.
      addPlugin(plugin) Adds a plug-in.
      init(slsConfig) Initializes all plug-ins.
      Notice The init() method is called to initialize all plug-ins. Do not call the init() method of a plug-in. Before you call the init() method, you must call the addPlugin() method.
      resetSecurityToken(accessKeyId, accessKeySecret, securityToken) Updates STS tokens.
      Notice Before you call the resetSecurityToken() method, you must call the initWithSLSConfig method.
      updateConfig(slsConfig) Updates the settings of the SLSConfig class. You can call this method to update the traceEndpoint, traceLogProject, and traceLogStore parameters and custom parameters.
      Notice Before you call the updateConfig () method, you must call the initWithSLSConfig method.
  3. Use STS to set the accessKeyId, accessKeySecret, and securityToken parameters.
    public class MyApplication extends Application {
    
        @Override
        public void onCreate() {
            super.onCreate();
            SLSAdapter adapter = SLSAdapter.getInstance();
            // Add the Trace plug-in. 
            adapter.addPlugin(SLSTracePlugin.getInstance());
    
            SLSConfig config = new SLSConfig(this);
            // Specify the AccessKey pair and STS token when you initialize the code. 
            config.accessKeyId = accesskeyid;
            config.accessKeySecret = accesskeysecret;
            config.securityToken = securityToken;
    
            config.pluginTraceEndpoint = "endpoint";      
            config.pluginTraceLogProject = "project";
            config.pluginTraceLogStore = "logstore";
            // Enable log debugging based on integration. 
            config.debuggable = true;
    
            adapter.init(config);
        }
    }
  4. Construct a span.
    // 1. Obtain the trace instance. 
    Tracer tracer = SLSTelemetry.getInstance().getTracer("your_tracer_name");
    // 2. Construct SpanBuilder. 
    SpanBuilder spanBuilder = tracer.spanBuilder("your_span_name");
    spanBuilder.setAttribute("Attribute key", "Attribute value");
    // 3. Construct a span. 
    Span span = spanBuilder.startSpan();
    // Add an attribute based on your business requirements. 
    span.setAttribute("Attribute key", "Attribute value");
    // Add an event based on your business requirements. 
    span.addEvent("your event");
    // 4. Specify the status of the span. Default value: UNSET. Set OK on a completed span. If the span is not completed, set the status to ERROR. 
    span.setStatus(StatusCode.OK);
    // 5. End the span. 
    span.end();
  5. Construct trace data.
    // 1. Obtain the trace instance. 
    Tracer tracer = SLSTelemetry.getInstance().getTracer("your_tracer_name");
    
    // 2. Construct the first span. 
    SpanBuilder spanBuilder = tracer.spanBuilder("your_span_name_1");
    spanBuilder.setAttribute("Attribute key1", "Attribute value1");
    Span span = spanBuilder.startSpan();
    span.setAttribute("Attribute key2", "Attribute value2");
    span.addEvent("your event");
    span.setStatus(StatusCode.OK);
    
    // 3. Construct the second span. 
    SpanBuilder spanBuilder = tracer
                                .spanBuilder("your_span_name_2")
                                // Specify the context of the first span. 
                                .setParent(Context.current().with(span));
    spanBuilder.setAttribute("Attribute key1", "Attribute value1");
    Span span2 = spanBuilder.startSpan();
    span.setAttribute("Attribute key2", "Attribute value2");
    span2.addEvent("your event");
    span2.setStatus(StatusCode.OK);
    // 4. End the second span. 
    span2.end();
    
    // 5. End the first span. 
    span.end();
  6. Use TextMapPropagator to connect the Android app and the backend.
    // 1. Obtain the trace instance. 
    Tracer tracer = SLSTelemetry.getInstance().getTracer("your_tracer_name");
    
    // 2. Construct the first span. 
    SpanBuilder spanBuilder=tracer.spanBuilder ("/"); // Specify a name for the span. 
    spanBuilder.setAttribute("Attribute key1", "Attribute value1");
    Span span = spanBuilder.startSpan();
    span.setAttribute("Attribute key2", "Attribute value2");
    span.addEvent("your event");
    span.setStatus(StatusCode.OK);
    span.end();
    
    // In this example, HttpURLConnection is used. 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    // 3. Construct TextMapSetter. 
    TextMapSetter<HttpURLConnection> setter = new TextMapSetter<HttpURLConnection>() {
        @Override
        public void set(HttpURLConnection carrier, String key, String value) {
            carrier.setRequestProperty(key, value);
        }
    };
    // 4. Inject traceparent and tracestate in HTTP request headers. 
    SLSTelemetry slsTelemetry = SLSTelemetry.getInstance();
    TextMapPropagator textMapPropagator = slsTelemetry.getPropagators().getTextMapPropagator();
    textMapPropagator.inject(context, connection, setter);

What to do next