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

3

67

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

Buckwheat answered 28/3, 2011 at 22:49 Comment(0)
T
114

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 
Thunder answered 28/3, 2011 at 23:1 Comment(3)
"-L$(SYSROOT)/usr/lib" part is not necessary, just "LOCAL_LDLIBS := -llog" will work the same. For those it doesn't work anyway (like me)) - I had line "include $(CLEAR_VARS)" in my Android.mk after "LOCAL_LDLIBS := -llog", moved it before, and it works OK now.Religionism
Just in case if this doesn't work, see below solution.Spondee
or __android_log_print(ANDROID_LOG_INFO, "Tag", "i%c works lik%x print%x", 't', 14, 15);Ambience
S
14

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
Spondee answered 31/3, 2014 at 9:21 Comment(0)
R
11

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.

Rotogravure answered 6/11, 2017 at 9:45 Comment(1)
it only supports literalsNatant

© 2022 - 2024 — McMap. All rights reserved.