实现多线程插入,按时间顺序,自测无问题
定义
using namespace std;
enum LEVEL
{
information = 0,
warrning,
error
};
class Log
{
public:
Log();
~Log();
Log(const char* dir);
void writeLog(const char* msg, LEVEL level = information);
private:
fstream file;
char *fileName;
void createFile(const char* filePath);
void createDirection(const char* dirPath);
void writeFileFunction(const char* msg, LEVEL level = information);
const char* dirPath;
mutex mtx;
};
核心实现
void Log::writeLog(const char* msg, LEVEL level) {
thread t1(&Log::writeFileFunction, this, msg, level);
t1.detach();
}
void Log::writeFileFunction(const char* msg, LEVEL level) {
mtx.lock();
createFile(dirPath);
file.open(fileName, ios::app | ios::in | ios::out);
if (file) {
SYSTEMTIME st = { 0 };
GetLocalTime(&st);
char *message = new char[500];
memset(message, 0, 500);
const char* info = NULL;
switch (level)
{
case information:
info = "info";
break;
case warrning:
info = "warn";
break;
case error:
info = "error";
break;
}
sprintf(message, "%d-%02d-%02d %02d:%02d:%02d:%03d [%s] %s\n", st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, info, msg);
file.write(message, strlen(message));
}
file.close();
mtx.unlock();
}
该博客介绍了如何实现一个多线程安全的日志类,使用C++的mutex确保线程同步,保证日志按时间顺序写入文件。通过创建独立线程并分离,实现了异步写入日志,同时提供了不同级别的日志记录选项。
548

被折叠的 条评论
为什么被折叠?



