Android System offers to developers a centralized system to manage all logs. Each developer can write custom log messages in his application that will be visible in the centralized system. Each log message has an associated tag and a priority constant. Thus, you can filter log statements from the centralized logs system easily.

API for sending logs in Android is based on the class android.util.Log . This class offers you the following static methods :

  • Log.v() for a VERBOSE priority log message
  • Log.d() for a DEBUG priority log message
  • Log.i() for an INFO priority log message
  • Log.w() for a WARN priority log message
  • Log.e() for an ERROR priority log message
  • Log.wtf() for a What a Terrible Failure message. A condition that should never happen

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG then VERBOSE. Be aware that Verbose priority should never be compiled into an application except during development phase. Debug logs are compiled in but stripped at runtime. Error, Warning and Info logs are always kept at runtime.

1/ Write a log statement

Best practice when you can to write a log statement is to define a TAG constant to filter easily these logs later :


public static final String TAG = "MyFirstTag";

Then, you can write your log message with your desired priority like that :


Log.v(TAG, "My first log message");

 

2/ Viewing a log statement

To view system logs from a device, you must use the logcat tool provided by the Android SDK. Most used IDE like Android Studio or Eclipse ADT offers you dedicated views. You can then filter by tag or package for example.

logcat_screenshot

 

3/ Remove logs for an application in production

For an application in production, you mustn’t have any log statements. To enable your logs statements calls only during development phase, Android offers you the BuildConfig.DEBUG property. This flag is setted automatically to false when an application if deployed into an APK for production and then, it’s setted to true during development.

To use it, you must write your log statements like that :


if (BuildConfig.DEBUG) {
   Log.d(TAG, "My message only available on development");
}