How to redirect ostream to Boost Log library

I have a run function that takes a std :: ostream parameter as a parameter. I simplified it here for description purposes.

void someprogressbar(std::ostream & stream)
{
    stream << "Hello";
}

I cannot change this function, since it is a third-party function. I call this function either with std::ostringstream myoss; someprogressbar(myoss)or with someprogressbar(std::cout). The function prints some information in real time as my program progresses.

How to redirect output to Boost Log library? I can do BOOST_LOG_TRIVIAL(debug) << "Hello", but I can not do someprogressbar(BOOST_LOG_TRIVIAL(debug))).

+4
source share
1 answer

To redirect the output to the Boost logger via ostream, I needed to create a receiver using the Boost Iostreams library. Thanks @sehe for the tip!

++ 11 :

#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;
    }
};

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);
+3

All Articles