2

In general, how can I perform string manipulation on boost log format expressions? in particular, how can I to truncate a TimeStamp expression ending in fractional seconds so that milliseconds are logged rather than microseconds?

Given this snippet, how can I log, for example, 13:13:08.440 instead of 13:13:08.440736?

logging::add_file_log("xyz.log",
    keywords::format = expr::stream
        << expr::format_date_time<boost::posix_time::ptime>("TimeStamp", "%T.%f")
);

I'd like to do something like this:

<< expr::format_date_time<boost::posix_time::ptime>("TimeStamp", "%T.%.3f")
plong
  • 1,723
  • 3
  • 14
  • 14

1 Answers1

2

There is currently no such feature built into Boost.Log. What you can do, however, is to write your own formatting function and set it as a formatter to the Boost.Log sink. You can either create a function that will format the whole record (see here for example) or just define an operator<< for a specific attribute. Here is an example. Also note that Boost.Log expressions are based on Boost.Phoenix, so using Boost.Phoenix constructs in filters and formatters is also possible. For example:

std::string my_formatter(logging::value_ref< boost::posix_time::ptime > const& timestamp)
{
    if (timestamp)
    {
        // Format date/time here and return the result.
    }
    else
    {
        // The "TimeStamp" attribute value was not found or has unexpected type.
        // Return a placeholder string.
    }
}

logging::add_file_log("xyz.log",
    keywords::format = expr::stream
        << boost::phoenix::bind(&my_formatter, expr::attr<boost::posix_time::ptime>("TimeStamp"))
);
Andrey Semashev
  • 10,046
  • 1
  • 17
  • 27
  • For additional information on building custom formatters, see [this SO question](https://stackoverflow.com/questions/25075854/boost-log-not-showing-custom-timestamp) (and its answer). – Christian Severin Nov 14 '18 at 15:41