4

For example, 'info' and 'warning' have different width, it looks not preety in the log. I want to align them to same width in log.

It seems that I could use customized formatter factory as this article described: boost log format single attribute with logging::init_from_stream

This is another solution by using customized severity level: how do I format a custom severity_level using a format string

Besides that, is there an easier way to achieve this by customizing the format string just like printf?

Community
  • 1
  • 1
user1633272
  • 2,007
  • 5
  • 25
  • 48
  • Did you try `std::setw`? Depending on how you output severity level, setting width to the stream before and after the severity level might work. – Andrey Semashev Nov 30 '16 at 06:33

1 Answers1

0

You can try setting the formatter to something like

expr::stream << std::left << std::setw(7) << std::setfill(' ') <<
                logging::trivial::severity << " " << expr::smessage;

The width of 7 comes from the maximum possible length ('warning'). You should change it if you use custom severity levels.

Here a more complete example (header files omitted for simplicity):

namespace logging = boost::log;
namespace expr = boost::log::expressions;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;

using namespace logging::trivial;

logging::sources::severity_logger<severity_level> s_log;

void init_logging(const std::string& log_dir)
{
  boost::shared_ptr<logging::core> core = logging::core::get();
  boost::shared_ptr<sinks::text_file_backend> backend =
    boost::make_shared<sinks::text_file_backend>(
      keywords::file_name = log_dir + "/l_%Y-%m-%d_%5N.log", // one file per date and execution
      keywords::rotation_size = 512 * 1024); // rotate after 512KB

  // Collect clashing logs
  backend->set_file_collector(sinks::file::make_collector(keywords::target = log_dir));
  backend->scan_for_files();

  typedef sinks::synchronous_sink<sinks::text_file_backend> sink_t;
  boost::shared_ptr<sink_t> sink(new sink_t(backend));
  sink->locked_backend()->auto_flush(true);
  sink->set_formatter(expr::stream <<
                      "[" << expr::attr<boost::posix_time::ptime>("TimeStamp") << "] " <<
                      std::left << std::setw(7) << std::setfill(' ') << logging::trivial::severity << " " <<
                      expr::smessage);
  core->add_sink(sink);

  s_log.add_attribute("TimeStamp", logging::attributes::local_clock());
}
cbuchart
  • 10,847
  • 9
  • 53
  • 93
  • I apologize if the code contains any typo or error, I copied and edited from one of the applications I'm working on but I didn't have time to test it in a clean project. – cbuchart Jan 17 '17 at 09:10