What is the Log API to call from an Android JNI program?

AndroidCAndroid EmulatorAndroid Ndk

Android Problem Overview


I would like to debug a JNI C application by inserting log messages to logcat. What is the C API that does this?

Android Solutions


Solution 1 - Android

Like this:

#include <android/log.h>


__android_log_write(ANDROID_LOG_ERROR, "Tag", "Error here");//Or ANDROID_LOG_INFO, ...	

Add it to your makefile like this:

LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog 

Solution 2 - Android

Following is the code snippet that you should include in your native code.

#include <android/log.h>


__android_log_write(ANDROID_LOG_ERROR, "Tag", "Error msg");//Or ANDROID_LOG_INFO, ...  

In order to use the above API, we need to link the corresponding library.

We can link a shared library in Android in 3 ways. In below 3 cases, the lines mentioned should be added in Android.mk

So here are the three ways.

#1. LOCAL_LDLIBS way
LOCAL_LDLIBS := -llog

For some reason if 1 doesnt work(it did not work for me), You can try below 2 ways

#2. LOCAL_LDFLAGS way
LOCAL_LDFLAGS := -llog

#3. LOCAL_SHARED_LIBRARIES way
LOCAL_SHARED_LIBRARIES += liblog

Solution 3 - Android

syslog

This POSIX function also outputs to logcat.

It has the advantage of being more portable across non Android systems than __android_log_write and it automatically adds the app package to the log.

Tested with this example app: https://github.com/cirosantilli/android-cheat/tree/a080f5c370c1f06e74a8300fb4a2e93369861047/gradle/NdkSyslog the NDK source is:

#include <jni.h>
#include <string>
#include <syslog.h>
    
extern "C"
JNIEXPORT jstring JNICALL
Java_com_cirosantilli_android_1cheat_ndksyslog_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    syslog(LOG_CRIT, "hello syslog");
    return env->NewStringUTF("Check adb logcat");
}

And logcat now contains:

01-14 15:39:07.582  3633  3633 E com.cirosantilli.android_cheat.ndksyslog: hello syslog  

Tested on Android O, HiKey 960.

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
QuestionhopiaView Question on Stackoverflow
Solution 1 - AndroidRyan ReevesView Answer on Stackoverflow
Solution 2 - AndroidSandeepView Answer on Stackoverflow
Solution 3 - AndroidCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow