【问题标题】:boost log format single attribute with logging::init_from_stream使用 logging::init_from_stream 提升日志格式单一属性
【发布时间】:2015-04-06 06:00:05
【问题描述】:

当我在代码中设置格式参数以格式化日期时间输出时,我可以使用类似这样的东西

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

但是当我使用配置文件初始化记录器时,我只能在属性位置表示法中指定格式,而不是它们的格式详细信息。

所以,boost 日志配置文件中的这一行

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

产生输出:

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

我想把时间戳减少到这样的程度

[06.02.2015 09:32:27]

在boost log config文件中怎么描述,根本做不到?

【问题讨论】:

    标签: c++ boost format boost-log


    【解决方案1】:

    序言

    我的答案对 boost 1.55 有效(尚未使用最新版本进行测试)。并且仅使用 MSVC 2013 编译器进行了测试。

    回答

    看起来您需要为 TimeStamp 属性自定义 formatter_factory 才能指定其格式。这对我有用:

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

    现在它是你的设置文件,你可以为TimeStamp 属性指定format 参数。像这样:

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

    【讨论】:

    • Ty,看起来很棒,今天我已经完成了我的工作,周一我会试试看。
    【解决方案2】:

    您应该能够使用set_formatter 记录的here

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

    【讨论】:

      猜你喜欢
      • 2013-08-03
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多