有的时候,我们的工程需要记录一些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();
}
}
{
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();
}
}