Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect ostream to Boost Log library

Tags:

c++

boost

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))).

like image 750
Hernan Villanueva Avatar asked Sep 27 '22 13:09

Hernan Villanueva


1 Answers

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);
like image 107
Hernan Villanueva Avatar answered Sep 30 '22 08:09

Hernan Villanueva