C++ Log日志类轻量级支持格式化输出变量实现代码
2019/7/10 22:27:51
本文主要是介绍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日志类轻量级支持格式化输出变量实现代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升