Boost.log: How to prevent the output will be duplicated to all added streams when it uses the add_file_log() function?

风格不统一 提交于 2019-11-29 07:00:25

You seem to have a misunderstanding of how Boost.Log works.

There are sources and sinks. A source takes data, such as a string, and creates an entry with it. The entry is then given to the core, which dispatches it to all the sinks. The sinks can then filter, format and output the entries to wherever they want, such as stdout or a file.

An example of a source would be the severity_logger you are using. You might be used to the term "logger" instead of "source", but "logger" isn't very precise because logging is a multi-stage process.

You don't usually have to create multiple sources ("loggers"). Instead, you can add multiple global sinks. In your case, you'll need a filtered sink per file.

                                  +--------------+
                            +---> | console sink | ----> stdout
                            |     +--------------+
                            |
+--------+      +------+    |     +--------------+
| source | ---> | core | ---+---> | file sink    | ----> log1.txt
+--------+      +------+    |     +--------------+
                            |
                            |     +--------------+
                            +---> | file sink    | ----> log2.txt
                                  +--------------+

Now, you could have multiple sources, each with their own threading model, attributes, character type, etc., but they would still all generate entries and give them to the core. In your case, it wouldn't be very useful.

Let's get the headers out of the way:

#include <string>
#include <fstream>
#include <boost/log/sinks.hpp>
#include <boost/log/utility/setup/formatter_parser.hpp>
#include <boost/log/sources/severity_channel_logger.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/attributes/scoped_attribute.hpp>

namespace bl = boost::log;

Let's start:

BOOST_LOG_ATTRIBUTE_KEYWORD(tag_attr, "Tag", std::string);

A log entry has attributes which can be set every time something is logged. These attributes are usually used in formatting (such as "[%TimeStamp%] [%Message%]"), but we'll add a new attribute to allow for differentiating between the different files. I called the attribute "Tag".

using logger_type = bl::sources::severity_logger<bl::trivial::severity_level>;
static logger_type g_logger;

const std::string g_format = "[%TimeStamp%] (%LineID%) [%Severity%] [%Tag%]: %Message%";

Now, in this example, the actual boost logger is a global object (g_logger). You may want to restrict its scope and pass it around to your own logger objects. I've also made the format a global constant. YMMV.

This is the logger class:

class logger
{
public:
    logger(std::string file)
        : tag_(file)
    {
        using backend_type = bl::sinks::text_file_backend;
        using sink_type = bl::sinks::synchronous_sink<backend_type>;
        namespace kw = bl::keywords;

        auto backend = boost::make_shared<backend_type>(
            kw::file_name = file + "_%N.log",
            kw::rotation_size = 10 * 1024 * 1024,
            kw::time_based_rotation = bl::sinks::file::rotation_at_time_point(0, 0, 0),
            kw::auto_flush = true);

        auto sink = boost::make_shared<sink_type>(backend);
        sink->set_formatter(bl::parse_formatter(g_format));
        sink->set_filter(tag_attr == tag_);

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

    void log(const std::string& s)
    {
        BOOST_LOG_SCOPED_THREAD_TAG("Tag", tag_);
        BOOST_LOG_SEV(g_logger, bl::trivial::info) << s;
    }

private:
    const std::string tag_;
};

I've used the file name as a tag, but it could be anything else as long as it's unique. Every log entry will have this tag as an attribute, which will be used in the sink filter.

First, a text_file_backend is created and is given to a new sink, which is then added to the core. This is actually what happens when you call add_file_log(), it's just a helper function. I've reused the same parameters you had in your example (filename pattern, rotation, etc.)

The interesting line is this one:

sink->set_filter(tag_attr == tag_);

Here, tag_attr was defined above as an attribute keyword. Keywords are a bit unusual in Boost.Log: they can be used to create expressions that will be evaluated at runtime. In this case, the sink will only accept entries where tag_attr == tag_. So when a logger logs something, it sets its own tag as an attribute, and the sink will ignore anything that doesn't have this tag. In log(), you can see the "Tag" attribute being set.

Here's main():

int main()
{
    bl::register_simple_formatter_factory<bl::trivial::severity_level, char>("Severity");
    boost::log::add_common_attributes();

    bl::add_console_log(std::clog, bl::keywords::format=g_format);

    logger lg1("1");
    logger lg2("2");

    lg1.log("a");
    lg1.log("b");
    lg1.log("c");

    lg2.log("d");
    lg2.log("e");
    lg2.log("f");
}

You'll see that I've moved the common stuff outside of logger since it doesn't really belong there. Entries "a", "b" and "c" will be written to "1_0.txt" and "d", "e" and "f" to "2_0.txt". All six entries will be written to the console.

     +--------------+
     | lg1.log("a") |
     +--------------+
            |
            v
+-------------------------+
| Entry:                  |
|   Timestamp: 1472660811 |
|   Message:   "a"        |
|   LineID:    1          |
|   Severity:  info       |
|   Tag:       "1"        |
+-------------------------+
            |            
            v                 +----------------------+
         +------+             | console sink         |
         | core | -----+----> |   file: stdout       |  --> written
         +------+      |      |   filter: none       |
                       |      +----------------------+
                       |      
                       |      +----------------------+
                       |      | file sink            |
                       +----> |   file: "1_0.txt"    |  --> written
                       |      |   filter: tag == "1" |
                       |      +----------------------+
                       |      
                       |      +----------------------+
                       |      | file sink            |
                       +----> |   file: "2_0.txt"    |  --> discarded
                              |   filter: tag == "2" |
                              +----------------------+
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!