Thursday, October 24, 2013

Android Logging Tutorial

Logging with Android
This tutorial describes how to create log statements in Android applications.

1. Logging in Android

The Android system uses a centralize logging for all logs. The application programmer can also write log messages. The tooling to develop Android applications allows you to define filters for the log statements you are interested in.

2. Viewing log messages with the LogCat view

You can see the Android log statements via the LogCat view .
You can open this view via Window → Show View → Other... → Android → LogCat.
Showing the LogCat view
The LogCat view allows you also to define a filter for the log messages, e.g. for your category. Press the+ sign to create a new filter.

3. Create log statements

To write log statements you use the android.util.Log class with the Log.i()Log.d(),Log.w()Log.e() or Log.wtf() method. A log statement written with Log.i() is the least important and so on.
The first parameter of these method is the category and the second is the message.
Typically you create a Constants interface in your Android application and provide your log flag as a field.
package com.vogella.android.first;

public interface Constants {
String LOG = "com.vogella.android.first";
}
Android advises that a deployed application should not contain logging code. The Android development tools provide the BuildConfig.DEBUG flag for this purpose. This flag will be automatically set tofalse, if you export the Android application for deployment. During development it will be set totrue, therefore allow you to see your logging statements during development.
The following example show how to write an error log message. This message is visible in the LogCatview in Eclipse.
if (BuildConfig.DEBUG) {
Log.e(Constants.TAG, "onCreate called");
}

4. Exercise: Using log statements and the LogCat view

In your com.vogella.android.first project create the following interface to define a constant for your log statements.
package com.vogella.android.first;

public interface Constants {
String LOG = "com.vogella.android.first";
}
Add a log statement to your onCreate method.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if (BuildConfig.DEBUG) {
Log.d(Constants.LOG, "onCreated called");
}
setContentView(R.layout.activity_main);
}
Run your application and check that you see your log statement in the LogCat view.

5. Exercise: Create filter in LogCat

Create a new filter in the view to see only logs based on your category.

No comments:

Post a Comment