Any simple way to log in Android NDK code?
Solution 1:
You can use the Android logging facilities:
#include <android/log.h>
#define APPNAME "MyApp"
__android_log_print(ANDROID_LOG_VERBOSE, APPNAME, "The value of 1 + 1 is %d", 1+1);
Make sure you also link against the logging library, in your Android.mk file:
LOCAL_LDLIBS := -llog
Solution 2:
No one has posted info about different log levels so far. The answer is an attempt to make the logging "picture" full.
#include <android/log.h>
#define TAG "MY_TAG"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
Usage:
char err[] = "wrong";
LOGE("Something went %s", err);
Link Android log library as below.
Android.mk:
LOCAL_LDLIBS := -llog
CMakeLists.txt:
find_library( log-lib log )
target_link_libraries( ${log-lib} )
Further reading: Logging
Solution 3:
The easiest way is probably to redirect printf() statements to the system log (based on the "Viewing stdout and stderr" section of the official ADB reference manual.
Type these 3 commands on a command line:
adb shell stop
adb shell setprop log.redirect-stdio true
adb shell start
Then you can view the output of your "printf()" statements by looking at the "LogCat" window of Eclipse Debugger, or by typing this on a command line:
adb logcat
Just be aware that since the data is buffered before transferring from the emulator or device, you should definitely flush the stdout buffer, eg:
printf("Hello, I am %d years old!\n", 30);
fflush(stdout);
You should then see a log message starting with "I/stdout:"