Logging with Android
This tutorial describes how to create log statements in Android applications.
Table of Contents
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.
You can open this view via
→ → → → .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.
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");
}
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.
No comments:
Post a Comment