用C/C++编写日志文件

Writing a Log file in C/C++

本文关键字:日志 文件 C++      更新时间:2023-10-16

我想用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("This is log message");写入文件(或附加现有文件(

/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可以很好地解决这个问题。

#include<string>
#include <fstream>
inline std::string getCurrentDateTime( std::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  std::string(buf);
};
inline void Logger(std::string logMsg){
    std::string filePath = "./log_"+getCurrentDateTime("date")+".txt";
    std::string now = getCurrentDateTime("now");
    std::ofstream ofs(filePath.c_str(), std::ios_base::out | std::ios_base::app );
    ofs << now << 't' << logMsg << 'n';
    ofs.close();
}

例如:

Logger("JAMLEE: ---------| start VT_SETMODE");