文章

安卓NDK开发,如何优雅的打印日志

做音视频开发不可避免需要Android NDK调试,经常需要打日志,如何优雅的打印安卓NDK开发日志,整理到这里:

头文件

1
2
#include <android/log.h> 

日志级别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/** 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 */

使用

简单使用:

1
2
#include <android/log.h> 
__android_log_print(ANDROID_LOG_INFO, "log_tag", "this is log:%d", val);

更优雅的方式:宏封装:

1
2
3
4
5
6
7
8
#include <android/log.h>

#define TAG "Your Log Tag" 
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__) 	// 定义LOGD类型
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__) 		// 定义LOGI类型 
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__) 		// 定义LOGW类型 
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__) 	// 定义LOGE类型 
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__) 	// 定义LOGF类型

使用:

1
2
3
4
LOGI("This is info log!"); 
LOGD("This is debug log!"); 
LOGW("This is warn log!"); 
LOGE("This is error log!"); 

参考

@See https://developer.android.com/ndk/reference/group/logging

本文由作者按照 CC BY 4.0 进行授权