头文件
#pragma once
/////////////////////////////////////////////////////////////////////////////////
//异常信息记录类
#include <string>
#ifdef UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif
//定义异常信息结构体
typedef struct _EXCEPTION_INFO
{
tstring tstrExceptionInfo;//异常信息字符串
int nExceptionLine; //出现异常的代码行
}EXCEPTION_INFO,LPEXCEPTION_INFO;
//填充异常结构体
inline EXCEPTION_INFO FillExceptionInfo(TCHAR* pInfo,int nLine)
{
EXCEPTION_INFO ei;
ei.tstrExceptionInfo.append(pInfo);
ei.nExceptionLine=nLine;
return ei;
}
class _declspec(dllexport) CErrorLog
{
public:
CErrorLog(TCHAR* pModuleName);
virtual~ CErrorLog();
//记录异常,参数依次为函数名、错误信息、模块名
bool WriteErrorLog(tstring& tstrFuncName,int nLine,tstring& tstrErrorMsg=tstring(_T("")),tstring& tstrModuleName=tstring(_T("")));
bool WriteErrorLog(TCHAR* pFuncName,int nLine,TCHAR* pErrorMsg=NULL,TCHAR* pModuleName=NULL);
protected:
/********************受保护的成员函数**********************/
//记录自身异常
bool WriteOwerErrorLog( tstring& tstrFunName, tstring& tstrErrMsg,int nLine);
bool WriteOwerErrorLog(TCHAR* strFuncName,TCHAR* pErrorMsg,int nLine);
//格式化当前时间
inline std::string FormatTime();
//获取系统错误信息
inline std::string FormatLastError();
private:
//保存当前模块的名称
tstring m_strModuleName;
};
实现
#include "stdafx.h"
#include "CodeConvert.h"
#include "ErrorLog.h"
#include <time.h>
#include <assert.h>
CErrorLog::CErrorLog(TCHAR* pModuleName)
{
assert(pModuleName);
m_strModuleName.append(pModuleName);
}
CErrorLog::~CErrorLog()
{
}
bool CErrorLog::WriteOwerErrorLog(TCHAR* pFuncName,TCHAR* pErrorMsg,int nLine)
{
return WriteErrorLog(pFuncName,nLine,pErrorMsg,_T("CErrorLog"));
}
bool CErrorLog::WriteOwerErrorLog(tstring& tstrFunName, tstring& tstrErrMsg,int nLine )
{
return WriteErrorLog(tstrFunName,nLine,tstrErrMsg,tstring(_T("CErrorLog")));
}
bool CErrorLog::WriteErrorLog(TCHAR* pFuncName,int nLine,TCHAR* pErrorMsg,TCHAR* pModuleName)
{
bool bRet=true;
try
{
assert(pFuncName);
if(NULL!=pErrorMsg)
{
std::string strExcep;
std::string strFuncName;
#ifdef UNICODE
strFuncName.append(CCodeCovert::WcharToChar(pFuncName));
strExcep.append(CCodeCovert::WcharToChar(pErrorMsg));
#else
strFuncName.append(pFuncName);
strExcep.append(pErrorMsg);
#endif
TCHAR szPath[MAX_PATH+1]={0};
GetModuleFileName(NULL,szPath,MAX_PATH);
int nDes=-1;
for(size_t i=0;i<_tcslen(szPath);++i)
{
if('\'==szPath[i])
nDes=i;
}
szPath[nDes+1]='