nikhil
nikhil

Reputation: 9363

Implement Minimal logging program in 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?

Upvotes: 0

Views: 655

Answers (2)

andand
andand

Reputation: 17487

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;
}

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.

Upvotes: 1

Ghita
Ghita

Reputation: 4505

Have a look at the implementation of this simple logging system from Dr Dobs article: http://drdobbs.com/cpp/201804215

It is template based, has logging levels (that don't incur any overhead at run-time if not needed) and is small

Upvotes: 0

Related Questions