Logging values of variables in Android native ndk

AndroidC++DebuggingLoggingAndroid Ndk

Android Problem Overview


I set up logging with C++ in Android NDK.

I can print a message to logcat like this:

__android_log_write(ANDROID_LOG_INFO, "tag here", "message here");

Now let's say I have an integer called testint. How can I print the value of this int?

Something like this prints the address, but I want the value. I haven't found anything in C++ on how to do this. Thanks for any help!

__android_log_print(ANDROID_LOG_INFO, "sometag", "%p", *test);

Android Solutions


Solution 1 - Android

Here's the most concise way I've seen:

#include <android/log.h>

#define  LOG_TAG    "someTag"

#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#define  LOGW(...)  __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__)
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)

...

// Now you can log very simply like this:
int foo = 42;
LOGD( "This is a number from JNI: %d", foo );

Also, make sure you link to the log library in your Android.mk:

LOCAL_LDLIBS    := -llog

Solution 2 - Android

You could use __android_log_print which uses a sprintf-like syntax that formats your data into a string.

__android_log_print(ANDROID_LOG_INFO, "sometag", "test int = %d", testInt);

Solution 3 - Android

Take advantage of the variadic log print function you have available. For my own code, I provide a LogInfo() function to make it simple. Of course there are several options available to you here.

void LogInfo(const char *sTag, const char *fmt, ...)
{
  va_list ap;
  va_start(ap, fmt);
  __android_log_vprint(ANDROID_LOG_INFO, sTag, fmt, ap);
  va_end(ap);
}

Solution 4 - Android

__android_log_print() takes a format string and a variable argument list. The format specifier you're looking for to print out a signed integer is "%d". So something like this is what you want:

int foo = 42;
__android_log_print(ANDROID_LOG_INFO, "SomeTag", "foo is %d", foo);

For more information on format strings, you can see the sprintf manual.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondorienView Question on Stackoverflow
Solution 1 - AndroidAdamView Answer on Stackoverflow
Solution 2 - AndroidBenoit DuffezView Answer on Stackoverflow
Solution 3 - AndroidmahView Answer on Stackoverflow
Solution 4 - AndroidkelnosView Answer on Stackoverflow