To redirect clog, I have been using this:
std::streambuf* clog_save;
std::ofstream ofs;
clog_save = std::clog.rdbuf();
ofs.open(LogFilename.c_str());
std::clog.rdbuf(ofs.rdbuf());
cout << "Test cout." << endl;
std::clog << "Test log." << endl;
std::clog.rdbuf(clog_save);
ofs.close();
However, it seems like bad "code reuse" practice to have to put this in every program I want to log. I tried to make this:
class Log
{
private:
std::streambuf* clog_save;
std::ofstream ofs;
public:
Log(const std::string &LogFilename)
{
clog_save = std::clog.rdbuf();
ofs.open(LogFilename.c_str());
std::clog.rdbuf(ofs.rdbuf());
}
~Log()
{
//reset the buffer
std::clog.rdbuf(clog_save);
ofs.close();
}
};
and do this to accomplish the same thing:
Log(LogFilename);
cout << "Test cout." << endl;
std::clog << "Test log." << endl;
but in this case "Test log." gets written to the screen instead of the file. This might have something to do with the scope of std::clog? I guess don't understand how these automatically instantiated classes (ie. cout, clog) work? Are they static or something?
Is there anyway to do this?
Thanks,
Dave