Logging in Android

In Android we are able to log info by using the static methods provided by the final class Log. This class is part of the android.util package.

Available methods

Log class - android fundamentals

Method signature

loge - android fundamentals

If we log the next messages, the result from Logcat is present in the picture below.

public class LogSampleActivity extends AppCompatActivity {
private static final String TAG = "LogSampleActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lifecycle_test);
Log.e(TAG, "onCreate");
Log.w(TAG, "onCreate");
Log.i(TAG, "onCreate");
Log.v(TAG, "onCreate");
Log.d(TAG, "onCreate");
Log.wtf(TAG, "onCreate");
}
}

In Android Studio > Settings > search Android Logcat and from there we are able to customise the color of the logged messages from Logcat.

When and what to log?

It is recommended to create different build flavors depending on the available server environments. For example you could have a dedicated flavor for dev, qa, pre-prod, prod. Based on this classification also the logging strategy is changed.

On the test environments is ok to log many details in order to make sure everything is working properly. On the production environment it is recommended to log only the most relevant info in order to not affect the performance. Also you should take care not to log sensitive data like emails, phone numbers, personal ids and so on.

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
}
}
view raw build.gradle hosted with ❤ by GitHub

public class Logging {
public static void show(Object obj, String message) {
if (BuildConfig.DEBUG) {
Log.e(obj.getClass().getName(), message);
}
}
}
view raw Logging.java hosted with ❤ by GitHub

If you want to learn more about logging you could check a dedicated episode on the Fragmented Podcast.


Enjoy and feel free to leave a comment if something is not clear or if you have questions. And if you like it please share !

Thank you for reading! 🙌🙏😍✌

Follow me on: Twitter Medium | Dev.to

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s