http://blog.csdn.net/dpsying/article/details/17122739
有时候需要输出一些程序运行的信息,供我们不需要调试就可以直接查看程序运行状态。所以我们需要在程序中加入一些LOG输出。
适合涉及到虚拟机调试一些关于驱动等的程序时,或进行远程调试时。
搜了些log工具,不够轻……还是简单实现下吧
贴上来,可能有用的上:
Log.h
-
-
-
- #ifndef LOG_H
- #define LOG_H
-
-
- #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);
- }
-
-
- 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();
- }
-
-
- 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();
- }
-
-
- 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();
- }
-
-
- 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:
-
- 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。
-
BOOL
-
-
-
-
int
float
BOOL
enum
)
-
return
-
效果:

一个小巧的C++Log输出到文件类 (转)
原文:http://www.cnblogs.com/mazhenyu/p/4139352.html