首页 > 代码库 > 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