运行日志Log文件c++实现

运行日志Log文件c++实现,第1张

实现多线程插入,按时间顺序,自测无问题
定义


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();
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/993208.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-21
下一篇2022-05-21

发表评论

登录后才能评论

评论列表(0条)

    保存