Search code examples
c++boost-log

How to use boost::log::expressions::format_date_time in a custom formatting function?


To format the timestamp in a formatter one can simply write

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

But how can I use the boost::log::expressions::format_date_time in a custom formatting function like this:

void MyFormatter(boost::log::record_view const &rec, boost::log::formatting_ostream &stream)
{
  stream << expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S"); // <-- does not work!
  stream << rec[expr::smessage];
}

Solution

  • The formatter lambda-style expression is invocable as a function, so you can just delegate to it:

    auto date_time_formatter = expr::stream << expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S");
    date_time_formatter(rec, stream);
    stream << rec[expr::smessage];