在c ++中实现最小日志记录程序

在c ++中实现最小日志记录程序

问题描述:

我正在为数据库引擎开发一个基于磁盘的树,我喜欢为我的程序维护一个日志文件。我基本上需要两种功能从日志程序。它必须允许我将消息记录到日志文件中,并且还必须将任何我将其作为参数传递到日志文件中的变量。我只需要这两个功能。第一个是相当简单的实现,但我发现很难实现第二个。我想传递任何数量的任何类型的参数到日志程序,以将其写入日志文件。我试图实现第二个使用可变参数函数,但问题是我们必须知道正在传递的变量的类型。我相信必须有一些方法来做到这一点。

I am developing a disk based tree for a database engine and i like to maintain a log file for my program. I basically need two kinds of functionality from the log program. It must allow me to log a message into a log file and also must write any variable that i pass it as an argument into the log file. I need only these two functions. The first is fairly simple to achieve but i am finding it hard to achieve the second one. I want to pass any number of arguments of any type to the log program to write it into the log file. I tried to achieve the second one using variable argument function but the problem is we must know the type of the variables that are being passed. I am sure there must be some way to do this. Can anyone enlighten me on this?

log4C ++ 提供您正在寻找的功能。

log4C++ provides the functionality you're looking for.

如果这是一个太重的重量,你可以做一些事情类似使用模板。类似:

If that is a little too heavy weight for you you can do something similar using templates. Something like:

class log
{
private:
  std::ostream& stream;

public:
  log(std::ostream& src) : stream(src) {}

...

  std::ostream& getStream() { return stream; }
}

template <typename T> log& operator<<(log&, const T& val)
{
  log.getStream() << val;
  return log;
}

这里 log :: stream std :: ostream 您为输出到文件,控制台或其他任何内容定义的实例。您可以通过区分不同类型的日志记录事件,使其成为一名鸽友。

Here log::stream is some std::ostream instance you defined for output to a file, to a console or whatever. You can make it a bit fancier by distinguishing between different types of logging events.