How to turn on/off native log cat in ndk at runtime

android, android-ndk, c++

Solution

macro file

extern bool useDebug;
#include <android/log.h>
#define  LOG_TAG    "native_log"
#define  LOGD(...)  if(useDebug){__android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)}

C file

bool useDebug = true;
JNIEXPORT void JNICALL Java_com_my_package_Native_nativeSetDebug(JNIEnv *env, jobject thiz, jboolean flag){
    useDebug = flag;

}

The extern is important, otherwise each file including the header will define its own variable and they won't be set correctly.

Problem

I use this snippet code to turn log on or off ``` #define DEBUG 1 #if DEBUG #include <android/log.h> #define LOG_TAG "native_log" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #else # define LOGD(...) do {} while (0) // do nothing #endif // use it LOGD("%s : %d","value", val); ``` It worked fine by turn `DEBUG` flag on/off. The problem is I want to do it at run time in java side. What I want like this: ``` // java private native void nativeSetDebug(boolean flag); // jni JNIEXPORT void JNICALL Java_com_my_package_Native_nativeSetDebug(JNIEnv *env, jobject thiz, jboolean flag){ // what should I do in this method? } ``` Since the macros in c++ are replaced by the preprocessor by their value before source file even compiles, so I'm looking for another approach. Is there any ideas?

Original source