Skip to content

Supportability for Android

The SAP Mobile Platform SDK provides a set of features and APIs (collectively referred to as supportability) that captures errors, traces and logs events, then uploads this information to SAP Mobile Platform Server or SAP Cloud Platform mobile service for development and operations, where it can be analyzed from the cockpit.

Define client log and trace policies in the administrator cockpit. For detailed information see Managing Application Logs and Traces (for SAP Mobile Platform Server) or Application Log and Trace Files (for SAP Cloud Platform mobile service for development and operations).

  • Enabling devices to upload logs to the server devices do not upload their logs and traces to the server by default. The server administrator must first enable log and trace retrieval from within the administration cockpit for each device.

  • Enabling end-to-end tracing on the server the administrator must enable end-to-end tracing on the server from within the administration cockpit.

In this section:

Logging and Tracing Overview

SAP Mobile Platform provides supportability through logs and traces that enable administrators, developers, and support professionals to troubleshoot application issues.

Getting Started with Supportability

Set up your Android environment and get familiar with logging and tracing components.

Add Logging to your Android Application

Add logging to your native Android OData app, upload the log to the server, and view the logs.

Add Tracing to your Android Application

Add tracing to your native Android OData app, upload the BTX that contains all collected trace data to the server, and view the trace information.

Logging and Tracing Overview

SAP Mobile Platform provides supportability through logs and traces that enable administrators, developers, and support professionals to troubleshoot application issues. All logs have a common format and are stored in the SAP Mobile Platform Server database. All log entries for a particular business or application flow (such as an OData request or a registration) are correlated across the client and server stack. This enables you to visualize and understand the end-to-end flow, which helps in identifying the source of an application problem. In addition to logs and traces, you can activate end to end tracing on a per user/device basis to enable support to perform end-to-end diagnostics to identify performance or functional application problems.

System logs collect log messages that allow administrators and support professionals to identify problem areas. Developers can identify code problems by capturing debug level log messages. Set the log level for individual logging components to specify the amount of information captured.

Application tracing captures additional business data for a request (such as message data, payloads, HTTP headers, and URIs), which you can use to troubleshoot application problems. The business data captured in application traces is determined by the application developer. Enable tracing for individual logging components on an as-needed basis.

alt text

E2E tracing sessions are conducted by administrators and device users. E2E trace information is recorded in a Business Transaction XML (BTX) file on the client, which is uploaded to the server, and then uploaded to SAP Solution Manager for analysis.

Getting Started with Supportability

Set up your Android environment and get familiar with logging and tracing components.

Getting Started

  • Environment Set Up

Follow the environment setup documentation for using gradle if developing your mobile app in Android Studio. See Setting Up the Android Development Environment. After extracting the libraries and resources, make sure your application references these libraries:

SupportabilityFacade-*.jar
ClientLog-*.jar
E2ETrace-*.jar
simple-xml-*.jar
HttpConversation-*.jar
HttpConvAuthFlows-*.jar
  • Requirements

    • Minimum Android SDK version: 5.0 (21)
    • Target Android SDK version: 5.0 (21)
    • Compile SDK version: 8.0 (26)
  • Architecture

alt text

  • SupportabilityFacade Component: provides an additional level of abstraction; prevents developers from interacting directly with the underlying sub-components.

  • ClientLog Component: includes a set of logging related management and the consumer interfaces and classes.

  • E2ETrace Component: includes a set of E2E tracing related management and the consumer interfaces and classes.

Public interfaces include:

  • com.sap.smp.client.supportability.Supportability: an abstraction on top of the underlying E2ETrace and ClientLogger components. Clients retrieve the required management and consumer instances via the exposed APIs and factory methods.
  • com.sap.smp.client.supportability.ClientLogManager: the central access point to loggers; provides setters to common properties used by various loggers.
  • com.sap.smp.client.supportability.ClientLogger: defines the interface for client loggers. The ClientLog library provides a default implementation.
  • com.sap.smp.client.supportability.E2ETraceManager: provides management API for End-To-End tracing. The E2ETraceManager library provides a default implementation.
  • com.sap.smp.client.supportability.E2ETrace: clients should use the APIs exposed by the E2ETrace interface when implementing end-to-end tracing.

Add Logging to your Android Application

Add logging to your native Android OData app, upload the log to the server, and view the logs.

Logging

Use logging features provided by supportability and logging libraries.

  • Logger Creation and Setup

    The Supportability framework provides advanced logging capabilities. Instantiate dedicated and custom logger objects using ClientLogManager’s getLogger method. The various SDK components use specific loggers internally. 1. Add this statement to import the required classes from the namespaces:

    ```java
    import com.sap.smp.client.supportability.*;
    ```
    
    1. Query the default client log manager:

      java// Get ClientLogManager instanceClientLogManager logMan = Supportability.getInstance().getClientLogManager(this);

      By default, loggers persist their logs in a local file system. If you need the logs to also appear in the console, you can override the default using the ClientLogManager’s setLogDestination API. The API expects values defined in an EnumSet of ClientLogDestination types, and therefore can be combined:

      java// Gets it for every loggerlogMan.setLogDestination(EnumSet.of(ClientLogDestination.CONSOLE, ClientLogDestination.FILESYSTEM));

    Note: This is a global setting that is applied to all loggers (both currently active and for those created later).

    1. Set the log output destination and log level. Two log destinations are supported:

      • Console logs are displayed in Android Studio's debug console
      • FileSystem logs are persisted in the clients local storage

      ClientLogManager’s setLogLevel method allows setting of the global log level. The default log level is ERROR, which makes your logs less verbose; however, if you need more detailed log messages, you can lower the log level to Warning or Debug:

      ```java // Set the desired log level on all the loggers logMan.setLogLevel(ClientLogLevel.DEBUG);

      // Set the desired log level for a particular logger // optional: default is ErrorClientLogLevel logManager.setLogLevel(ClientLogLevel.INFO, "LOGGER_PARSER"); logManager.setLogLevel(ClientLogLevel.FATAL, "LOGGER_SERVER");

      // Set the log destination for a particular logger logManager.setLogDestination(EnumSet.of(ClientLogDestination.CONSOLE), "LOGGER_PARSER"); ``` To instantiate a custom logger, provide a unique ID to every particular custom logger. Reusing the same logger ID produces the same logger instance:

      java// Instantiate a custom loggerClientLogger customLogger = Supportability.getInstance().getClientLogManager(this).getLogger("LOGGER_PARSER");

    2. Log a warning using the newly created logger:

      javacustomLogger.logWarning("Warning message goes here");

      In a real application, create a logger member variable, to use throughout the given implementation class.

  • Fine Tune Logger Settings

    The global setting applies for all existing logger instances, and provides default values for loggers to be created later. (If no global setting is made, the original defaults apply; Error for log level and File system for log destination.)

    Global settings can be overridden on a per logger basis, which is useful if you want to silence some components, while enabling logging for a group of selected loggers (for example, to identify issues in a specific part of the project, or focus on a small subset of components).

    ```java // Set log level to DEBUG for this very logger logManager.setLogLevel(ClientLogLevel.DEBUG, "CustomLogger");

    // Do not persist logs, just display them in console window logManager.setLogDestination(EnumSet.of(ClientLogDestination.CONSOLE), "CustomLogger"); ```

  • Client Log Levels

    The default log level setting is ERROR. The following log levels are supported:

    javaClientLogLevel.FATAL > ClientLogLevel.ERROR > ClientLogLevel.WARNING > ClientLogLevel.INFO > ClientLogLevel.DEBUG.

    Lower levels automatically enable higher ones. For example, setting the log level to WARNING means that all WARNINGs, ERRORs and FATAL log messages are logged, while INFO and DEBUG messages are not:

    javaFATAL > ERROR > WARNING > INFO > DEBUG

    Setting the log level to FATAL silences all other log levels:

    javaFATAL > ERROR > WARNING > INFO > DEBUG

    Enabling the DEBUG log level is equivalent to enabling ALL log levels:

    javaFATAL > ERROR > WARNING > INFO > DEBUG

Tip

> *  Enable WARNING or even DEBUG log levels during development
> *  Log only ERRORs and FATAL conditions in production mode, since (verbose) logging deteriorates system performance
> *  Alternatively, clients may want to add the ability to switch on verbose logging (WARNINGS, DEBUG, or INFO)
  • Retrieving Logs

    ClientLogManager provides APIs to retrieve the logs that have been produced by the app.

    Use iterateLogEntries to sequentially retrieve all logs with the specified and more critical level. Alternatively, use iterateLogEntriesForLogger(String loggerId, ClientLogLevel logLevel) to fetch logs for a given logger.

    Retrieve logs that are below a certain logLevel:

    javaIterator<ClientLogEntry> logs = logMan.iterateLogEntriesForLogger(ClientLogLevel.ERROR);

    Or use this code for a custom logger:

    javaIterator<ClientLogEntry> logs = logMan.iterateLogEntriesForLogger(”CustomLogger”, ClientLogLevel.ERROR);

    After getting the entries the user can read each ClientLogEntry. You can persist these entries by storing the Message and additional details, such as:

    Attribute Type
    Application String
    Date java.util.Date
    Location String
    Message String
    MessageType MessageType
    LogLevel ClientLogLevel
  • Client-side Log Persistence

    Since it is difficult to predict how many logs will be produced by an app, persisting them on the client is intentionally temporary. Logs are removed: After being successfully uploaded to the server or Once their expiation date is reached. By default log entries are purged after one week. * If the coded limit is reached: Logs are generated into various log files that are created as the logs are generated. If the sum of the logs reach a limit that can be modified by the API user, the oldest log file is deleted.

    The default settings for log file persistence are:

    • File age: 604800000 ms (7 days)
    • Max. file size: 102400 (100 KB)
    • Max. number of files: 10

    You can override these settings by adding the sap-supportability.properties file into your application’s assets folder with property values. For example:

    javafile_size=1000000file_count=10file_age=1209600000

  • Uploading Logs to the Server

    SAP Mobile Platform Server supports uploading of client log files. Access is controlled by the security configuration associated with the given application. Therefore, prior to uploading logs, the Server Administer must set the appropriate settings. See http://help.sap.com/saphelp_smp307svr/helpdata/en/e6/46aa8668a64efb94ec30e198a0b009/content.htm (or perform a Web search for “SMP” “Defining Client Log and Trace Policies”). Additionally, the application connection ID must be passed as a “X-SMP-APPCID” header field.

    The following code attempts to upload client logs to SAP Mobile Platform Server. You must supply a valid SAP Mobile Platform Server log upload URL in the form “http(s)://host:port/clientlogs”, and the client log policy must be configured to accept log uploads on the Management Cockpit. See http://help.sap.com/saphelp_smp307svr/helpdata/en/e6/46aa8668a64efb94ec30e198a0b009/content.htm for details.

    ```java HttpConversationManager convMan = new HttpConversationManager(this); IHttpConversation conv = convMan.create(logURL); // logURL is assembled beforehand conv.addHeader(HEADER_SMP_APPCID, ); // appcid or connection ID is coming from onboarding

    SupportabilityUploaderImpl uploader = new SupportabilityUploaderImpl(conv, this); logMan.uploadClientLogs(uploader, new UploadListener() { public void onUploadSuccess() {
    Log.i(LOG_TAG, "Log Upload Successful"); }

    public void onUploadFailure(UploadResult result) {
        Log.e(LOG_TAG, "Log Upload Failed: " + result.getResponseStatusCode() + ", " + result.getHint());
    }
    

    }); ```

    The above code uses the uploader provided by the HttpConversation library.

  • Viewing Logs on the Server

    Logs that are successfully uploaded to the server can be viewed and filtered to analyze and troubleshoot issues. See : http://help.sap.com/saphelp_smp307svr/helpdata/en/81/540a14ddb04e00a73ddaaa10c7260f/content.htm

Add Tracing to your Android Application

Add tracing to your native Android OData app, upload the BTX that contains all collected trace data to the server, and view the trace information.

End-to-End Tracing

The E2ETracing component collects end-to-end step and request trace data including performance measurements and user actions. SDK libraries are instrumented for E2ETrace enablement. Furthermore, the E2ETrace component exposes APIs which allows developers to perform various, E2E tracing related tasks on the client.

  • E2E Transactions, Steps and Requests

    To perform E2E tracing, start an end-to-end transaction. A transaction defines the boundaries of an E2E tracing session.

    ! Restriction Only one E2E transaction can be active at a time. Starting a new transaction while an active one is running causes the latter to terminate (including its active steps and requests).

    Within the context of an active E2E trace transaction one can start several E2E steps. Steps can be logically mapped to a given use case or business scenarios. For example, an E2E step might be assigned to the phase of presenting your main screen and populating it with data.

    Steps can in turn consist of one to many E2E requests. An E2E request is an atomic logical entity generally bound to one network request. An E2E request could be mapped, for example, a GET request for fetching data, or a POST request that updates an entity on the server.

    A Business Transaction XML is generated as a result of running an E2E trace session. This XML file contains E2E trace relevant step and request data in a standard format. The framework allows for uploading the generated BTX to the SAP Mobile Platform Server, where BTX files are archived for further analysis.

  • Basic E2E Tracing

    These steps enable basic E2E trace enablement of an app. Custom E2E tracing is described later.

    1. Instantiate the E2E trace manager instance:

      java//get the E2ETraceManager instanceE2ETraceManager traceMan = Supportability.getInstance().getE2ETraceManager(this);

      Start a transaction; which is mandatory because E2E steps and requests must start within the context of an E2E transaction. Only one E2E transaction can be active at a time.

      javaE2ETraceTransaction transaction = traceMan.startTransaction("MyTransaction"); The call to E2ETraceManager startTransaction creates and starts an E2E transaction. If there was an active transaction when calling the API, the old transaction ends and a new instance is created. You can query the active transaction (if any) using the E2ETraceManager getActiveTransaction API.

      javaE2ETraceTransaction actTransaction = traceMan.getActiveTransaction();

      An E2E transaction can have two states: Started or Ended.

      ! Remember If a transaction is ended, it cannot perform further E2E steps and requests.

    2. Start an E2E step in the context of the newly created transaction. To start a step, call E2ETransaction startStep API on a valid E2ETransaction instance. The transaction must be in status started in order to start new steps; if the transaction is ended, attempts to start new steps fail.

      javaE2ETraceStep step = transaction.startStep();

      You can also call the E2ETraceManager getActiveTransaction API to retrieve the active transaction, and start the step:

      javatraceMan.getActiveTransaction().startStep();

  • Close the active step before ending the E2E trace session. E2ETraceSteps can be ended by invoking their endStep method.

    javastep.endStep();

  • Invoke the E2ETraceManager endTransaction to close the E2E trace session.

    javatraceMan.getActiveTransaction().endTransaction();

    This call ends the active steps and their running requests. You can also call endTransaction on the transaction instance itself:

    javatransaction.endTransaction();

    ! Note Selected SDK components are instrumented specifically for E2E tracing. Which means that although the above code snippets did not trigger custom steps or requests, the SDK produces trace data. The BTX contains all collected trace data, including performance measurements, network related metric data like count of bytes sent or received, request / response headers, and so on.

  • Custom E2E Tracing

    Although basic E2E tracing is sufficient in most cases, some apps may need to generate custom E2E trace data, which the Supportability framework provides. In this case, along with starting and ending an E2E transaction and E2E steps, the developer must also manage requests. Create and start an E2E trace request from an active E2E transaction and an E2E step:

    java// create a request within the context of the current stepE2ETraceRequest traceRequest = null;E2ETrace e2eTrace = Supportability.getInstance().getE2ETrace();if (e2eTrace != null)traceRequest = e2eTrace.startRequest();

The E2ETraceRequest exposes APIs that allow setting properties required for E2E tracing:

```java //Should be called before data is sent. void markSending()

//Should be called as soon as the data was sent. void markSent()

//Should be called upon receiving first data bytes. void markReceiving()

//Should be called as soon as data was completely received. void markReceived()

//Sets the size of sent data in bytes.
void setByteCountSent(long)

//Sets the size of received data in bytes. void setByteCountReceived(long)

//Sets the HTTP request line void setRequestHeaders(Map) void setResponseHeaders(Map) void setRequestLine(String) ```

  1. For example, set up the E2E trace request when starting a network request:

    ```java
    

    traceRequest.setByteCountSent(byteSent); traceRequest.markSending(); traceRequest.markSent(); traceRequest.setRequestHeaders(requestHeaders); traceRequest.setRequestLine(requestLine); ```

  2. After the network request completes, the response is processed:

    ```java
    

    traceRequest.markReceiving(); traceRequest.markReceived(); traceRequest.setResponseHeaders(traceRespHeaders); traceRequest.setReturnCode(responseCode); traceRequest.setByteCountReceived(responseByteCount); ```

  3. Close the trace request:

    javatraceRequest.endRequest();

    Calling the E2ETraceRequest endRequest API causes the E2ETrace request to be marked as ended.

    Remember Further attempts to modify this request will fail.

  4. Client-Side BTX Persistence

    The end result of an E2E trace session is the Business Transaction XML (BTX), which is temporarily stored in the app’s file system when an upload is initiated. The BTX is automatically removed when one of the following conditions are met:

    • the BTX is successfully uploaded to the server, or
    • a new E2E trace session starts
  5. Uploading the BTX

    SAP Mobile Platform Server supports uploading E2E trace results ( BTX). Access is controlled by the security configuration associated with the given application. Therefore, prior to uploading the BTX, the Server Administrator must perform some administrative tasks. For detailed instructions on E2E trace and log related settings and configuration see http://help.sap.com/saphelp_smp307svr/helpdata/en/e6/46aa8668a64efb94ec30e198a0b009/content.htm (or perform a Web search for for “SMP” “Defining Client Log and Trace Policies”). In addition, the application connection ID must be passed as a “X-SMP-APPCID” header field.

    The following code attempts to upload the BTX to the SAP Mobile Platform Server. You must supply a valid SAP Mobile Platform Server log upload URL in the form “http(s)://host:port/btx”, and application E2E tracing must be enabled in Management Cockpit. See http://help.sap.com/saphelp_smp307svr/helpdata/en/e6/46aa8668a64efb94ec30e198a0b009/content.htm for details.

    ```java HttpConversationManager convMan = new HttpConversationManager(this); IHttpConversation conv = convMan.create(traceURL); conv.addHeader("X-SMP-APPCID", appCId); SupportabilityUploaderImpl uploader = new SupportabilityUploaderImpl(conv, this); try { traceMan.uploadBTX(uploader, new UploadListener() { public void onUploadSuccess() { Log.i(LOG_TAG, "BTX Upload Successful"); }

        public void onUploadFailure(UploadResult result) {
            Log.e(LOG_TAG, "BTX Upload Failed: " + result.getResponseStatusCode() + ", " + result.getHint());
        }
    });
    

    } catch (E2ETraceException e) { Log.e(LOG_TAG, "BTX Upload Failed: " + e.getMessage()); } ```

Normally the E2E trace closes once the BTX is uploaded; however, if this does not happen, the framework performs the necessary cleanup when calling the upload API.

! Remember Invoking the upload API closes the active E2E trace session; any pending E2E transactions, steps, or requests will be ended.

  • E2E Trace Implications

Enabling E2E tracing is useful to track the functionality of apps; however, it does come at a cost which affects performance and memory usage. When E2E tracing is on, additional housekeeping is done by the various SDK components to insert the required values in the generated BTX. During the E2E session, the BTX document is managed in memory, and only gets persisted to disk if uploading it to the server fails. Additionally, E2E tracing automatically switches all loggers to DEBUG mode, meaning that logs become more verbose compared to the default ERROR mode.

! Remember When the E2ETrace session is closed, loggers automatically revert to their normal settings.

Use application E2E tracing only if it is required.

  • Examples

The Supportability framework includes an extensive set of unit tests that cover many use-cases. Additionally, every public API is documented, and includes usage examples for the less obvious use-cases.