C++中Log日志类轻量级支持格式化输出变量的示例分析

发布时间:2021-07-30 14:25:57 作者:小新
来源:亿速云 阅读:125

这篇文章主要为大家展示了“C++中Log日志类轻量级支持格式化输出变量的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“C++中Log日志类轻量级支持格式化输出变量的示例分析”这篇文章吧。

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

#ifndef __CLOG__
#define __CLOG__
#include <windows.h>
#include <string>
#include <fstream>
#include <tchar.h>
#include <ctime>
class CLog
{
public:
  CLog();
  CLog(const std::string LogFile);
  ~CLog();
  template <class T>
  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 <class T> 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::endl;
  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日志类轻量级支持格式化输出变量的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. python中类的示例分析
  2. C++中变量和基本类型的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:dubbo中ConsumerContextFilter的作用是什么

下一篇:docker中dockerfile语法如何使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》