I have created a derived class of basic_streambuf so that it would write my messages to syslog and to cerr. It works great.
Now I am trying to move the redirection of clog's output to my class into the constructor and restoring it in the destructor. Now, my redirection only worked once (inside the constructor) and only once.
I am a new C++ programmer and I'm not sure where I have gone wrong.
I am using g++ and c++11 features.
Here's my class:
class Log
: public std::basic_streambuf<char, std::char_traits<char> >
{
public:
explicit Log(std::string& ident, logFacility facility);
virtual ~Log();
protected:
int sync();
int overflow(int c);
private: // routines
friend std::ostream& operator<< (std::ostream& os, const logPriority& priority);
private: // data
std::string buffer_;
logPriority priority_;
std::streambuf* origLog_;
};
And the constructor and destructor:
Log::Log(std::string& ident, logFacility facility)
: std::basic_streambuf<char, std::char_traits<char>>{}
, buffer_{}
, priority_{logPriority::debug}
, origLog_{std::clog.rdbuf()}
{
openlog(ident.c_str(), LOG_PID, static_cast<int>(facility));
std::clog.rdbuf(this);
clog << "Log " << this << " constructor; ident=" << ident << ", facility=" << static_cast<int>(facility) << endl;
}
Log::~Log()
{
clog << "Log " << this << " destructor" << endl;
std::clog.rdbuf(origLog_);
closelog();
}
Aucun commentaire:
Enregistrer un commentaire