Managing a log stream in C++ in a cout-like notation

Posted by Andry on Stack Overflow See other posts from Stack Overflow or by Andry
Published on 2010-12-30T13:49:37Z Indexed on 2010/12/30 13:54 UTC
Read the original article Hit count: 188

Hello! I have a class in c++ in order to write log files for an application of mine. I have already built the class and it works, it is something like this:

class Logger {
   std::string _filename;
public: 
   void print(std::string tobeprinted);
}

Well, it is intuitive that, in order to print a line in the log file, for an object of Logger, it is simply necessary to do the following:

Logger mylogger("myfile.log");
mylogger.print(std::string("This is a log line"));

Well. Using a method approach is not the same as using a much better pattern like << is. I would like to do the following:

Logger mylogger("myfile.log");
mylogger << "This is a log line";

That's all. I suppose I must overload the << operator... But overloading using this signature (the classic one):

ostream& operator<<(ostream& output, const MyObj& o);

But I do not have a ostream... So, should I do as follows?

Logger& operator<<(Logger& output, const std::string& o);

Is this the right way? Thanks

© Stack Overflow or respective owner

Related posts about c++

Related posts about logging