C ++ Logging Methods

I am reorganizing my C ++ application. Before I used a macro like

LOG("something interesting") // 1 LOG("something ended") // 2 LOG("foo: " << bar) // 3 

Now my idea was to write a Log class:

 Log(std::string _init_message): init_message(_init_message) { PrintLogLine(init_message + " ...");} ~Log() { PrintLogLine(init_message + " done.");} 

to get "automatic" logging of certain actions (i.e. when they start, stop + additional timings, etc.) when I use it like

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

Where I struggle is the definition of a way to make it work in case 3). In Java, I could use a method that takes a single String argument, since the compiler takes care of automatically building the string. What features do I have in C ++?

Can I make it work so that I can use it as one of the options?

  // in "do stuff" log("foo:" + bar); // OR log << "foo:" << bar; 
+4
source share
4 answers

As I mentioned in the comments, you can use Boost.Format. It also helps with the problem of converting int-to-string, etc. However, it can be a bit verbose - to avoid calling .str() to invoke the std::string constructor, you can make one that takes boost::format directly.

 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) 

See the Boost.Format documentation for more details .

+3
source

Two immediate possibilities come to mind. The first is to use std :: string appending:

 Log log(std::string("foo:") + bar); 

The second is to create additional log constructors that take additional parameters:

 Log log("foo:", bar); 
+1
source

You really should consider using Boost.Log for logging. Logging can be a daunting task; It is useful to get a fully formed implementation.

0
source

You can create a logging class that inherits from 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; }; 

Now you can record the output as,

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

In endf (ostream & s), you can translate ostream to Mstream and call Write (). In Write (), you format the output and print it to the console or to a file.

0
source

All Articles