http://blog.csdn.net/dpsying/article/details/17122739
有時候需要輸出一些程序運行的信息,供我們不需要調試就可以直接查看程序運行狀態。所以我們需要在程序中加入一些LOG輸出。
適合涉及到虛擬機調試一些關於驅動等的程序時,或進行遠程調試時。
搜了些log工具,不夠輕……還是簡單實現下吧
貼上來,可能有用的上:
Log.h
- /**
- * 用於輸出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
使用:
直接在需要輸出日志的地方使用宏LOG(text)就可以了,記得包含頭文件Log.h。
- #include "Log.h"
- BOOL
- int float BOOL enum )
- return
- 效果: