I have a progress bar function that takes a std::ostream as a parameter. I have simplified it here for description purposes.
void someprogressbar(std::ostream & stream)
{
stream << "Hello";
}
I can't modify this function, as it is a third-party function. I call this function with either std::ostringstream myoss; someprogressbar(myoss)
or with someprogressbar(std::cout)
. The function prints some info in real time as my program progresses.
How can I redirect the output to the Boost Log library? I can do BOOST_LOG_TRIVIAL(debug) << "Hello"
, but can't do someprogressbar(BOOST_LOG_TRIVIAL(debug)))
.
In order to redirect output to the Boost logger through an ostream, I needed to create a sink using the Boost Iostreams library. Thanks @sehe for the hint!
I use C++11 in the following implementation:
#include <iosfwd>
#include <boost/iostreams/categories.hpp>
class Logger_Sink
{
public:
typedef char char_type;
typedef boost::iostreams::sink_tag category;
Logger_Sink() = default;
virtual
~Logger_Sink() = default;
virtual
std::streamsize
write(
char_type const * s,
std::streamsize n) = 0;
};
class cout_Sink: public Logger_Sink
{
public:
std::streamsize
write(
char_type const * s,
std::streamsize n)
{
BOOST_LOG_TRIVIAL(info) << std::string(s, n);
return n;
}
};
Then, I needed to use this sink to create an ostream:
#include <iostream>
#include <boost/iostreams/stream.hpp>
namespace io = boost::iostreams;
io::stream_buffer<cout_Sink> cout_buf((cout_Sink()));
std::ostream mycout(&cout_buf);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With