how to customize "TimeStamp" format of Boost.Log

JQ. picture JQ. · May 10, 2011 · Viewed 7.5k times · Source

I want to get year-month-day hour:minute:second.fraction(2 digits), if I use "%Y-%m-%d %H:%M:%S.%f", I got almost what I want exception for the fraction( last part ) of seconds, it's showing 6 digits on my Windows XP, I don't know how to get 2 digits only, any idea?

Answer

Boaz Yaniv picture Boaz Yaniv · May 11, 2011

Boost.DateTime (upon which Boost.Log relies) doesn't seem to support specialized fractional seconds formatting, so the only way to do that would be to write your own custom attribute formatter, or (the easier, but less nice way) to slightly modify your formatting code.

Instead of something like this:

backend->set_formatter
(
    fmt::stream <<
      fmt::date_time<boost::posix_time::ptime>
        ("TimeStamp", keywords::format = "%Y-%m-%d %H:%M:%S.%f"));

backend->set_formatter
(
    fmt::stream <<
    fmt::date_time<boost::posix_time::ptime>
        ("TimeStamp", keywords::format = %Y-%m-%d %H:%M:%S.") <<
    (fmt::format("%.2s") % fmt::date_time<boost::posix_time::ptime>("%f"))
);

I haven't tested it myself, but I believe it should work: the first fmt::date_time() will return the timestamp without the fractional seconds, while the second fmt::date_time() will return just the fractional seconds, which will be cut to two digits by the fmt::format().