Android Log Collection
Datadog の調査レポート: サーバーレスの状態 レポート: サーバーレスの状態

Android Log Collection

このページは英語では対応しておりません。随時翻訳に取り組んでいます。翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください。

Send logs to Datadog from your Android applications with Datadog’s dd-sdk-android client-side logging library and leverage the following features:

  • Log to Datadog in JSON format natively.
  • Add context and extra custom attributes to each log sent.
  • Forward Java/Kotlin caught exceptions.
  • Record real client IP addresses and User-Agents.
  • Optimized network usage with automatic bulk posts.

Note: The dd-sdk-android library supports all Android versions from API level 19 (KitKat).

Setup

  1. Add the Gradle dependency by declaring the library as a dependency in your build.gradle file:

    repositories {
        maven { url "https://dl.bintray.com/datadog/datadog-maven" }
    }
    
    dependencies {
        implementation "com.datadoghq:dd-sdk-android:x.x.x"
    }
  2. Initialize the library with your application context and your Datadog client token. For security reasons, you must use a client token: you cannot use Datadog API keys to configure the dd-sdk-android library as they would be exposed client-side in the Android application APK byte code. For more information about setting up a client token, see the client token documentation:

    class SampleApplication : Application() {
        override fun onCreate() {
            super.onCreate()
    
            val config = DatadogConfig.Builder(BuildConfig.DD_CLIENT_TOKEN)
                            .setServiceName("<SERVICE_NAME>")
                            .build()
            Datadog.initialize(this, config)
        }
    }
    class SampleApplication : Application() {
        override fun onCreate() {
            super.onCreate()
    
            val config = DatadogConfig.Builder(BuildConfig.DD_CLIENT_TOKEN)
                            .setServiceName("<SERVICE_NAME>")
                            .useEUEndpoints()
                            .build()
            Datadog.initialize(this, config)
        }
    }

    There is also a utility method which gives you the current state of the SDK. You can use this to check if it was properly initialized or not:

        if(Datadog.isInitialized()){
          // your code here
        }

    When writing your application, you can enable development logs. All internal messages in the library with a priority equal or higher than the provided level are then logged to Android’s Logcat.

        Datadog.setVerbosity(Log.INFO)
  3. Configure the Android Logger:

    val logger = Logger.Builder()
        .setNetworkInfoEnabled(true)
        .setLogcatLogsEnabled(true)
        .setDatadogLogsEnabled(true)
        .setBundleWithTraceEnabled(true)
        .setLoggerName("<LOGGER_NAME>")
        .build();
  4. Send a custom log entry directly to Datadog with one of the following functions:

    logger.d("A debug message.")
    logger.i("Some relevant information ?")
    logger.w("An important warning…")
    logger.e("An error was met!")
    logger.wtf("What a Terrible Failure!")

    Exceptions caught can be sent with a message:

    try {
        doSomething()
    } catch (e : IOException) {
        logger.e("Error while doing something", e)
    }

    Note: All logging methods can have a throwable attached to them.

  5. (Optional) - Provide a map alongside your log message to add attributes to the emitted log. Each entry of the map is added as an attribute.

    logger.i("onPageStarted", attributes = mapOf("http.url", url))

    In Java you would have:

    Logger.d(
            "onPageStarted",
            null,
            new HashMap<String, Object>() {{
                put("http.url", url);
            }}
    );

Advanced logging

Initialization

The following methods in Logger.Builder can be used when initializing the logger to send logs to Datadog:

MethodDescription
setNetworkInfoEnabled(true)Add the network.client.connectivity attribute to all logs. The data logged by default is connectivity (Wifi, 3G, 4G…) and carrier_name (AT&T - US). carrier_name is only available for Android API level 28+.
setServiceName(<SERVICE_NAME>)Set <SERVICE_NAME> as value for the service standard attribute attached to all logs sent to Datadog.
setLogcatLogsEnabled(true)Set to true to use Logcat as a logger.
setDatadogLogsEnabled(true)Set to true to send logs to Datadog.
setBundleWithTraceEnabled(true)Set to true (default) to bundle the logs with the active trace in your application. This parameter shows all the logs sent during a specific trace by using the Datadog dashboard.
setLoggerName(<LOGGER_NAME>)Set <LOGGER_NAME> as the value for the logger.name attribute attached to all logs sent to Datadog.
setVerbosity(Log.INFO)Set the verbosity of the logger. All internal messages in the library with a priority equal to or higher than the provided level are logged to Android’s Logcat.
setSampleRate(<SAMPLE_RATE>)Set the sampling rate for this logger. All the logs produced by the logger instance are randomly sampled according to the provided sample rate (default 1.0 = all logs). Note: The Logcat logs are not sampled.
build()Build a new logger instance with all options set.

Global configuration

Find below functions to add/remove tags and attributes to all logs sent by a given logger.

Global Tags

Add Tags

Use the addTag("<TAG_KEY>","<TAG_VALUE>") function to add tags to all logs sent by a specific logger:

// This adds a tag "build_type:debug" or "build_type:release" accordingly
logger.addTag("build_type", BuildConfig.BUILD_TYPE)

// This adds a tag "device:android"
logger.addTag("device", "android")

Note: <TAG_VALUE> must be a String.

Remove Tags

Use the removeTagsWithKey("<TAG_KEY>") function to remove tags from all logs sent by a specific logger:

// This removes any tag starting with "build_type"
logger.removeTagsWithKey("build_type")

Learn more about Datadog tags.

Global Attributes

Add attributes

By default, the following attributes are added to all logs sent by a logger:

  • http.useragent and its extracted device and OS properties
  • network.client.ip and its extracted geographical properties (country, city)

Use the addAttribute("<ATTRIBUTE_KEY>", "<ATTRIBUTE_VALUE>") function to add a custom attribute to all logs sent by a specific logger:

// This adds an attribute "version_code" with an integer value
logger.addAttribute("version_code", BuildConfig.VERSION_CODE)

// This adds an attribute "version_name" with a String value
logger.addAttribute("version_name", BuildConfig.VERSION_NAME)

Note: <ATTRIBUTE_VALUE> can be any primitive, String, or Date.

Remove attributes

Use the removeAttribute("<ATTRIBUTE_KEY>", "<ATTRIBUTE_VALUE>") function to remove a custom attribute from all logs sent by a specific logger:

// This removes the attribute "version_code" from all further log send.
logger.removeAttribute("version_code")

// This removes the attribute "version_name" from all further log send.
logger.removeAttribute("version_name")

Further Reading

お役に立つドキュメント、リンクや記事: