C++简单实现Log日志类轻量级支持格式化输出变量
CLog 头 代码很简单 如果需要的直接Ctrl+C ----Ctrl+V 即可
1 #ifndef __CLOG__ 2 #define __CLOG__ 3 #include <windows.h> 4 #include <string> 5 #include <fstream> 6 #include <tchar.h> 7 #include <ctime> 8 class CLog 9 { 10 public: 11 CLog(); 12 CLog(const std::string LogFile); 13 ~CLog(); 14 template <class T> 15 static void WriteLog(T x); 16 //支持格式化输出多参数输出 17 static void WriteLogFormat(const char* format, ...); 18 private: 19 static std::string GetFilePath(); 20 std::string m_LogFilePath; 21 static std::string GetSystemTimes(); 22 static bool IsPathExist(const std::string FilePath); 23 }; 24 //支持输出int double 文本 25 template <class T> void CLog::WriteLog(T x) 26 { 27 std::fstream of(GetFilePath(), std::ios::app); 28 if (!of.is_open())return; 29 of.seekp(std::ios::end); //设置文件指针到文件尾部 30 of << GetSystemTimes() <<_T("line: ")<<__LINE__<<_T(" value: ")<< x << std::endl; 31 of.close(); //关闭文件; 32 } 33 #endif
CLog.cpp
1 #include "Log.h" 2 CLog::CLog() 3 :m_LogFilePath("") 4 { 5 m_LogFilePath = GetFilePath(); 6 if (IsPathExist(m_LogFilePath)) 7 DeleteFile(m_LogFilePath.c_str()); 8 9 } 10 11 CLog::CLog(const std::string LogFile) 12 :m_LogFilePath(LogFile) 13 { 14 if (IsPathExist(m_LogFilePath)) 15 DeleteFile(m_LogFilePath.c_str()); 16 } 17 18 CLog::~CLog() 19 { 20 } 21 22 void CLog::WriteLogFormat(const char* format, ...) 23 { 24 va_list arglist; 25 std::string strArgData; 26 char szBuffer[0x1024]; 27 ZeroMemory(szBuffer, 0x1024); 28 va_start(arglist, format); 29 vsprintf_s(szBuffer, format, arglist); 30 va_end(arglist); 31 strArgData = szBuffer; 32 std::fstream of(GetFilePath(), std::ios::app); 33 if (!of.is_open())return; 34 of << GetSystemTimes() << " Line: " << __LINE__ << " Value: " << strArgData << std::endl; 35 of.close(); 36 } 37 38 std::string CLog::GetFilePath() 39 { 40 std::string FlieTmp; 41 TCHAR szPath[MAX_PATH]; 42 ::ZeroMemory(szPath, MAX_PATH); 43 if (!::GetCurrentDirectory(MAX_PATH, szPath))return FlieTmp; 44 FlieTmp = szPath; 45 FlieTmp += _T("\\log.txt"); 46 return FlieTmp; 47 } 48 49 std::string CLog::GetSystemTimes() 50 { 51 time_t Time; 52 CHAR strTime[MAX_PATH]; 53 ZeroMemory(strTime, MAX_PATH); 54 time(&Time); 55 tm t; 56 localtime_s(&t, &Time); 57 strftime(strTime, 100, _T("%Y-%m-%d %H:%M:%S "), &t); 58 std::string strTimes = strTime; 59 return strTimes; 60 } 61 62 bool CLog::IsPathExist(const std::string FilePath) 63 { 64 DWORD dwAttribute = ::GetFileAttributes(FilePath.c_str()); 65 return dwAttribute != INVALID_FILE_ATTRIBUTES; 66 }