MFC写Log文件之定式

   有的时候,我们的工程需要记录一些Log的信息到文件中,方法有各种各样,下面介绍比较简单易用的CStdioFile类方法,自定义WriteLog方法,再调用CStdioFile方法即可:

void WriteLog(LPCTSTR logName, CString msg)
{
    try
    {
        //设置文件的打开参数
        CStdioFile outFile(logName, CFile::modeNoTruncate | CFile::modeCreate | CFile::modeWrite | CFile::typeText);
        CString msLine;
        CTime tt = CTime::GetCurrentTime();

        //作为Log 文件,经常要给每条Log 时间戳,时间格式可自由定义,
        //这里的格式如:2010-June-10 Thursday, 15:58:12
        msLine = tt.Format("[%Y-%B-%d %A, %H:%M:%S] ") + msg;
        msLine += "\n";

        //在文件末尾插入新纪录
        outFile.SeekToEnd();
        outFile.WriteString( msLine );
        outFile.Close();
    }
    catch(CFileException *fx)
    {
        fx->Delete();
    }
}
QT版本 //xxxx.h //log level #define LL_DEBUG 0 #define LL_INFO 1 #define LL_WARN 2 #define LL_ERROR 3 #define LL_ALARM 4 #define GetCurFileName (__FILE__) #define GetCurCodeLine (__LINE__) #define GetCurCodeFunctionName (__FUNCTION__) #define Write_Log(LEVEL, FMTLOG) WriteLog(LEVEL, FMTLOG, GetCurFileName, GetCurCodeLine, GetCurCodeFunctionName) void WriteLog(int, QString, QString, int, QString); //xxxx.cpp void WriteLog(int loglevel, QString strlogstr, QString strfilename, int iline, QString strfunname) { QString g_logdllpath(g_runPath + "/dependences/LoggingModeDLL.dll"); HINSTANCE hDll = LoadLibrary(g_logdllpath.toStdWString().data()); typedef int (__cdecl *MYFUNC)(int, char*, char*, int, char*); MYFUNC execfunc = (MYFUNC)GetProcAddress(hDll, "WriteLog"); execfunc(loglevel, const_cast<char*>(strlogstr.toLatin1().data()), const_cast<char*>(strfilename.toLatin1().data()), iline, const_cast<char*>(strfunname.toLatin1().data())); } MFC 版本 //xxxx.h //log level #define LL_DEBUG 0 #define LL_INFO 1 #define LL_WARN 2 #define LL_ERROR 3 #define LL_ALARM 4 #define GetCurFileName (__FILE__) #define GetCurCodeLine (__LINE__) #define GetCurCodeFunctionName (__FUNCTION__) #define Write_Log(LEVEL, FMTLOG) WriteLog(LEVEL, FMTLOG, GetCurFileName, GetCurCodeLine, GetCurCodeFunctionName) void WriteLog(int, CString, CString, int, CString); void WriteLog(int loglevel, CString strlogstr, CString strfilename, int iline, CString strfunname) { CString g_logdllpath(".\\LoggingModeDLL.dll"); HINSTANCE hDll = LoadLibrary(g_logdllpath.GetBuffer()); typedef int (__cdecl *MYFUNC)(int, char*, char*, int, char*); MYFUNC execfunc = (MYFUNC)GetProcAddress(hDll, "WriteLog"); execfunc(loglevel, const_cast<char*>(strlogstr.GetBuffer()), const_cast<char*>(strfilename.GetBuffer()), iline, const_cast<char*>(strfunname.GetBuffer())); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值