/**
* 用于输出log文件的类.
*/
#ifndef LOG_H
#define LOG_H
//log文件路径
#define LOG_FILE_NAME "C:\\log.txt"
//启用开关
#define LOG_ENABLE 1
#include <fstream>
#include <string>
#include <ctime>
using namespace std;
class CLog
{
public:
//输出一个内容,可以是字符串(ascii)、整数、浮点数、布尔、枚举
//格式为:[2011-11-11 11:11:11] aaaaaaa并换行
template <class T>
static void WriteLog(T text)
{
if(LOG_ENABLE == 0)
{
return;
}
ofstream fout(LOG_FILE_NAME,ios::app);
fout.seekp(ios::end);
fout << GetSystemTime() << text <<endl;
fout.close();
}
//输出一行当前函数开始的标志,宏需要传入__FUNCTION__
template <class T>
static void WriteFuncBegin(T x)
{
if(LOG_ENABLE == 0)
{
return;
}
ofstream fout(LOG_FILE_NAME,ios::app);
fout.seekp(ios::end);
fout << GetSystemTime() << "--------------------"<<x<<" Begin--------------------" <<endl;
fout.close();
}
//输出一行当前函数结束的标志,宏需要传入__FUNCTION__
template <class T>
static void WriteFuncEnd(T x)
{
if(LOG_ENABLE == 0)
{
return;
}
ofstream fout(LOG_FILE_NAME,ios::app);
fout.seekp(ios::end);
fout << GetSystemTime() << "--------------------"<<x<<" Begin--------------------" <<endl;
fout.close();
}
//输出Unicode字符串
static void WriteLogW(WCHAR* szContent)
{
if (LOG_ENABLE == 0)
{
return;
}
LPWSTR lpwzFile = TEXT(LOG_FILE_NAME);
HANDLE hOpenFile = (HANDLE)CreateFile(lpwzFile,GENERIC_WRITE,0,NULL,OPEN_ALWAYS,NULL,NULL);//OPEN_EXISTING
if (INVALID_HANDLE_VALUE == hOpenFile) {
hOpenFile = NULL;
return ;
}
DWORD num;
WORD nextlineFlag = 0x0A0D;
SetFilePointer(hOpenFile,0,0,FILE_END);
if(GetFileSizeFromNameW(lpwzFile) == 0){
WORD unicodeFlag= 0xFEFF;
WriteFile(hOpenFile,&unicodeFlag,sizeof(WORD),&num,NULL);
}
WriteFile(hOpenFile,szContent,2*wcslen(szContent),&num,NULL);
WriteFile(hOpenFile,L"\r\n",2*sizeof(WCHAR),&num,NULL);
ZeroMemory(hOpenFile,0,0,FILE_END);
CloseHandle(hOpenFile);
}
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;
}
//供WriteLogW使用
static DWORD WINAPI GetFileSizeFromNameW(IN LPWSTR lpwzFile)
{
WIN32_FILE_ATTRIBUTE_DATA wfad;
if ( GetFileAttributesExW(lpwzFile, GetFileExInfoStandard, &wfad) )
{
return wfad.nFileSizeLow;
}
return 0;
}
};
#define LOG(x) CLog::WriteLog(x); //括号内可以是字符串(ascii)、整数、浮点数、bool等
#define WLOG(x) CLog::WriteLogW(x); //如果要输出Unicode字符串用这个宏
#define LOG_FUNC LOG(__FUNCTION__) //输出当前所在函数名
#define LOG_LINE LOG(__LINE__) //输出当前行号
#define LOG_FUNC_BEGIN(x) CLog::WriteFuncBegin(x); //形式如:[时间]"------------FuncName Begin------------"
#define LOG_FUNC_END(x) CLog::WriteFuncEnd(x); //形式如:[时间]"------------FuncName End------------"
#endif
评论5
最新资源