最近搞一個 C++ 項目的二次開發,沒玩過 C++,可謂步履維艱。自己寫個簡單的日志類都被各種坑折磨。終於搞定了。
參考了這篇博客,並且進一步簡化:https://www.cnblogs.com/DswCnblog/p/5459539.html
代碼如下:
#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
使用也很簡單:
EasyLog::Write("hello Log");
發個博客記一下,省得忘了。