日志系统的设计
在大型项目中,完善的日志系统是监控状态的基础。Server 部分承载了所有类的最终调用逻辑,而清晰的日志能帮助快速定位问题。
FILE 和 LINE 是 C/C++ 编译器预定义的特殊宏,它们会被自动替换为当前源文件的路径或文件名,以及代码所在的行号。在日志函数中,这两个宏能精确记录 '这条日志是从哪个文件的哪一行输出的',例如 [test.cpp : 25]。
我们可以封装一个日志宏来统一输出格式。注意这里使用了 inline 关键字以避免头文件中重复定义的链接错误,同时补充了 <cstring> 以支持字符串长度计算。
#pragma once
#include <iostream>
#include <string>
#include <ctime>
#include <cstring>
#define NORMAL 1
#define WARNING 2
#define DEBUG 3
#define FATAL 4
// 使用 inline 确保头文件多次包含时的安全性
void log1(std::string level, std::string message, std::string file, int line) {
std::cout << "[" << level << "]"
<< "[" << time(nullptr) << "]"
<< "[" << message << "]"
<< "[" << file << " : " << line << "]"
<< std::endl;
}
#define LOG1(LEVEL, MESSAGE) log1(#LEVEL, MESSAGE, __FILE__, __LINE__)



