_log.h
- #ifdef __cplusplus
- extern "C" {
- #endif
- typedef int (* funcPtr)(const char * format, ...);
- typedef struct _Log
- {
- funcPtr d;
- funcPtr i;
- funcPtr e;
- }LOG;
- extern const LOG Log;
- #ifdef __cplusplus
- };
- #endif
_log.c
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdarg.h>
- #include "_log.h"
- #define BUFFER_SIZE (1024 * 2)
- static char db_buffer[BUFFER_SIZE];
- #ifdef WIN32
- # define vsnprintf _vsnprintf
- # define LOGD printf
- # define LOGI printf
- # define LOGW printf
- # define LOGE printf
- # define LOGF printf
- #else // #ifdef WIN32
- # include <jni.h>
- # include <android/log.h> // 这个是输出LOG所用到的函数所在的路径
- # define LOG_TAG "JNILOG" // 这个是自定义的LOG的标识
- # undef LOG // 取消默认的LOG
- //Android.mk中要添加LOCAL_LDLIBS := -llog
- //# 如果不包含这一句的话,会提示:__android_log_print 未定义
- # define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) // 定义LOG类型
- # define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) // 定义LOG类型
- # define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__) // 定义LOG类型
- # define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) // 定义LOG类型
- # define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,LOG_TAG,__VA_ARGS__) // 定义LOG类型
- #endif //#ifdef WIN32
- #define db_print(__tag, __p, __format) \
- do { \
- int n = 0; \
- va_list args; \
- va_start(args, __format); \
- vsnprintf(db_buffer, BUFFER_SIZE - 1, __format, args); \
- db_buffer[BUFFER_SIZE - 1] = 0; \
- __p(__tag);\
- n = __p(db_buffer); \
- va_end(args); \
- return n; \
- } while (0)
- static int log_d(const char * format, ...)
- {
- #ifdef _DEBUG
- db_print("debug: ", LOGD, format);
- #else
- return 0;
- #endif
- }
- static int log_i(const char * format, ...)
- {
- db_print("info : ", LOGI, format);
- }
- static int log_e(const char * format, ...)
- {
- db_print("error: ", LOGE, format);
- }
- const LOG Log =
- {
- log_d,
- log_i,
- log_e,
- };
Android.mk
- LOCAL_PATH := $(call my-dir)
- include $(CLEAR_VARS)
- LOCAL_MODULE := init
- LOCAL_SRC_FILES := _log.c
- LOCAL_LDLIBS := -llog
- include $(BUILD_SHARED_LIBRARY)
WIN32下测试
main.c
- #include "_log.h"
- int main(int argc, char * argv[])
- {
- Log.d("dddddddd\n");
- Log.i("iiiiiiii\n");
- Log.e("eeeeeeee\n");
- return 0;
- }
运行结果
debug: dddddddd
info : iiiiiiii
error: eeeeeeee
注意:Android.mk中要添加LOCAL_LDLIBS := -llog# 如果不包含这一句的话,会提示:__android_log_print 未定义