c++boostboost-logboost-logging

Passing functon object as filter when initializing boost log sink


I am creating new sink like in this example:

void init()
{
    logging::add_file_log
    (
        keywords::file_name = "sample_%N.log",
        keywords::rotation_size = 10 * 1024 * 1024,
        keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0),
        keywords::format = "[%TimeStamp%]: %Message%"
    );

    logging::core::get()->set_filter
    (
        logging::trivial::severity >= logging::trivial::info
    );
} 

I have implemented my own filter object:

struct MyFilter {
    ...
    bool operator()(const boost::log::attribute_value_set& attrs) const noexcept
    {
        bool result = ....
        // Do my filtering
        return result;
    }
    ...
};

How do I pass it as sink initialization parameter? i.e. I want to add following parameter:

keywords::filter = SOMETHING(MyFilter())

But I so far could not figure out what that "SOMETHING" should be. Can't find any examples. Can you please help me?


Solution

  • First, keywords::format is used to pass a formatter, not filter. For filters use keywords::filter parameter keyword.

    Second, both keywords::format and keywords::filter keywords only support string arguments currently. The accepted strings are interpreted according to the syntax described here as a formatter or filter, respectively.

    If you want to set a function object as a filter, you should call set_filter on the created sink with your function object. add_file_log returns a pointer to the created sink, so you can do it like this:

    auto sink = logging::add_file_log(...);
    sink->set_filter(MyFilter());
    

    The same applies to the formatter; formatting sinks provide set_formatter method for that.