boost log format single attribute with logging::init_from_stream

狂风中的少年 提交于 2019-12-04 16:34:00

Preamble

My answer is valid for boost 1.55 (haven't tested with latest one). And it was only tested with MSVC 2013 compiler.

Answer

Looks like you need custom formatter_factory for TimeStamp attribute to be able to specify it's format. This works for me:

#include <fstream>
#include "boost/shared_ptr.hpp"
#include "boost/log/trivial.hpp"
#include "boost/log/expressions.hpp"
#include "boost/log/utility/setup.hpp"
#include "boost/log/support/date_time.hpp"

class timestamp_formatter_factory :
    public boost::log::basic_formatter_factory<char, boost::posix_time::ptime>
{
    public:
        formatter_type create_formatter(boost::log::attribute_name const& name, args_map const& args)
        {
            args_map::const_iterator it = args.find("format");
            if (it != args.end())
                return boost::log::expressions::stream << boost::log::expressions::format_date_time<boost::posix_time::ptime>(boost::log::expressions::attr<boost::posix_time::ptime>(name), it->second);
            else
                return boost::log::expressions::stream << boost::log::expressions::attr<boost::posix_time::ptime>(name);
        }
};

int main()
{
    // Initializing logging
    boost::log::register_formatter_factory("TimeStamp", boost::make_shared<timestamp_formatter_factory>());
    boost::log::add_common_attributes();
    std::ifstream file("settings.ini");
    boost::log::init_from_stream(file);
    // Testing
    BOOST_LOG_TRIVIAL(info) << "Test";
    return 0;
}

And now it your settings file you can specify format argument for TimeStamp attribute. Like this:

[Sinks.ConsoleOut]
Destination=Console
AutoFlush=true
Format="[%TimeStamp(format=\"%Y.%m.%d %H:%M:%S\")%]: %Message%"

You should be able to use set_formatter as documented here

sink->set_formatter
(
    expr::stream << expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S")
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!