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

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


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 


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 wayLOCAL_LDLIBS := -llog

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

#2. LOCAL_LDFLAGS wayLOCAL_LDFLAGS := -llog#3. LOCAL_SHARED_LIBRARIES wayLOCAL_SHARED_LIBRARIES += liblog


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 JNICALLJava_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.