首页 > 其他 > 详细

Log

时间:2014-09-25 17:55:38      阅读:252      评论:0      收藏:0      [点我收藏+]
#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

原文:http://www.cnblogs.com/playerken/p/3993141.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!