
实现多线程插入,按时间顺序,自测无问题
定义
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::writeFileFunclass="superseo">ction, 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();
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)