最近搞一個 C++ 項目的二次開發,沒玩過 C++,可謂寸步難行。本身寫個簡單的日誌類都被各類坑折磨。終於搞定了。html
參考了這篇博客,而且進一步簡化:https://www.cnblogs.com/DswCnblog/p/5459539.htmlios
代碼以下:app
#pragma once #include <ctime> #include <iostream> #include <fstream> #include <direct.h> using namespace std; #ifndef __EASYLOG_PIPI_0813 #define __EASYLOG_PIPI_0813 class EasyLog { public: static void Write(std::string log) { try { std::ofstream ofs; time_t t = time(0); char tmp[64]; strftime(tmp, sizeof(tmp), "[%Y-%m-%d %X]", localtime(&t)); ofs.open("D:\\PipeLog.log", std::ofstream::app); ofs << tmp << " - "; ofs.write(log.c_str(), log.size()); ofs << std::endl; ofs.close(); } catch(...) { } } }; #endif
使用也很簡單:spa
EasyLog::Write("hello Log");
發個博客記一下,免得忘了。日誌