I'm working on a logger class in C++ that has the following syntax:
Logger log("mylog.txt");
log << "a string" << " " << 1 << " " << 6.2 << "\n";
And it prints: a string 1 6.2
This is what my class looks like:
class Logger
{
private:
unique_ptr<ofstream> m_pOutStream;
public:
Logger(std::string sFile) : m_pOutStream(new ofstream(sFile, std::ios::app))
{}
template<typename T>
Logger& operator<< (const T& data)
{
*m_pOutStream << data;
return *this;
}
};
It works fine, but I would also like to add a prefix to every line (e.g. a timestamp). So when I write:
Logger log("mylog.txt");
log << "a string" << " " << 1 << " " << 6.2 << "\n";
I want something like this to be displayed:
11:59:12 a string 1 6.2
I have thought of a couple of solutions:
1.Keep every input stored in a list/stream and use an extra function to print and then clear the list/stream:
Logger log("mylog.txt");
log << "a string" << " " << 1 << " " << 6.2 << "\n";
log.logd(); // <- this prints and then clears the internal stream/list.
2.Keep every input stored in a list/stream and print everything after a "new line" character is detected. And clear the internal stream/list after that.
Both of these solutions are nice but I'd prefer to use them only as a last resort.
Is there any other/better way to achieve what I want?