win32动态库比MFC动态库使用更广泛:
/************************************************************************
* 功能描述:日志类.
* 其它说明:使用单例模式实现
************************************************************************/
#ifndef _LOG_
#define _LOG_
#include "../MptBase.h"
class MPTEXPORT CLog
{
public:
static CLog *m_plog;
//static CMutex *m_mutex;
static HANDLE m_mutex;
private:
#if 0
FILE * m_fp;
void WriteLog(const CString &str, ...);
#endif
private:
CLog(void);
public:
static CLog *GetInstance();
void WriteLog(const LPCTSTR str, ...);
~CLog(void);
};
#endif
#include "stdafx.h"
#include "Log.h"
#include "debugviewhelper.h"
#include <tchar.h>
#if 0
static CString GetCurrentPath()
{
TCHAR path[MAX_PATH] = {0};
GetModuleFileName(GetModuleHandle(NULL), path, MAX_PATH);
CString str = path;
int nlen = str.ReverseFind('\\');
str = str.Left(nlen);
if (str.Right(0) != _T("\\"))
str = str + _T("\\");
return str;
}
#endif
CLog::CLog(void)
{
#if 0
CString str = GetCurrentPath();
str += _T("log.txt");
m_fp = _tfsopen((LPCTSTR)str, _T("w+, ccs=UTF-8"), _SH_DENYNO);
#endif
}
CLog *CLog::m_plog = NULL;
HANDLE CLog::m_mutex = CreateMutexA(NULL, FALSE, "mutex");//new CMutex();
CLog::~CLog(void)
{
if (m_mutex != NULL)
{
//delete m_mutex;
CloseHandle(m_mutex);
m_mutex = NULL;
}
if (m_plog != NULL)
{
delete m_plog;
m_plog = NULL;
}
}
CLog * CLog::GetInstance()
{
if (m_plog != NULL)
{
return m_plog;
}
else
{
//m_mutex->Lock();
WaitForSingleObject(m_mutex, INFINITE);
if (m_plog == NULL)
{
m_plog = new CLog();
}
//m_mutex->Unlock();
ReleaseMutex(m_mutex);
return m_plog;
}
}
void CLog::WriteLog(const LPCTSTR str, ...)
{
if((_tcslen(str) == 0))
return;
TCHAR buffer[1024];
memset(buffer, 0, sizeof(buffer));
TCHAR logtext[64+1024] = {0};
swprintf(logtext, _T("%d "), GetCurrentThreadId());
size_t textOffset = wcslen(logtext);
va_list maker;
va_start(maker, str);
_vsntprintf_s(buffer, sizeof(buffer)/sizeof(TCHAR) - 1, str, maker);
va_end(maker);
//DI << buffer;
wcscat(logtext, buffer);
DI << logtext;
}
#if 0
void CLog::WriteLog(const CString &str, ...)
{
if(!m_fp || (_tcslen(str)== 0))
return;
TCHAR buffer[1024];
va_list maker;
va_start(maker, str);
_vsntprintf_s(buffer, sizeof(str)/sizeof(TCHAR) - 1, 1024, str, maker);
va_end(maker);
CTime tm = CTime::GetCurrentTime();
_ftprintf_s(m_fp, _T("%4d-%02d-%02d %02d:%02d:%02d %s\r\n"),
tm.GetYear(),
tm.GetMonth(),
tm.GetDay(),
tm.GetHour(),
tm.GetMinute(),
tm.GetSecond(),
buffer);
fflush(m_fp);
}
#endif