提升日志时区

时间:2015-08-18 22:25:26

标签: c++ boost boost-log

我一直在学习Boost日志库

http://www.boost.org/doc/libs/develop/libs/log/doc/html/index.html

但我一直无法弄清楚如何显示用户的时区。有一个%q和%Q格式选项看起来很有前景,但似乎没有用(我使用的是MSVC ++ 2013)。使用此格式"%Y-%m-%d%H:%M:%S。%f%Q",我得到以下输出:

1 [2015-08-18 21:27:16.860724] main.cpp#11,Test App Started。

但我希望

1 [2015-08-18 21:27:16.860724-08.00] main.cpp#11,Test App Started。

如下所述:

http://www.boost.org/doc/libs/develop/libs/log/doc/html/log/detailed/expressions.html#log.detailed.expressions.formatters

这里是我一直在尝试的代码,还有一些注释掉的内容,我也试过没有运气:

void Log::init() const
{
    boost::log::core::get()->add_global_attribute("TimeStamp", boost::log::attributes::utc_clock());
//  boost::log::core::get()->add_global_attribute("TimeStamp", boost::log::attributes::local_clock());

    boost::log::register_simple_formatter_factory<Severity, char>("Severity");
//  boost::log::register_formatter_factory("TimeStamp", boost::make_shared<timestamp_formatter_factory>());

    boost::log::add_common_attributes();

    boost::log::add_file_log
    (
        boost::log::keywords::file_name = "appname_%N.log", 
        boost::log::keywords::rotation_size = 10 * 1024 * 1024, 
        boost::log::keywords::time_based_rotation = boost::log::sinks::file::rotation_at_time_point(0, 0, 0), 
        boost::log::keywords::format = 
            boost::log::expressions::stream
            << boost::log::expressions::attr<unsigned>("LineID") << " "
            << "[" << boost::log::expressions::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S.%f%Q"<< "]" << " "
            << "<" << boost::log::expressions::attr<Severity>("Severity") << _NSTR(">") << _NSTR(" ")
            << boost::log::expressions::smessage
//          "%LineID% [%TimeStamp(format=\"%Y-%m-%d %H:%M:%S.%f%Q\")%] <%Severity%>: %%Message%"
    );

    const auto severity = boost::log::expressions::attr<Severity>("Severity");

    boost::log::core::get()->set_filter
    (
        severity >= severityThreshold_
    );
}

有关我可能做错的任何建议吗?

1 个答案:

答案 0 :(得分:1)

utc_clocklocal_clock都会生成boost::posix_time::ptime类型的值,这些值没有时区信息。时钟之间的差异是时间ptime代表 - UTC或本地时间根据机器上设置的时区。格式化程序不能用于%Q%q,并用空字符串替换它们。

boost::local_time::local_date_time类型中存在时区,%Q%q占位符适用于此区域。该库没有生成local_date_time的时钟属性,因此您必须自己编写一个。有关示例,请参阅here