c++中自定义日志的方法

Ways for custom logging in C++

本文关键字:方法 日志 自定义 c++      更新时间:2023-10-16

我正在重构我的一个c++应用程序。在我使用像

这样的宏之前
LOG("something interesting") // 1
LOG("something ended")       // 2
LOG("foo: " << bar)          // 3

我现在的想法是写一个Log类,像这样:

Log(std::string _init_message):
    init_message(_init_message)
{   PrintLogLine(init_message + "   ...");}
~Log() 
{   PrintLogLine(init_message + " done.");}
当我像 那样使用它时,

获得特定动作的"自动"记录(即当它们开始,停止+额外的计时等)。

void ActionXYZ() {
   Log log("xyz");
   // do stuff
}

我正在努力的地方是在定义一种方法,使它的工作情况3)。在Java中,我可以使用一个方法,它需要一个String参数,因为编译器会自动处理字符串构建。c++中有哪些可能性?

我可以使它工作,以便我可以像使用一个选项一样使用它吗?

 // in "do stuff"
 log("foo:" + bar); // OR
 log << "foo:" << bar;

正如我在评论中提到的,您可以使用Boost.Format。它还有助于解决int-to-string转换等问题。这可能会变得有点冗长,但是—为了避免调用.str()来调用std::string构造函数,您可以创建一个直接接受boost::format的构造函数。

Log log(boost::format("foo %1% bar") % 42); // with Log(boost::format)
Log log((boost::format("foo %1% bar") % 42).str()); // with only Log(std::string)

参考Boost。

我立刻想到了两种可能。第一种是利用std::string附加:

Log log(std::string("foo:") + bar);
第二种是创建更多的log构造函数,这些构造函数接受额外的形参:
Log log("foo:", bar);

您确实应该考虑使用Boost.Log进行日志记录。日志记录可能是一件复杂的事情;得到一个完全形成的实现是很有用的。

你可以创建一个从std::strstream继承的日志类。

class Mstream : public std::strstream
{
  public:
  Mstream() : std::strstream(Buffer = new char[BUFLEN], BUFLEN, ios::out);
  ostream& endf(ostream& s);
  void Write();
  private:
  char* Buffer;
};

现在您可以将输出记录为

Mstream m; 
m <<"Foo"<<s<<endf;

endf (ostream&5)你可以将ostream转换为Mstream并调用Write()。在Write()中,格式化输出并将其打印到控制台或文件中。