Android jni 代码中打印 log,使用android/log.h

文章目录

  • 日志库在 CMakeLists 的配置
  • 日志库简介
    • 日志级别枚举:
    • 定义宏


日志库在 CMakeLists 的配置

CMakeLists.txt :

#查找库:参数1,一个表示路径的变量,它会赋予库的路径值,且可用于后面的link; 参数2,库的名字
find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

#链接们自己的lib和其它lib。 可以使用 上面 find_library定位到的库,如${log-lib},也可以直接写上库的名字。
#这些预构建库在 //platforms/android-/arch-/usr/lib/
target_link_libraries(
	# 省略链接我们自己的库和其它库 
	
	# 链接日志库,可以使用变量名 或 库的名字
	# Links the target library to the log library  included in the NDK.
    ${log-lib}  #use variable
    #log #use real name
	
)

日志库简介

引入:#include

内部定义了 日志级别的枚举,打印日志的函数;
且可以使用 类似 c 中的 printf一样的格式化参数。

日志级别枚举:

typedef enum android_LogPriority {
  /** For internal use only.  */
  ANDROID_LOG_UNKNOWN = 0,
  /** The default priority, for internal use only.  */
  ANDROID_LOG_DEFAULT, /* only for SetMinPriority() */
  /** Verbose logging. Should typically be disabled for a release apk. */
  ANDROID_LOG_VERBOSE,
  /** Debug logging. Should typically be disabled for a release apk. */
  ANDROID_LOG_DEBUG,
  /** Informational logging. Should typically be disabled for a release apk. */
  ANDROID_LOG_INFO,
  /** Warning logging. For use with recoverable failures. */
  ANDROID_LOG_WARN,
  /** Error logging. For use with unrecoverable failures. */
  ANDROID_LOG_ERROR,
  /** Fatal logging. For use when aborting. */
  ANDROID_LOG_FATAL,
  /** For internal use only.  */
  ANDROID_LOG_SILENT, /* only for SetMinPriority(); must be last */
} android_LogPriority;

定义宏

如,新建一个 logutil.h。
定义了 ANDROID_LOG_INFO级别的 Tag 为 "stone.stone"的宏 slogd :

#include 
#ifndef LOG_TAG
#define LOG_TAG "stone.stone"
#define slogd(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#endif

其中,…表示可变参数列表,__VA_ARGS__在预处理中,会被实际的参数列表所替换。

之后,在其它地方使用,例:

#include "logutil.h" 

int num = 100;
void testlog() {
	slogd("test number=%d", number);
}

你可能感兴趣的:(Android,JNI/NDK,JNI&Android,NDK)