I want to create a generic log file which I can easily reuse in multiple files. Also, I want to be able to use the versatile std::cout
so I can easily write formatted text (as oppose to create my own write function which may write only strings and which can probably never be that versatile).
Definition
#include <fstream>
class logstream :
public std::ofstream
{
public:
logstream();
~logstream();
protected:
std::streambuf *psbuf, *backup;
std::ofstream filestr;
};
Implementation
logstream::logstream()
{
filestr.open("test_streaming.txt", std::ofstream::app);
backup = std::clog.rdbuf(); // back up cout's streambuf
psbuf = filestr.rdbuf(); // get file's streambuf
std::clog.rdbuf(psbuf); // assign streambuf to cout
}
logstream::~logstream()
{
std::clog.rdbuf(backup); // restore cout's original streambuf
filestr.close();
}
Usage:
void CExportDlg::OnBnClickedButtonLog()
{
logstream log; // redirects clog and restores it when it goes out of scope
std::clog << "hello this goes into log file" << std::endl;
std::clog << "And I can readily write intetgers like " << 5 << "this one" << std::endl;
}
In reality, I have put the line logstream log
in the main application class so now I can use only std:clog()
anywhere in the application and output goes to a log file. But can this be improved?
What if I want to create multiple log files for different purposes? Is there a way I can access clog()
(or cout()
) by the object so it goes into that object only, like log.clog()
?