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

时间:2021-11-17 13:23:36

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#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;
}

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