简单的日志操作

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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值