[英]Writing a Log file in C/C++
我想用 C++ 写一个日志文件。 我正在处理某些事情,因此我需要维护我处理的事情的属性日志,以便我可以恢复到此日志文件以查看我特别感兴趣的任何内容的属性......有人可以帮助我吗在实现这一目标?
记录日志的标准方法(根据我的经验)是使用 stdout 或 stderr 流。 在 C++ 中使用这些你需要包含 iostream,并使用如下:
#include <iostream>
int main(int argc, char* argv[])
{
using std::cout;
using std::cerr;
using std::endl;
cout << "Output message" << endl;
cerr << "Error message" << endl;
}
然而,这只能实现打印到那些通常在终端结束的输出。 如果您想使用这些标准流方法(它们非常易读)输出到文件,那么您必须以某种方式重定向输出。 一种方法是使用 cstdio 提供的freopen
函数。 它的作用是打开一个文件,并将给定的流移动到该文件。 有关文档,请参见此处。 一个例子是:
#include <iostream>
#include <cstdio>
int main(int argc, char* argv[])
{
using namespace std;
freopen( "output.txt", "w", stdout );
freopen( "error.txt", "w", stderr );
cout << "Output message" << endl;
cerr << "Error message" << endl;
}
(我已改为using namespace std;
只是为了简洁起见。)
您正在将标准输出流stdout
(由cout
)移动到 output.txt(在写入模式下),并且您正在将stderr
(由cerr
)移动到 error.txt 也在写入模式下。
希望这能解决问题。
这非常方便,只需插入一些通用头文件即可从程序中的任何位置调用(更好的方法是使用这些函数形成一个类)
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("这是日志消息"); 写入文件(或追加现有文件)
/somedir/log_2017-10-20.txt
内容:
2017-10-20 09:50:59 This is log message
您尝试做的事情太深入,无法提供有关堆栈溢出的完整解决方案。 您可以做的是查看您选择的日志库的文档。 就我而言,这是Boost.Log
,它是Boost C++ 库的日志库,其文档可在 此处找到。
它在我刚刚链接到的页面底部指出
尽管该库已通过审核并被临时接受,但它不是 Boost 库集合的官方部分。 审查结果可在此处获得。
所以你会怎么做。
为什么不使用许多可用的日志框架之一,比如Apache log4cxx ? 我建议这样做而不是尝试自己动手 - 为什么要重新发明轮子?
您可能还想考虑https://github.com/johnwbyrd/logog 。 它是一个面向性能的 C++ 日志系统。 但是,如果这对您的项目来说有点过于紧张,那么好的旧 cerr 和 cout 可以很好地解决这个问题。
非常感谢所有的回复...我认为我正在寻找的答案是,甚至UTF8中的日志文件的格式就像一个txt文件所以c在编写带有简单文件的那种文件时没有问题写它提供。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.