最近项目出现点小Bug,需要调试跟踪代码,于是乎写了份打印日志的代码。
CLogFile.h文件
1 #if !defined(AFX_LOGFILE_H__288388CA_9A3E_4F3D_A2B8_F1078E1F6A6B__INCLUDED_) 2 #define AFX_LOGFILE_H__288388CA_9A3E_4F3D_A2B8_F1078E1F6A6B__INCLUDED_ 3 4 #if _MSC_VER > 1000 5 #pragma once 6 #endif // _MSC_VER > 1000 7 8 class CLogFile 9 { 10 public: 11 CLogFile(); 12 ~CLogFile(); 13 private: 14 static CString GetFileName(); 15 static CString GetFilePath(); 16 public: 17 static bool WriteLog(CString LogText); 18 }; 19 20 #endif // !defined(AFX_LOGFILE_H__288388CA_9A3E_4F3D_A2B8_F1078E1F6A6B__INCLUDED_)
CLogFile.cpp文件
1 #include "stdafx.h" 2 #include "CLogFile.h" 3 4 CLogFile::CLogFile() 5 { 6 7 } 8 9 CLogFile::~CLogFile() 10 { 11 12 } 13 //获取文件名称 14 CString CLogFile::GetFileName() 15 { 16 CString sFileName; 17 18 sFileName = CTime::GetCurrentTime().Format("%Y-%m-%d") + TEXT(".log"); 19 20 return sFileName; 21 } 22 23 //获取应用程序所在路径 24 CString CLogFile::GetFilePath() 25 { 26 CString m_FilePath; 27 28 GetModuleFileName(NULL,m_FilePath.GetBufferSetLength(MAX_PATH+1),MAX_PATH); 29 30 m_FilePath.ReleaseBuffer(); 31 32 int m_iPosIndex; 33 34 m_iPosIndex = m_FilePath.ReverseFind('\'); 35 36 //m_FilePath = m_FilePath.Left(m_iPosIndex) + TEXT("\Log"); 37 m_FilePath = "D:\VISTA\LOGSA"; 38 39 return m_FilePath; 40 } 41 42 bool CLogFile::WriteLog(CString LogText) 43 { 44 try 45 { 46 //CFile m_File; 47 CFile m_SFile; 48 CFileFind m_FileFind; 49 CString m_sErrorMessage; 50 CString m_sFileName = GetFileName(); 51 CString m_sFilePath = GetFilePath(); 52 CString m_sCurrentTime = CTime::GetCurrentTime().Format("%Y-%m-%d %X"); 53 54 55 if(!m_FileFind.FindFile(m_sFilePath)) 56 { 57 CreateDirectory(m_sFilePath,NULL); 58 } 59 60 m_SFile.Open(m_sFilePath + TEXT("\") +m_sFileName,CFile::modeCreate |CFile::modeNoTruncate| CFile::modeReadWrite |CFile::shareDenyWrite); 61 /*{ 62 m_SFile.Open(m_sFilePath + TEXT("\") + m_sFileName,CFile::modeCreate | CFile::modeReadWrite |CFile::shareDenyWrite| CFile::typeText); 63 }*/ 64 65 m_SFile.SeekToEnd(); 66 67 if(sizeof(TCHAR)==sizeof(WCHAR)) 68 { 69 WORD wSignature = 0xFEFF; 70 m_SFile.Write(&wSignature, 2); 71 } 72 73 //TCHAR* m_szMessage; 74 75 //m_szMessage=m_sErrorMessage.GetBuffer(); 76 77 m_sErrorMessage = TEXT("*******************") + m_sCurrentTime + TEXT("*******************")+TEXT(" ") ; 78 m_SFile.Write(m_sErrorMessage,m_sErrorMessage.GetLength()*sizeof(TCHAR)); 79 80 //m_sErrorMessage = LogText ; 81 LogText+=TEXT(" "); 82 m_SFile.Write(LogText,LogText.GetLength()*sizeof(TCHAR)); 83 //m_sErrorMessage = TEXT("*******************") + m_sCurrentTime + TEXT("*******************") ; 84 m_SFile.Write(m_sErrorMessage,m_sErrorMessage.GetLength()*sizeof(TCHAR)); 85 86 //m_SFile.Write(m_sErrorMessage.GetBuffer(),m_sErrorMessage.GetLength()); 87 88 m_SFile.Close(); 89 } 90 catch(CFileException fileException) 91 { 92 return false; 93 } 94 95 return true; 96 }
以上代码经过调试通过!