我想用 C++ 写一个日志文件。我正在处理某些事情,因此我需要维护我处理的事情的属性的日志,以便我可以恢复到这个日志文件来查看我特别感兴趣的任何东西的属性……有人可以帮我吗在实现这一目标? 原文由 noddy 发布,翻译遵循 CC BY-SA 4.0 许可协议
这很方便;只需插入,例如,从程序中的任何位置调用的一些通用头文件(更好的方法是用这些函数形成一个类) inline string getCurrentDateTime( string s ){ time_t now = time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); if(s=="now") strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct); else if(s=="date") strftime(buf, sizeof(buf), "%Y-%m-%d", &tstruct); return string(buf); }; inline void Logger( string logMsg ){ string filePath = "/somedir/log_"+getCurrentDateTime("date")+".txt"; string now = getCurrentDateTime("now"); ofstream ofs(filePath.c_str(), std::ios_base::out | std::ios_base::app ); ofs << now << '\t' << logMsg << '\n'; ofs.close(); } 用法: Logger("This is log message"); 写入文件(或附加现有文件) /somedir/log_2017-10-20.txt 内容: 2017-10-20 09:50:59 This is log message 原文由 Streamsoup 发布,翻译遵循 CC BY-SA 4.0 许可协议
这很方便;只需插入,例如,从程序中的任何位置调用的一些通用头文件(更好的方法是用这些函数形成一个类)
用法:
Logger("This is log message");
写入文件(或附加现有文件)内容: