Android Essentials: Application Logging

Android Essentials: Application Logging

Tutorial Details
  • Technology: Android SDK
  • Difficulty: Beginner
  • Estimated Completion Time: 15-20 Minutes
This entry is part 4 of 14 in the series Android Essentials

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.

Eclipse / Android SDK / LogCat Log Output

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.

A LogCat Log Filter for My Tag

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.

Need More Help Writing Android Apps? Check out our Latest Books and Resources!

Buy Android Wireless Application Development, 2nd Edition  Buy Sam's Teach Yourself Android Application Development in 24 Hours  Mamlambo code at Code Canyon

Series Navigation«Android Essentials: Application PreferencesAndroid Essentials: ListView Item State Management: A “Read Item” Flag»

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.jsxtech.com Jaspal Singh

    Great! sure will give a try to android application logging.
    Thanks for sharing.

  • Steve Dobson

    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! :-)

    • http://www.facebook.com/brent.parsons.710 Brent Parsons

      My solution to this problem was to create my own public class Log(). I essentially duplicated the methods but also add in a Global DEBUG boolean that is set in LSApplication. So when a class calls to my Log() class,I check to see if logging is enabled. When logging is enabled, the call simply gets passed up to the android.util.Log class as you normally would.

      For instance:


      public class Log {
      public static int d(java.lang.String tag, java.lang.String msg) {
      if (LSApplication.DEBUG)
      {
      return android.util.Log.d(tag, msg);
      } else return 0;
      }
      .... (and so on)

      }

      As long as (DEBUG == TRUE), logs will be outputted. This could be simply extended just a little further to also handle showing Logs by severity, if you wanted a little more granularity.

  • Steve Dobson

    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.

  • Tommy

    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)

  • android developer

    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(…);
    }

  • Rolf Kulemann

    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”);
    }
    }
    }

  • http://shareprogrammingtips.com jigar patel

    instead 0f defining TAG separately in every class

    you can just do \

    Log.i(“myApp”, “I am logging something informational!”);

    • Fred .

      It is best to define a TAG as you will likely log in more than one place, then you re-use the same tag then it gets easier to find the messages by filtering the logs by the tag.

  • Fazileh

    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.

    • Fazileh

      Hi again,
      My problem solved… I had a little mistake. :-)

      • Fluckysan

        I can’t see my log from jar files
        Could you tell me how you solved this (please mail me) ?