我喜欢从std::ostream派生我的日志类,所以我得到了所有流的好处。诀窍是将所有特定于应用程序的代码放在相关的streambuf类中。考虑一下这个工作示例。要修改它以满足您的需求,只需重写
CLogBuf::sync()
,就像这样:
int sync() {
renderer->renderText(50, 50, color, "%s", str());
str("");
return false;
}
例子:
#include <iostream>
#include <sstream>
class CLogger : public std::ostream {
private:
class CLogBuf : public std::stringbuf {
private:
// or whatever you need for your application
std::string m_marker;
public:
CLogBuf(const std::string& marker) : m_marker(marker) { }
~CLogBuf() { pubsync(); }
int sync() { std::cout << m_marker << ": " << str(); str(""); return !std::cout; }
};
public:
// Other constructors could specify filename, etc
// just remember to pass whatever you need to CLogBuf
CLogger(const std::string& marker) : std::ostream(new CLogBuf(marker)) {}
~CLogger() { delete rdbuf(); }
};
int main()
{
CLogger hi("hello");
CLogger bye("goodbye");
hi << "hello, world" << std::endl;
hi << "Oops, forgot to flush.\n";
bye << "goodbye, cruel world\n" << std::flush;
bye << "Cough, cough.\n";
}