Clone clog output stream with C++

48 Views Asked by At

In addition to cout, cerr and clog I want to have another output stream that is doing and manageable the same as clog, maybe called debg. I would like to use it for a library for its own (error/debug) output without affecting the standard output streams. They may be used by the program that is using the library.

For example I want to

// disable debg output
debg.setstate(std::ios_base::failbit);
// and enable it with
debg.clear();

Because these are system wide settings it should not also disable clog or one of the other default output streams.

I had a look at the different stream classes and some examples using them. The closest example I could find was to redirect the output stream. But that isn't what I need.

Is there a way to clone the clog output stream to have an additional output stream, maybe called debg, that do the same as clog, e.g. debg << "alternative stream used" << std::endl; that will also output to stderr?

1

There are 1 best solutions below

1
Stephen M. Webb On

What you want to do is create an object of type std::basic_ostream called debg and give it a custom streambuf derived from std::basic_streambuf that clones its output to the same streambuf as std::clog::rdbuf() with whatever customization your special stream requires, if any.