首页 > 代码库 > Log
Log
#include <fstream>#include <windows.h>#define LOG_PATH "c:\\NetBiosUtilDll.log"// Use global object to ensure initialization and release.class GlobalEnv{public: GlobalEnv() { ::InitializeCriticalSection(&csLock); } ~GlobalEnv(); CRITICAL_SECTION csLock;} g_env;// Singleton multi-thread friendly log writer.// Call LogWriter::GetInstance()->WriteLog() to output log.class LogWriter{public: bool WriteLog(const char* cStr); static LogWriter* GetInstance(); static void ReleaseInstance();private: LogWriter(); ~LogWriter(); static LogWriter* s_Instance; std::fstream m_file; class LockCS { public: LockCS() { ::EnterCriticalSection(&g_env.csLock); } ~LockCS() { ::LeaveCriticalSection(&g_env.csLock); } };};GlobalEnv::~GlobalEnv(){ LogWriter::ReleaseInstance(); ::DeleteCriticalSection(&csLock);}LogWriter::LogWriter(){ m_file.open(LOG_PATH, std::ios::app); if(m_file.is_open()) WriteLog("---------- Start Logging ----------");}LogWriter::~LogWriter(){ if(m_file.is_open()) { WriteLog("---------- End Logging ----------\n"); m_file.close(); }}LogWriter* LogWriter::GetInstance(){ if(NULL == s_Instance) { LockCS cs; if(NULL == s_Instance) { s_Instance = new LogWriter(); } } return s_Instance;}void LogWriter::ReleaseInstance(){ if(NULL != s_Instance) { LockCS cs; if(NULL != s_Instance) { delete s_Instance; s_Instance = NULL; } }}LogWriter* LogWriter::s_Instance = NULL;bool LogWriter::WriteLog(const char* cStr){ if(!m_file.is_open()) return false; LockCS cs; DWORD dwPid = GetCurrentThreadId(); SYSTEMTIME sys; GetLocalTime( &sys ); // Output pid m_file<<‘[‘<<dwPid<<‘]‘<<‘\t‘; // Output time m_file<<‘(‘<<sys.wYear<<‘-‘<<sys.wMonth<<‘-‘<<sys.wDay<<‘ ‘<<sys.wHour<<‘:‘<<sys.wMinute<<‘:‘<<sys.wSecond<<‘)‘<<‘\t‘; // Output log m_file<<cStr<<std::endl; return true;}//// test#include <process.h>void ThreadProc(void*){ for(int i=0; i<5; ++i) { ::Sleep(3); LogWriter::GetInstance()->WriteLog("hello"); }}void test( ){ for(int i=0; i<5; ++i) { ::Sleep(3); ::_beginthread(ThreadProc, 0, NULL); }}int main(){ test(); getchar(); return 0;}
Log
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。