class MyLog
{
public:
MyLog();
~MyLog();
public:
bool Init();
bool Init(const string &logDir, const string &fileName,
const string &strSuffix = ".log");
bool Deinit();
bool WriteLog(const string &logInfo);
string GetCurrTime();
string GetCurrDate();
private:
//CStdioFile *m_sf;
std::ofstream ofs;
};
//日志操作类
MyLog::MyLog()
{
//m_sf = NULL;
}
MyLog::~MyLog()
{
Deinit();
}
bool MyLog::Init()
{
string logPath = GetAppPath()+"\\logs";
bool bRes=Init(logPath,"MMail_error",".log");
return bRes;
}
bool MyLog::Init(const string &logDir, const string &filePreName,const string &strSuffix)
{
//判断指定目录是否存在,如果不存在,创建之
/*BOOL bExist = PathIsDirectory(logDir.c_str());
if(!bExist)*/
CreateDirectory(logDir.c_str(),NULL);
string filePath = logDir+"\\"+filePreName+"_"+GetCurrDate()+strSuffix;
ofs.open (filePath.c_str(),ios_base::out|ios_base::app);
if(ofs.is_open())
return true;
else
return false;
}
bool MyLog::Deinit()
{
if(ofs.is_open())
{
ofs.flush();
ofs.close();
}
return true;
}
bool MyLog::WriteLog(const string &logInfo)
{
if(ofs)
{
ofs <<GetCurrTime()<<" error:"<< logInfo << std::endl;
ofs.flush();
return true;
}
else
return false;
}
// 获得当前时间,来记录日志中错误出现的时间
string MyLog::GetCurrTime()
{
SYSTEMTIME SysTime;
GetLocalTime(&SysTime);
char tArr[256];
memset(tArr,0,sizeof(tArr));
sprintf_s(tArr,"%0.4d-%0.2d-%0.2d %0.2d:%0.2d:%0.2d.%0.3d",SysTime.wYear, SysTime.wMonth, SysTime.wDay, SysTime.wHour, SysTime.wMinute,
SysTime.wSecond, SysTime.wMilliseconds);
return string(tArr);
}
//用来创建日志文件用的,格式:"日志文件名+日期+.log"
string MyLog::GetCurrDate()
{
SYSTEMTIME SysTime;
GetLocalTime(&SysTime);
char tArr[256];
memset(tArr,0,sizeof(tArr));
sprintf_s(tArr,"%0.4d-%0.2d-%0.2d",SysTime.wYear, SysTime.wMonth, SysTime.wDay);
return string(tArr);
}