1. 程式人生 > >log檔案的讀寫[轉]

log檔案的讀寫[轉]

/**  
 * 用於輸出log檔案的類.  
 */    


#ifndef LOG_H    
#define LOG_H    


//log檔案路徑  
#define LOG_FILE_NAME "log.txt"  

//啟用開關  
#define LOG_ENABLE  

#include <fstream>    
#include <string>    
#include <ctime>    

using namespace std;    

class CLog    
{    
public:    
    static void
GetLogFilePath(CHAR* szPath) { GetModuleFileNameA( NULL, szPath, MAX_PATH ) ; ZeroMemory(strrchr(szPath,_T('\\')), strlen(strrchr(szPath,_T('\\') ) )*sizeof(CHAR)) ; strcat(szPath,"\\"); strcat(szPath,LOG_FILE_NAME); } //輸出一個內容,可以是字串(ascii)、整數、浮點數、布林、列舉
//格式為:[2011-11-11 11:11:11] aaaaaaa並換行 template <class T> static void WriteLog(T x) { CHAR szPath[MAX_PATH] = {0}; GetLogFilePath(szPath); ofstream fout(szPath,ios::app); fout.seekp(ios::end); fout << GetSystemTime() << x <<endl; fout.close(); } //輸出2個內容,以等號連線。一般用於前面是一個變數的描述字串,後面接這個變數的值
template<class T1,class T2> static void WriteLog2(T1 x1,T2 x2) { CHAR szPath[MAX_PATH] = {0}; GetLogFilePath(szPath); ofstream fout(szPath,ios::app); fout.seekp(ios::end); fout << GetSystemTime() << x1 <<" = "<<x2<<endl; fout.close(); } //輸出一行當前函式開始的標誌,巨集傳入__FUNCTION__ template <class T> static void WriteFuncBegin(T x) { CHAR szPath[MAX_PATH] = {0}; GetLogFilePath(szPath); ofstream fout(szPath,ios::app); fout.seekp(ios::end); fout << GetSystemTime() << " --------------------"<<x<<" Begin--------------------" <<endl; fout.close(); } //輸出一行當前函式結束的標誌,巨集傳入__FUNCTION__ template <class T> static void WriteFuncEnd(T x) { CHAR szPath[MAX_PATH] = {0}; GetLogFilePath(szPath); ofstream fout(szPath,ios::app); fout.seekp(ios::end); fout << GetSystemTime() << "--------------------"<<x<<" End --------------------" <<endl; fout.close(); } private: //獲取本地時間,格式如"[2011-11-11 11:11:11] "; static string GetSystemTime() { time_t tNowTime; time(&tNowTime); tm* tLocalTime = localtime(&tNowTime); char szTime[30] = {'\0'}; strftime(szTime, 30, "[%Y-%m-%d %H:%M:%S] ", tLocalTime); string strTime = szTime; return strTime; } }; #ifdef LOG_ENABLE //用下面這些巨集來使用本檔案 #define LOG(x) CLog::WriteLog(x); //括號內可以是字串(ascii)、整數、浮點數、bool等 #define LOG2(x1,x2) CLog::WriteLog2(x1,x2); #define LOG_FUNC LOG(__FUNCTION__) //輸出當前所在函式名 #define LOG_LINE LOG(__LINE__) //輸出當前行號 #define LOG_FUNC_BEGIN CLog::WriteFuncBegin(__FUNCTION__); //形式如:[時間]"------------FuncName Begin------------" #define LOG_FUNC_END CLog::WriteFuncEnd(__FUNCTION__); //形式如:[時間]"------------FuncName End------------" #else #define LOG(x) #define LOG2(x1,x2) #define LOG_FUNC #define LOG_LINE #define LOG_FUNC_BEGIN #define LOG_FUNC_END #endif #endif