Tutorial Details
- Technology: Android SDK
- Difficulty: Beginner
- Estimated Completion Time: 15-20 Minutes
- Android Essentials: Creating Simple User Forms
- Android Essentials: Using the Contact Picker
- Android Essentials: Application Preferences
- Android Essentials: Application Logging
- Android Essentials: ListView Item State Management: A “Read Item” Flag
- Android Essentials: Enhancing Your Applications with App Widgets
- Android Tools: Leveraging the Hierarchy Viewer for UI Profiling
- Android Essentials: Working with Strings and String Arrays
- Android Essentials: Making Sense of Android Versioning
- Android Essentials: Adding Events to the User’s Calendar
- Android Essentials: Create a Mirror
- Android Essentials: Submitting Your Application to the Android Market
- Android Essentials: Publishing to Specific Devices
- Android Essentials: Creating Android-Compliant Libraries
- Android Essentials: Adding JAR Files to Android Projects
In this quick tip tutorial, you’ll learn how to use application logging support in your Android applications for diagnostic purposes.
This quick tip shows you the steps to incorporate logging support into your applications and then use the LogCat logging utility to monitor your application’s log output, either on the emulator or a device that is attached to Eclipse via the debugger. This skill is invaluable for debugging issues, even when great debuggers are available for stepping through code.
Step 1: Create an Android Application
Begin by creating an Android project. Implement your Android application as normal. Once you’ve setup your Android project, you are ready to proceed with this quick tip.
Step 2: Logging Options for Android Applications
The Android SDK includes a useful logging utility class called android.util.Log. Logging messages are categorized by severity (and verbosity), with errors being the most severe, then warnings, informational messages, debug messages and verbose messages being the least severe. Each type of logging message has its own method. Simply call the method and a log message is created. The message types, and their related method calls are:
- The Log.e() method is used to log errors.
- The Log.w() method is used to log warnings.
- The Log.i() method is used to log informational messages.
- The Log.d() method is used to log debug messages.
- The Log.v() method is used to log verbose messages.
- The Log.wtf() method is used to log terrible failures that should never happen. (“WTF” stands for “What a Terrible Failure!” of course.)
The first parameter of each Log method is a string called a tag. It’s common practice to define a global static string to represent the overall application or the specific activity within the application such that log filters can be created to limit the log output to specific data. For example, you could define a string called TAG, as follows:
private static final String TAG = "MyApp";
You will often find that the tag is defined as the class in which the Log statement occurs. This is a reasonable convention, but anything identifiable or useful to you will do.
Now anytime you use a Log method, you supply this tag. An informational logging message might look like this:
Log.i(TAG, "I am logging something informational!");
You can also pass a Throwable object, usually on Exception, that will allow the Log to print a stack trace or other useful information.
try {
// ...
} catch (Exception exception) {
Log.e(TAG, "Received an exception", exception);
}
NOTE: Calling the Log.wtf() method will always print a stack trace and may cause the process to end with an error message. It is really intended only for extreme errors. For standard logging of exceptions, we recommend using the Log.e() method. The Log.wtf() method is available only in Android 2.2 or later. The rest are available in all versions of Android.
Step 3: Adding Log Support to an Activity Class
Now let’s add some logging to your Activity class. First, add the appropriate import statement for the logging class android.util.Log. Next, declare a logging tag for use within your class (or whole application); in this case, we call this variable DEBUG_TAG. Finally, add logging method calls wherever you want logging output. For example, you might add an informational log message within the onCreate() method of your Activity class.
Below is some sample code that illustrates how all these steps come together:
package com.mamlambo.simpleapp;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MySimpleAppActivity extends Activity {
private static final String DEBUG_TAG= "MySimpleAppLogging";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(DEBUG_TAG, "Info about MySimpleAppActivity.");
}
}
Step 4: Monitoring Application Log Output – The Easy Way
You can use the LogCat utility from within Eclipse to view the log output from an emulator or device. LogCat is integrated into Eclipse using the Android Development plug-in. You’ll find the LogCat panel integrated into the DDMS and Debug perspectives of Eclipse.
Step 5:Monitoring Application Log Output – Creating Log Filters
As you can see, the basic LogCat logging output includes log data from lots of different sources. For debugging purposes, it can be useful to filter the output to only the tags for your specific application. This way, you can focus on your application log output, amidst all the clutter.
You can use the LogCat utility from within Eclipse to filter your log messages to the tag string you supplied for your application. To add a new filter, click the green plus sign button in the LogCat pane of Eclipse. Name the filter—perhaps using the tag name—and fill in the tag you want to filter on. A new tab is created in LogCat that will show only log messages that contain this tag. You can create filters that display items by severity level.
Performance Considerations with Logging
Logging output puts a damper on application performance. Excessive use can result in decreased application performance. At minimum, debug and verbose logging should be used only for development purposes and removed before release. It’s also a good idea to review other logging output before publication as well.
Conclusion
Logging is a very handy debugging and diagnostic technique used by developers. Use the logging class provided as part of the Android SDK to log important information about your application to LogCat, but make sure you review your application’s logging implementation prior to publication, as logging has performance drawbacks.
About the Authors
Mobile developers Lauren Darcey and Shane Conder have coauthored several books on Android development: an in-depth programming book entitled Android Wireless Application Development and Sams TeachYourself Android Application Development in 24 Hours. When not writing, they spend their time developing mobile software at their company and providing consulting services. They can be reached at via email to androidwirelessdev+mt@gmail.com, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.




Great! sure will give a try to android application logging.
Thanks for sharing.
As the documentation recommends before calling one of the logging functions one should first check that logging is enabled for that tag and level:
if (Log.isLoggable(DEBUG_TAG, Log.DEBUG))
Log.i(DEBUG_TAG, “Info about MySimpleAppActivity.”);
Then there is no need to remove your logging calls. After all, Sod’s Law demands that the removal of logging code introduces bugs! :-)
Sorry the code should have read:
if (Log.isLoggable(DEBUG_TAG, Log.INFO))
Log.i(DEBUG_TAG, “Info about MySimpleAppActivity.”);
I didn’t notice you were using and info logging call to report debug information.
Good info, but where do we enter this code? I’ve been reading your teach-yourself book which this article is referenced from. The first two chapters are great, but things start to get lost after that. The first two chapters had great explainations of the topic with good examples and descriptions on how to use it. After that, the examples disappeared so it’s hard to make use of the good information given for someone trying to learn (especially when you don’t tell us where to enter the code). It would also be great to have a crash course or brief explaination on the format or syntax of the code to help make sense of why we’re writing it as such. As a total beginner, I chose your book after reading the “Who Should Read This Book” section. The book looks promising, but if you could keep the methodology from the first two chapters, it would be great. (start off with building a simple app with explainations of the code and how to use it, then start adding more complex functionality that demostrates the topic you are covering)
you can disable logging of your entire application by using the proguard.cfg file when you export your app to apk. just add those lines there:
-assumenosideeffects class android.util.Log {
public static int v(…);
public static int d(…);
public static int e(…);
public static int w(…);
public static int i(…);
}
If logging to a log file is alos required, it is maybe more convenient to use a generic logging api such as slf4j and configure it using android-logging-log4j.
A small example showing logging inAndroid using slf4j and log4j
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.log4j.Level;
import android.os.Environment;
import de.mindpipe.android.logging.log4j.LogConfigurator;
public class ExampleLog4JOverSLF4J {
private final Logger log = LoggerFactory.getLogger(ExampleLog4JOverSLF4J.class);
static {
final LogConfigurator logConfigurator = new LogConfigurator();
logConfigurator.setFileName(Environment.getExternalStorageDirectory() + “myapp.log”);
logConfigurator.setRootLevel(Level.DEBUG);
// Set log level of a specific logger
logConfigurator.setLevel(“org.apache”, Level.ERROR);
logConfigurator.configure();
}
public void myMethod() {
if(log.isInfoEnabled())
log.info(“This message should be seen in log file and logcat”);
}
}
}
instead 0f defining TAG separately in every class
you can just do \
Log.i(“myApp”, “I am logging something informational!”);
Hi,
Thank you for great article.
I have a library that there are some Logs in it. I add this jar library to my android project correctly.
My project run without any error. But I can not view my logs in jar library from LogCat window.
Is any way for watching logs from jar library?
Thanks in advanced.
Hi again,
My problem solved… I had a little mistake. :-)