MFC写log

来源:互联网 发布:都市之数据化人生 编辑:程序博客网 时间:2024/05/31 19:11

void OutputLog(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();
    }
}

 

用法:

  1. CString str; 
  2. str.Format(_T("%s, %s [L%d] "), __FILE__, __FUNCTION__, __LINE__); 
  3. str += "Start..."
  4. OutputLog("Log.log", str);