注:在网上找到的,自己改了一点
log.h
log.cpp
log.h
#ifndef _LOG_H
#define _LOG_H
class CLog
{
public:
CLog();
~CLog();
public:
void InitLog(LPCTSTR lpszLogPath);
void Add(const TCHAR* fmt, ...);
void AddString(LPCTSTR str);
protected:
enum {BUFSIZE = 3000};
TCHAR m_tBuf[BUFSIZE];
CString m_strLogPath;
CRITICAL_SECTION m_crit;
} ;
#endif
#define _LOG_H
class CLog
{
public:
CLog();
~CLog();
public:
void InitLog(LPCTSTR lpszLogPath);
void Add(const TCHAR* fmt, ...);
void AddString(LPCTSTR str);
protected:
enum {BUFSIZE = 3000};
TCHAR m_tBuf[BUFSIZE];
CString m_strLogPath;
CRITICAL_SECTION m_crit;
} ;
#endif
log.cpp
#include
"
stdafx.h
"
#include " log.h "
#include < wchar.h >
CLog::CLog()
{
::InitializeCriticalSection(&m_crit);
}
CLog:: ~ CLog()
{
::DeleteCriticalSection(&m_crit);
}
void CLog::InitLog(LPCTSTR lpszLogPath)
{
m_strLogPath=lpszLogPath;
}
void CLog::Add( const TCHAR * fmt, ...)
{
#ifdef _DEBUG
if (m_strLogPath.IsEmpty())
return ;
if (!AfxIsValidString(fmt, -1))
return ;
::EnterCriticalSection(&m_crit);
try
{
va_list argptr;
va_start(argptr, fmt);
_vsnwprintf_s(m_tBuf, BUFSIZE, fmt, argptr);
va_end(argptr);
}
catch (...)
{
m_tBuf[0] = 0;
}
FILE *fp;
_wfopen_s(&fp, (LPCTSTR)m_strLogPath, _T("a"));
if (fp)
{
fwprintf(fp,_T("%s: "), AfxGetApp()->m_pszExeName);
CTime ct ;
ct = CTime::GetCurrentTime();
fwprintf(fp,_T("%s : "),ct.Format("%m/%d/%Y %H:%M:%S"));
fwprintf(fp, _T("%s "), m_tBuf);
fclose(fp);
}
::LeaveCriticalSection(&m_crit);
#endif
}
void CLog::AddString(LPCTSTR str)
{
#ifdef _DEBUG
Add(_T("%s"), str);
#endif
}
#include " log.h "
#include < wchar.h >
CLog::CLog()
{
::InitializeCriticalSection(&m_crit);
}
CLog:: ~ CLog()
{
::DeleteCriticalSection(&m_crit);
}
void CLog::InitLog(LPCTSTR lpszLogPath)
{
m_strLogPath=lpszLogPath;
}
void CLog::Add( const TCHAR * fmt, ...)
{
#ifdef _DEBUG
if (m_strLogPath.IsEmpty())
return ;
if (!AfxIsValidString(fmt, -1))
return ;
::EnterCriticalSection(&m_crit);
try
{
va_list argptr;
va_start(argptr, fmt);
_vsnwprintf_s(m_tBuf, BUFSIZE, fmt, argptr);
va_end(argptr);
}
catch (...)
{
m_tBuf[0] = 0;
}
FILE *fp;
_wfopen_s(&fp, (LPCTSTR)m_strLogPath, _T("a"));
if (fp)
{
fwprintf(fp,_T("%s: "), AfxGetApp()->m_pszExeName);
CTime ct ;
ct = CTime::GetCurrentTime();
fwprintf(fp,_T("%s : "),ct.Format("%m/%d/%Y %H:%M:%S"));
fwprintf(fp, _T("%s "), m_tBuf);
fclose(fp);
}
::LeaveCriticalSection(&m_crit);
#endif
}
void CLog::AddString(LPCTSTR str)
{
#ifdef _DEBUG
Add(_T("%s"), str);
#endif
}