65

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

hopia
  • 4,880
  • 7
  • 32
  • 54

3 Answers3

113

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 
Nolan Hergert
  • 141
  • 1
  • 14
Ryan Reeves
  • 10,209
  • 3
  • 42
  • 26
  • 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. – Mixaz Nov 25 '13 at 06:02
  • Just in case if this doesn't work, see below solution. – Sandeep Mar 31 '14 at 09:25
  • 9
    or __android_log_print(ANDROID_LOG_INFO, "Tag", "i%c works lik%x print%x", 't', 14, 15); – bartolo-otrit Oct 11 '14 at 15:41
13

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
Sandeep
  • 18,356
  • 16
  • 68
  • 108
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.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985