Logging

As we have seen in many listings already, you can use the Log class to print out messages to LogCat. In addition to the Java traditional logging mechanism such as System.out.println(), Android defines six log levels, each having its own methods:

  • verbose (Log.v)
  • debug (Log.d)
  • info (Log.i)
  • warning (Log.w)
  • error (Log.e)
  • assert (Log.wtf)

For example, a call to Log.v(TAG, “my message”) is equivalent to a call to Log.println(Log.VERBOSE, TAG, “my message”).

NOTE: The Log.wtf() methods were introduced in API level 8, but Log.ASSERT exists since API level 1. If you want to use the ASSERT log level but want to guarantee compatibility with older Android devices, use Log.println(Log.ASSERT, …) instead of Log.wtf(…).

You can then use LogCat in Eclipse (Window Image Show View Image LogCat) and/or in a terminal (adb logcat, or simply logcat from an adb shell) and see the messages generated while your application runs.

Since many messages may be displayed, many of them not coming from your application, you may want to create filters so you can focus on the output that is relevant to you. You can filter messages based on their tags, priority levels, and PIDs. In Eclipse, you can use the Create Filter feature, as shown in Figure 6–6.

Image

Figure 6–6. Creating LogCat filter with Eclipse

Eclipse currently does not support creating a filter on multiple tags, so you will have to use adb logcat instead if you want to do that. For example, to show only log messages with the tag “MyTag” at priority “Debug” or above (that is, Debug, Info, Warning, Error, and Assert), and log messages with the tag “MyOtherTag” at priority “Warning” or above, you can type:

adb logcat MyTag:D MyOtherTag:W *:S

Make sure you don't forget the *:S part since it means all other log messages will be filtered out. (S is for Silent.)

Logging functions are also available in the NDK, so you can use LogCat as well to log messages from your C/C++ code. Functions are defined in the NDK's android/log.h:

  • __android_log_write
  • __android_log_print
  • __android_log_vprint
  • __android_log_assert

For example, the equivalent of Log.i(“MyTag”, “Hello”) would be __android_log_write(ANDROID_LOG_INFO, “MyTag”, “Hello”).

Because these are Android-specific routines and because their use makes your code a little too wordy, it is recommended you create a wrapper around these functions. As a matter of fact, this is exactly what the Android source code does in the cutils/log.h file by creating macros such as LOGI and LOGE, the equivalent of Log.i and Log.e, respectively. You should design your wrapper so you can easily use it in non-Android code as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.63.231