• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C++ Log日志类轻量级支持格式化输出变量实现代码

c++ 搞代码 4年前 (2022-01-06) 33次浏览 已收录 0个评论

这篇文章主要介绍了C++ Log日志类轻量级支持格式化输出变量实现代码,需要的朋友可以参考下

CLog 头 代码很简单 如果需要的直接Ctrl+C —-Ctrl+V 即可

 #ifndef __CLOG__ #define __CLOG__ #include  #include  #include  #include  #include  class CLog { public: CLog(); CLog(const std::string LogFile); ~CLog(); template  static void WriteLog(T x); //支持格式化输出多参数输出 static void WriteLogFormat(const char* format, ...); private: static std::string GetFilePath(); std::string m_LogFilePath; static std::string GetSystemTimes(); static bool IsPathExist(const std::string FilePath); }; //支持输出int double 文本 template  void CLog::WriteLog(T x) { std::fstream of(GetFilePath(), std::ios::app); if (!of.is_open())return; of.seekp(std::ios::end);  //设置文件指针到文件尾部 of << GetSystemTimes() <<_T("line: ")<<__LINE__<<_T(" value: ")<< x << std::e<i style="color:transparent">来源gaodai$ma#com搞$代*码网</i>ndl; of.close();  //关闭文件; } #endif

CLog.cpp

 #include "Log.h" CLog::CLog() :m_LogFilePath("") { m_LogFilePath = GetFilePath(); if (IsPathExist(m_LogFilePath)) DeleteFile(m_LogFilePath.c_str()); } CLog::CLog(const std::string LogFile) :m_LogFilePath(LogFile) { if (IsPathExist(m_LogFilePath)) DeleteFile(m_LogFilePath.c_str()); } CLog::~CLog() { } void CLog::WriteLogFormat(const char* format, ...) { va_list arglist; std::string strArgData; char szBuffer[0x1024]; ZeroMemory(szBuffer, 0x1024); va_start(arglist, format); vsprintf_s(szBuffer, format, arglist); va_end(arglist); strArgData = szBuffer; std::fstream of(GetFilePath(), std::ios::app); if (!of.is_open())return; of << GetSystemTimes() << " Line: " << __LINE__ << " Value: " << strArgData << std::endl; of.close(); } std::string CLog::GetFilePath() { std::string FlieTmp; TCHAR szPath[MAX_PATH]; ::ZeroMemory(szPath, MAX_PATH); if (!::GetCurrentDirectory(MAX_PATH, szPath))return FlieTmp; FlieTmp = szPath; FlieTmp += _T("\\log.txt"); return FlieTmp; } std::string CLog::GetSystemTimes() { time_t Time; CHAR strTime[MAX_PATH]; ZeroMemory(strTime, MAX_PATH); time(&Time); tm t; localtime_s(&t, &Time); strftime(strTime, 100, _T("%Y-%m-%d %H:%M:%S "), &t); std::string strTimes = strTime; return strTimes; } bool CLog::IsPathExist(const std::string FilePath) { DWORD dwAttribute = ::GetFileAttributes(FilePath.c_str()); return dwAttribute != INVALID_FILE_ATTRIBUTES; }

好了这篇文章就介绍到这了,需要的朋友可以的参考一下。

以上就是C++ Log日志类轻量级支持格式化输出变量实现代码的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++ Log日志类轻量级支持格式化输出变量实现代码
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址