C++写一个日志类及日志类的使用方法

#define LOG
#define WRITE_LOG(format, ...) CLog::getInstance()->PushLogInfo(__FUNCTION__, __LINE__, format, __VA_ARGS__)
class CLog
{
public:
	static CLog* getInstance()//返回CLog的单例
	{
		static CLog m_log;
		return &m_log;
	}
	void PushLogInfo(const char* szInfo);//将log信息加到队列中
	static unsigned __stdcall SaveLogThred(void * pThis)//保存Log线程
	{
		CLog * pthX = (CLog*)pThis;
		pthX->SaveLogInfo();
		return 1;
	}
	void StopThread();
private:
	CLog();
	~CLog();
	void SaveLogInfo();
	FILE* m_pFile;
	CBaselock m_lock;
	char m_szLogPath[MAX_PATH];
	list m_InfoLst;
	bool m_IsRun;
	bool m_IsExit;


};

为了不影响主程序性能,这种日志类开启了一个线程来单独作业。

CLog::CLog()
{
	char folderPath[256] = { 0 };
	SYSTEMTIME sysTime;
	GetLocalTime(&sysTime);
	char szExePath[256] = { 0 };
	GetModuleFileNameA(NULL, szExePath, MAX_PATH); //获取当前程序exe的全路径
	strrchr(szExePath, '\\')[1] = '\0';//去掉exe文件名
	sprintf_s(folderPath, "%sLog_Plugin", szExePath);
	if (_access(folderPath, 0) == -1)
	{
		_mkdir(folderPath);
	}
	sprintf_s(m_szLogPath, "%sLog\\Log%d%02d%02d%02d%02d%02d.txt", szExePath, sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond);//重新命名
	m_pFile = NULL;
	fopen_s(&m_pFile, m_szLogPath, "w+");//打开Log.txt文件,如果不存在,则创建该文件
	m_IsRun = true;
	m_IsExit = true;
	_beginthreadex(NULL, 0, &SaveLogThred, this, 0, 0);

}
CLog::~CLog()
{
	StopThread();//确保SaveLogInfo()中的while循环自然中止。
}
void CLog::StopThread()
{
	m_IsRun = false;
	int waitCnt = 5;
	while (waitCnt > 0)
	{
		if (m_IsExit)
			break;
		else
		{
			Sleep(100);
			waitCnt--;
		}
	}	
}
void CLog::PushLogInfo(const char* szInfo)
{
	m_lock.Lock();
	m_InfoLst.push_back(szInfo);
	m_lock.UnLock();
}
void CLog::SaveLogInfo()
{
	m_IsExit = false;
	while (m_IsRun)
	{
		if (m_InfoLst.empty())
		{
			Sleep(10);
			continue;
		}
		if (m_pFile != NULL)
		{
			fputs(m_InfoLst.front().c_str(), m_pFile);
			fflush(m_pFile);
			m_lock.Lock();
			m_InfoLst.pop_front();
			m_lock.UnLock();
		}
	}
	m_IsExit = true;
	fputs("Log Thread Exit!\n", m_pFile);
	if (m_pFile != NULL)
	{
		fclose(m_pFile);
		m_pFile = NULL;
	}
}

生成位置为程序目录下log文件。名称时年月日时分秒。

在程序中为了方便管理用宏的方法管理起来。

#ifdef LOG
		CLog::getInstance()->PushLogInfo("挺好的\n");
#endif // LOG

当然由于我已经定义了宏的方法也可以用宏来代替。WRITE_LOG(format, ...)

你可能感兴趣的:(C++,c++)