C++日志记录类实例解析
本文所述实例是从一个RedHat开源项目里面扒出来的,非常实用!读者还可以根据自身需求加以修改!完整源码如下:
Log.h文件部分:
#ifndef__LOG_H__
#define__LOG_H__
#include<stdio.h>
#include<tchar.h>
#include<crtdbg.h>
#include<windows.h>
#include<time.h>
#include<sys/timeb.h>
classCLog{
public:
~CLog();
staticCLog*get(TCHAR*path=NULL);
voidprintf(constchar*format,...);
private:
CLog(FILE*handle);
private:
staticCLog*_log;
FILE*_handle;
};
enum{
LOG_DEBUG,
LOG_INFO,
LOG_WARN,
LOG_ERROR,
LOG_FATAL
};
#ifdef_DEBUG
staticunsignedintlog_level=LOG_DEBUG;
#else
staticunsignedintlog_level=LOG_INFO;
#endif
#definePRINT_LINE(type,format,datetime,ms,...)\
printf("%lu::%s::%s,%.3d::%s::"format"\n",GetCurrentThreadId(),type,datetime,ms,\
__FUNCTION__,##__VA_ARGS__);
#defineLOG(type,format,...)do{\
if(type>=log_level&&type<=LOG_FATAL){\
CLog*log=CLog::get();\
constchar*type_as_char[]={"DEBUG","INFO","WARN","ERROR","FATAL"};\
struct_timebnow;\
structtmtoday;\
chardatetime_str[20];\
_ftime_s(&now);\
localtime_s(&today,&now.time);\
strftime(datetime_str,20,"%Y-%m-%d%H:%M:%S",&today);\
if(log){\
log->PRINT_LINE(type_as_char[type],format,datetime_str,now.millitm,##__VA_ARGS__);\
}else{\
PRINT_LINE(type_as_char[type],format,datetime_str,now.millitm,##__VA_ARGS__);\
}\
}\
}while(0)
#definelog_printf(format,...)LOG(LOG_INFO,format,##__VA_ARGS__)
#defineLOG_INFO(format,...)LOG(LOG_INFO,format,##__VA_ARGS__)
#defineLOG_WARN(format,...)LOG(LOG_WARN,format,##__VA_ARGS__)
#defineLOG_ERROR(format,...)LOG(LOG_ERROR,format,##__VA_ARGS__)
#defineDBGLEVEL1000
#defineDBG(level,format,...)do{\
if(level<=DBGLEVEL){\
LOG(LOG_DEBUG,format,##__VA_ARGS__);\
}\
}while(0)
#defineASSERT(x)_ASSERTE(x)
#endif
Log.cpp文件部分:
#include"Log.h"
#include<stdio.h>
#include<stdarg.h>
#include<share.h>
#defineLOG_ROLL_SIZE(1024*1024)
CLog*CLog::_log=NULL;
CLog::CLog(FILE*handle)
:_handle(handle)
{
_log=this;
}
CLog::~CLog()
{
if(_log&&_handle){
fclose(_handle);
_log=NULL;
}
}
CLog*CLog::get(char*path)
{
if(_log){
return_log;
}
if(!path)
{
path="dll.log";
}
DWORDsize=0;
HANDLEfile=CreateFile(path,GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,
NULL);
if(file!=INVALID_HANDLE_VALUE){
size=GetFileSize(file,NULL);
CloseHandle(file);
}
if(size!=INVALID_FILE_SIZE&&size>LOG_ROLL_SIZE){
TCHARroll_path[MAX_PATH];
sprintf(roll_path,"%s.1",path);
if(!MoveFileEx(path,roll_path,MOVEFILE_REPLACE_EXISTING)){
returnNULL;
}
}
FILE*handle=fopen(path,"a+");
if(!handle){
returnNULL;
}
_log=newCLog(handle);
return_log;
}
voidCLog::printf(constchar*format,...)
{
va_listargs;
va_start(args,format);
vfprintf(_handle,format,args);
va_end(args);
fflush(_handle);
}