The C++ Log logging class lightweight supports formatting output variable implementation code

  • 2020-06-15 09:59:17
  • OfStack

CLog header code is very simple if you want it directly 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);
  // Support for formatted output multi-parameter output 
  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);
};
// Support the output int double  The text  
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);  // Sets the file pointer to the end of the file 
  of << GetSystemTimes() <<_T("line: ")<<__LINE__<<_T(" value: ")<< x << std::endl;
  of.close();  // Close the file; 
}
#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;
}

Well, this article has been introduced to this, the need for friends can refer to 1.


Related articles: