Format a single log format attribute with logging :: init_from_stream

When I tweaked the format options in the code to format the date time output, I can use something like this

logging::formatter simpleFormat(expr::format("%1% %2%") %
   expr::format_date_time<boost::posix_time::ptime>("TimeStamp", "%H:%M:%S") %
   expr::smessage
);

But when I initialize logger with the configuration file, I can specify the format only at the position of the attribute position, and not in their formats.

therefore this line in the write buffer configuration file

Format="[%TimeStamp%]: %Message%"

outputs the result:

[2015-Feb-06 09:32:27.401496]: blah blah blah

I want to reduce the timestamp to something like this

[06.02.2015 09:32:27]

How can this be described in the boost log configuration file, otherwise it cannot be executed?

+2
source share
2 answers

Preamble

boost 1.55 ( ). MSVC 2013.

, formatter_factory TimeStamp, . :

#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;
}

format TimeStamp. :

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

set_formatter

sink->set_formatter
(
    expr::stream << expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S")
);
+1

Source: https://habr.com/ru/post/1662245/


All Articles