知识点
- 宏定义参数 控制打印的等级与打印开关
- enum的使用
- stdarg.h中对可变数量参数的函数的机制运用
- 文件包含结构
- ifdef 与 ifndef的运用
zlog.h
#define OPEN_LOG
#define Error_SHOW_LEVEL D
typedef enum
{
A = 1,
B,
C,
D,
E
}Error_Level;
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
void printStrings(const Error_Level level, const char* func, const int line, const char* fmt, ...);
#define ErrorPrint(level, fmt,...) printStrings(level, __FUNCTION__, __LINE__, fmt) //宏定义与函数调用的嵌套
zlog.cpp
#ifndef ZLOG_H
#define ZLOG_H
#include "zlog.h"
#endif // !ZLOG_H
const char* getErrorLevelString(Error_Level level) {
switch (level) {
case A:
return "Error Level A";
case B:
return "Error Level B";
case C:
return "Error Level C";
case D:
return "Error Level D";
case E:
return "Error Level E";
default:
return "Unknown Error Level";
}
}
void printStrings(const Error_Level level, const char* func, const int line, const char* fmt, ...) {
#ifdef OPEN_LOG
if (level >= Error_SHOW_LEVEL) {
va_list args;
va_start(args, fmt); // 初始化参数列表
int len = 1 + vsnprintf(NULL, 0, fmt, args);
char* buf = (char*)malloc(len * sizeof(char));
if (buf == NULL) {
printf("Memory allocation failed.\n");
return;
}
vsnprintf(buf, len, fmt, args); // 使用 vsnprintf 将格式化后的字符串写入缓冲区
printf("[%s] [%s %d] [%s]\n", getErrorLevelString(level), func, line, buf); // 打印格式化后的字符串
free(buf); // 释放动态分配的缓冲区
va_end(args); // 结束参数列表
}
#endif //
}
//int main() {
// ErrorPrint(A,"这是一A级别的错误");
// ErrorPrint(B, "这是一B级别的错误");
// ErrorPrint(C, "这是一C级别的错误");
// ErrorPrint(D, "这是一D级别的错误");
// ErrorPrint(E, "这是一E级别的错误");
// return 0;
//}
test.cpp
#include"zlog.h"
int main() {
ErrorPrint(A, "这是一A级别的错误");
ErrorPrint(B, "这是一B级别的错误");
ErrorPrint(C, "这是一C级别的错误");
ErrorPrint(D, "这是一D级别的错误");
ErrorPrint(E, "这是一E级别的错误");
return 0;
}