manski's blog

Logging from C/C++ on Android (instead of debugging)

With the Android NDK Google lets us write C/C++ code for Android. I don’t like writing C/C++ code because it’s error-prone but sometimes there’s no other way.

Unfortunately (this is the “I don’t like this” part), debugging Android C/C++ code is terribly difficult. If you don’t have a week to get the debugging toolchain working, and if you only need some quick and temporary solution, logging may be an alternative.

The easiest form of logging I can think of is using printf(). Unfortunately, I couldn’t get this working.

Fortunately, the Android NDK provides a logging API for C/C++. Here’s an example:

#include <android/log.h>

#define  LOG_TAG    "testjni"
#define  ALOG(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)

void myMethod() {
  ALOG("This message comes from C at line %d.", __LINE__);
}

ALOG works like printf(), so you can add parameters to the log message. The log message is routed to Android’s logcat and has log level “info” (due to ANDROID_LOG_INFO). The log tag (LOG_TAG) can be chosen freely.

The last thing you need to do is adding the logging library to your Android.mk makefile:

include $(CLEAR_VARS)
...
LOCAL_LDLIBS  := -llog
...
include $(BUILD_SHARED_LIBRARY)

6 comments

  1. Dorien said: ∞

    Great tip. How come it’s not the first thing you read

  2. Dorien said: ∞

    Quick question though. How do I log an integer value. I tried

    int myint = 5;
    ALOG(myint + “This message comes from C++ at line “, __LINE__);

    But doesn’t seem to work. any idea?

    • Manski (post author) replied: ∞

      This doesn’t work in C++. I’m not C guru but I faintly remember a function called “sprintf()” doing this stuff.

    • Rene Lindsay replied: ∞

      Use %d to insert the integer value into the string (just like printf):

      ALOG(“%d This message comes from C++ at line %d“,__LINE__);

  3. Joe said: ∞

    Can you tell me the location of Android.mk file ?

  4. Albert Tra said: ∞

    Your post save my life

Leave a Reply

Your email address will not be published. Required fields are marked *