1. debug.h 代码
typedef enum {
LOG_LEVER_INFO = 0,
LOG_LEVER_WARN = 1,
LOG_LEVER_DBG = 2,
LOG_LEVER_ERR = 3,
LOG_LEVER_MAX
} LOG_LEVER_E;
void debugOut(LOG_LEVER_E lever, const char *fmt, ...);
2. common.h 代码
typedef struct {
unsigned int id;
char *info;
} IdTable;
3. debug.c 代码
#include "debug.h"
#include <stdio.h>
#include <stdarg.h>
#include "common.h"
#define LOG_MAX_LEN 400
IdTable g_levelTbl[] = {
{LOG_LEVER_INFO, "[INFO]"},
{LOG_LEVER_WARN, "[WARN]"},
{LOG_LEVER_DBG, "[DBG]"},
{LOG_LEVER_ERR, "[ERR]"},
};
void debugOut(LOG_LEVER_E lever, const char *fmt, ...)
{
if (lever >= LOG_LEVER_MAX) {
return;
}
char res[LOG_MAX_LEN] = {0};
char *logLever = g_levelTbl[lever].info;
int ret = sprintf_s(res, LOG_MAX_LEN, "%s:", logLever);
if (ret < 0) {
printf("debug lever string is overflow: %d\n", ret);
return;
}
unsigned int left = ret;
va_list arg_list;
va_start(arg_list, fmt);
ret = sprintf_s(res + left, LOG_MAX_LEN - left, fmt, arg_list);
va_end(arg_list);
if (ret < 0) {
printf("debug string is overflow: %d\n", ret);
return;
}
printf("%s\n", res);
}
4. 主函数
int main() {
debugOut(LOG_LEVER_INFO, "test debug out");
return 0;
}
5. 运行结果