如何将严重性与升压日志中的相同宽度保持一致

How to align severity to same width in Boost log

本文关键字:保持一致 日志 严重性      更新时间:2023-10-16

例如,'info'和'警告'具有不同的宽度,在日志中看起来并不是预备。我想在日志中对齐它们相同的宽度。

看来我可以使用本文所述使用自定义的格式化工厂:带有logging :: init_from_stream

的Boost日志格式单属性

这是使用自定义严重性级别的另一个解决方案:如何使用格式字符串

格式化自定义afterity_level

除此之外,是否有一种更简单的方法来通过自定义格式字符串(例如printf)来实现此目标?

您可以尝试将格式化设置为

之类的东西
expr::stream << std::left << std::setw(7) << std::setfill(' ') <<
                logging::trivial::severity << " " << expr::smessage;

7的宽度来自最大可能的长度("警告")。如果您使用自定义严重性级别,则应更改它。

在这里,一个更完整的示例(为简单起见而省略了标题文件):

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());
}