Android JNI打印logcat日志

在 JNI 中打印日志可以使用 __android_log_print 函数来实现。该函数是 Android NDK 提供的一个用于在本地代码中输出日志消息到 logcat 的方法。

要在 JNI 中打印日志,请按照以下步骤进行操作:

  1. 在你的 JNI C/C++ 代码中包含 头文件:

    #include 
    
  2. 使用 __android_log_print 函数来打印日志。它的原型定义如下:

    __android_log_print(int priority, const char* tag, const char* format, ...)
    

    priority:日志的优先级,可以是 ANDROID_LOG_VERBOSE、ANDROID_LOG_DEBUG、ANDROID_LOG_INFO、ANDROID_LOG_WARN 或 ANDROID_LOG_ERROR。
    tag:用于标识日志来源的字符串。
    format:日志消息的格式化字符串。
    …:可变参数,用于填充格式化字符串中的占位符。

  3. 在适当的地方使用 __android_log_print 函数来打印日志。例如:

    __android_log_print(ANDROID_LOG_DEBUG, "MyApp", "JNI log message: %s, %d", "Hello", 123);
    

    上述代码将以 DEBUG 级别在 logcat 中打印一条日志,标签为 “MyApp”,内容为 “JNI log message: Hello, 123”。

  4. 在项目的 Android.mk 文件或 CMakeLists.txt 文件中添加对 log 库的链接。例如,在 CMakeLists.txt 中,可以添加以下行:

     target_link_libraries(your_library_name log)
    

    这将确保你的 JNI 库能够正确链接到 log 库。

通过上述步骤,你可以在 JNI 中使用 __android_log_print 函数来打印日志,并在 logcat 中查看输出。确保根据需要设置适当的日志级别和标签,以及格式化字符串和参数。
下面是一个简单的 LogUtil 工具类示例,其中封装了 __android_log_print 函数:

#include 
class LogUtil {
public:
    static void debug(const char* tag, const char* message) {
        __android_log_print(ANDROID_LOG_DEBUG, tag, "%s", message);
    }

    static void info(const char* tag, const char* message) {
        __android_log_print(ANDROID_LOG_INFO, tag, "%s", message);
    }

    static void warn(const char* tag, const char* message) {
        __android_log_print(ANDROID_LOG_WARN, tag, "%s", message);
    }

    static void error(const char* tag, const char* message) {
        __android_log_print(ANDROID_LOG_ERROR, tag, "%s", message);
    }
};

使用时,可以通过 LogUtil::debug、LogUtil::info、LogUtil::warn 和 LogUtil::error 方法打印不同级别的日志。例如:

LogUtil::debug("MyApp", "Debug log message");
LogUtil::info("MyApp", "Info log message");
LogUtil::warn("MyApp", "Warning log message");
LogUtil::error("MyApp", "Error log message");

你可能感兴趣的:(android,JNI)