将boost :: log :: expressions :: attr <std :: string>转换为std :: string

mal*_*lat 4 c++ boost boost-log

在使用Boost.Log时,我试图保留我的TimeStamp格式化程序,例如:

  logging::add_file_log
    (
     keywords::file_name = "my.log",
     keywords::format =
     (
      expr::stream
      << expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S")
      << "," << expr::attr< int >("Line")
      << " " << expr::attr< std::string >("File")
      << " " << logging::trivial::severity
      << " - " << expr::smessage
     )
    );
Run Code Online (Sandbox Code Playgroud)

据说我不能使用其他形式的格式化程序,因为我在转换"TimeStamp"为自定义格式时会遇到很多困难:

static void my_formatter(logging::record_view const& rec, logging::formatting_ostream& strm)
{
  strm << logging::extract< boost::posix_time::ptime >("TimeStamp", rec);
Run Code Online (Sandbox Code Playgroud)

将输出类似于:2015-Jul-01 16:06:31.514053,而我只对以下内容感兴趣:"%Y-%m-%d %H:%M:%S".但是第一种形式非常难以使用,例如我无法将其expr::attr< std::string >转换为简单std::string的例如:

  logging::add_file_log
    (
     keywords::file_name = "my.log",
     keywords::format =
     (
      expr::stream
      << expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S")
      << "," << expr::attr< int >("Line")
      << " " << boost::filesystem::path(expr::attr< std::string >("File"))
        .filename().string()
      << " " << logging::trivial::severity
      << " - " << expr::smessage
     )
    );
Run Code Online (Sandbox Code Playgroud)

上面的代码甚至没有编译.

是否有一种简单的方法可以TimeStamp使用我的自定义格式进行打印,同时使用自定义强制转换为字符串以便能够使用boost::filesystem::path::filename()

doq*_*tor 5

在自定义格式化程序中,您可以轻松地以"%Y-%m-%d %H:%M:%S"格式构建时间戳:

void my_formatter(logging::record_view const& rec, logging::formatting_ostream& strm)
{
    const boost::posix_time::ptime &pt = *logging::extract< boost::posix_time::ptime >("TimeStamp", rec);
    strm << pt.date() << " " << pt.time_of_day().hours() << ":" << pt.time_of_day().minutes() << ":" << pt.time_of_day().seconds()
    ...
    << rec[expr::smessage];
}
Run Code Online (Sandbox Code Playgroud)