c++ - 使用logging::init_from_stream boost 日志格式单个属性

标签 c++ boost format boost-log

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

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 日志配置文件中描述它,或者根本无法完成?

最佳答案

序言

我的答案对于 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;
}

现在,您可以在设置文件中为 TimeStamp 属性指定 format 参数。像这样:

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

关于c++ - 使用logging::init_from_stream boost 日志格式单个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28359921/

相关文章:

c++ - 奇怪的计算结果

c++ - 如何使用 C++ 将时区化的 XML 类型 dateTime 转换为 time_t

c++ - boost.multiindex 和值的地址作为键

python - Pandas Dataframe to_csv 格式输出

html - 下划线格式问题

xml - Golang 更改 float 的 xml 编码格式

c++ - 使用非常量变量作为 constexpr 数组的索引来传递给模板参数

c++ - 在 CMake 中可移植地设置编译器选项(如 -Wall 和 -pedantic)的最佳方法

c++ - 使用 boost 线程 : Signal and wait for termination

c++ - 在以下用例中使用 boost::optional 有好处吗?