Search code examples
c++c++11boostboost-log

How to organize thread safe reading from boost log sink?


I looking for a correct way to safe get text data from boost::log::sinks::text_ostream_backend. I'm currently getting data only after everything was recorded in sink backend. I want get copy of backend internal buffer (m_ss) while data can still be produced.

using Logger = boost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level, std::string>;

class MyClass
{
  mutable std::mutex  m_mutex;
  mutable Logger      m_logger {boost::log::keywords::channel = "MyClass"};
  std::stringstream   m_ss;
  bool                m_completed {false};

public:
  void initLogging(const std::string& id)
  {
    using namespace boost::log;
    using Sink = sinks::synchronous_sink<sinks::text_ostream_backend>;

    auto backend = boost::make_shared<sinks::text_ostream_backend>();
    backend->add_stream(boost::shared_ptr<std::stringstream>(&m_ss, boost::null_deleter()));
    auto sink = boost::make_shared<Sink>(backend);
    sink->set_filter(expressions::has_attr<std::string>("ID") && expressions::attr<std::string>("ID") == id);

    core::get()->add_sink(sink);

    m_logger.add_attribute("ID", attributes::constant<std::string>(id));
  }

  void doSomething()
  {
    BOOST_LOG_SEV(logger, boost::log::trivial::severity_level::debug) << "TEST";
    BOOST_LOG_SEV(logger, boost::log::trivial::severity_level::error) << "TEST";

    // Stop write logs
    std::lock_guard<std::mutex> lock(m_mutex);
    m_completed = true;
  }

  void access()
  {
    std::lock_guard<std::mutex> lock(m_mutex);

    if (m_completed) {
      // Can read from stream
      useStreamData(m_ss.str());
    }
  }
};

Solution

  • If the stream is only accessed by the sink backend then the easiest way to synchronize access is to use locked_backend.

    auto locked_backend = sink->locked_backend();
    

    Here, the locked_backend object is a smart pointer, which locks the sink frontend and therefore prevents logging threads from accessing the backend and, consequently, the m_ss stream. You can use m_ss safely while locked_backend exists.

    There are also other ways to achieve this. For example, you can implement a custom sink backend or implement a stream buffer that would allow synchronized access to the accumulated data. There are a number of articles and blog posts about writing custom stream buffers, here is one example.