0

I use boost.log in my multi-thread project, but I don't need a thread-safe version logger because I already make codes runs in thread-safe manner.

If use non thread safe logger, I need to make the logger object be thread_local: each thread has its own logger object. But the object is hidden behind boost.log's API: to create a logger object, user can not define the object as type obj; Its creating done by macro like BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULTI and get by logging::core::get() . I can not just write like:

thread_local boost::core::logger logger_obj;

How to do this?

jean
  • 2,825
  • 2
  • 35
  • 72

1 Answers1

0

Yes, you can create loggers in thread-local storage, almost exactly as you wrote:

thread_local boost::log::sources::logger logger_obj;

The logging core, however, cannot be made thread-local because it contains references to sinks and is used by all loggers from all threads concurrently.

Andrey Semashev
  • 10,046
  • 1
  • 17
  • 27
  • I got mix up logging core and logger. If logging core must be global singleton, how many times of thread synchronization can saved by making logger be thread local? Because sink still can not be unlocked because it is add to logging core, I guess the saving is very tiny, does it? – jean Dec 28 '15 at 07:55
  • It depends on how much thread contention there is on the logger in question. As for the logging core, it is able to process log records in parallel in some cases - especially when there are more than one sink. If there is one (synchronous) sink and lots of records are passed to it then it may become a bottleneck. – Andrey Semashev Dec 28 '15 at 11:28
  • Want to ask another question: What is the difference between sink thread safety with logging core thread safety? Add unlocked_sink to mt logging core is a incorrect usage? – jean Dec 29 '15 at 10:27
  • 1
    The logging core is always thread-safe, unless you build a single-threaded version of Boost.Log. `unlocked_sink` frontend can be used when the backend does not require thread synchronization (most of the backends provided by Boost.Log do). Sinks have to be thread-safe because any thread that performs logging in the app can access them. Loggers are more fine grained and can be used so that only one thread has access to a given logger, in which case you can avoid the overhead of locking. When multiple threads use one logger, that logger has to be `_mt`. – Andrey Semashev Dec 30 '15 at 09:51
  • So Boost.Log provided backends does an requirement on its frontends, if the backends doesn't need thread sync, it can use an unlocked_sink to be its frontend, or else it must use async or sync frontends sink. Does boost.log doc list this info? How user knows which backends needs thread sync or not? Or there is a generic rule? – jean Dec 30 '15 at 10:57
  • The requirements are documented by the code. Backends won't compile with frontends that do not fulfill requirements. – Andrey Semashev Dec 30 '15 at 15:36