Boost::Log Safety of using the same backend with m

2019-08-23 22:34发布

Mine is not a real problem but more a correct usage question.

Foreword: I am using boost::log as logging facility and I am working on some libraries that will be shared among different applications and all may need different levels of logging. I came up with a setup where I have (or may have) specific channels and severity levels for each library, and a kind of factory that enables the library-using application to create the proper/desired sink(s) for the library, without the need of knowing the details of the library's channels and severity levels.

Now the real question: wanting to collect all the application's logs in some specific "places" (e.g. stdout, or some severity related files) I was planning to feed all the relevant sinks with the same backend; is this approach correct? I didn't find anything against it in the docs, but neither an example showing this usage...

An example would be:

namespace bl = boost::log;
namespace bl_snk = boost::log::sinks;
.
.
.
boost::shared_ptr< bl_snk::text_file_backend > text_backend = boost::make_shared< bl_snk::text_file_backend >(
                bl::keywords::file_name = "/tmp/file_%5N.log",
                bl::keywords::rotation_size = 5 * 1024 * 1024,
                bl::keywords::time_based_rotation = bl_snk::file::rotation_at_time_point(12, 0, 0)
            );
text_backend->auto_flush(true);

log_factory_libA.CreateSink< bl_snk::text_file_backend >(text_backend);
log_factory_libB.CreateSink< bl_snk::text_file_backend >(text_backend);

Where, under the hood, CreateSink does basically:

using sink_t = bl_snk::synchronous_sink< bl_snk::text_file_backend >;
boost::shared_ptr<sink_t> lib_sink = boost::make_shared<sink_t>(text_backend);

1条回答
Juvenile、少年°
2楼-- · 2019-08-23 23:33

I was planning to feed all the relevant sinks with the same backend; is this approach correct?

No, this is not correct. Sink frontends implement thread synchronization, so if multiple frontends share a backend the backend becomes unprotected.

There is generally no reason to use multiple frontends for a single backend. If you want to direct multiple channels to a single file or console, you don't need to create multiple sinks. A single sink should be created per file/console; you can control which channels are routed to the sink by updating its filter.

查看更多
登录 后发表回答