在軟件開發中,為程序建立Log日志是很必要的,它可以記錄程序運行的狀態以及出錯信息,方便維護和調試。
下面實現了一個簡單的Log類,使用非常簡單,僅供參考。
// CLogHelper.h : header file for log information // #pragma once class CLogHelper { public: CLogHelper(void); ~CLogHelper(void); static void WriteLog(LPCTSTR lpszLog); private: static CString MakeFilePath(); static CString MakeLogMsg(LPCTSTR lpszLog); };
// LogHelper.cpp : implementation file // #include "StdAfx.h" #include "LogHelper.h" #include <io.h> #include <stdio.h> #include <stdlib.h> #include <locale> #define LOG_FILE_NAME _T("*Log.log") CLogHelper::CLogHelper(void) { } CLogHelper::~CLogHelper(void) { } void CLogHelper::WriteLog( LPCTSTR lpszLog ) { // 獲取日志文件路徑 static CString strLogFilePath = _T(""); if (strLogFilePath.IsEmpty()) { strLogFilePath = MakeFilePath(); } // 判斷日志文件是否存在,不存在則創建 wchar_t* pwchLogFilePath = strLogFilePath.AllocSysString(); errno_t err = 0; if ((err = _taccess_s(pwchLogFilePath, 0)) != 0) { CStdioFile file; if(file.Open(strLogFilePath, CStdioFile::modeCreate)) { file.Close(); } } // 向日志文件寫入日志 CStdioFile file; if (file.Open((LPCTSTR)strLogFilePath, CStdioFile::modeWrite | CStdioFile::shareDenyNone)) { CString strMsg = MakeLogMsg(lpszLog); file.SeekToEnd(); char* old_locale = _strdup( setlocale(LC_CTYPE,NULL) ); setlocale( LC_CTYPE, "chs" ); // 設定區域 file.WriteString(strMsg); setlocale( LC_CTYPE, old_locale ); free( old_locale ); // 還原區域設定 file.Close(); } } CString CLogHelper::MakeLogMsg(LPCTSTR lpszLog) { CTime time = CTime::GetCurrentTime(); CString strMsg = time.Format("[%Y-%m-%d %H:%M:%S] "); strMsg = strMsg + lpszLog + _T("\r\n"); return strMsg; } CString CLogHelper::MakeFilePath() { // 獲取當前進程路徑 TCHAR szFilePath[MAX_PATH]; memset(szFilePath, 0, MAX_PATH); ::GetModuleFileName(NULL, szFilePath, MAX_PATH); (_tcsrchr(szFilePath, _T('\\')))[1] = 0; // 刪除文件名,只獲得路徑字符串 CString strFilePath = szFilePath; strFilePath = strFilePath + LOG_FILE_NAME; return strFilePath; }
使用方法:
CString strLogMsg = _T("程序開始運行..."); CLogHelper::WriteLog(strLogMsg);