加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何在Boost日志中将严重性与相同宽度对齐

发布时间:2020-12-16 06:52:51 所属栏目:百科 来源:网络整理
导读:例如,’info’和’warning’具有不同的宽度,它在日志中看起来并不可取.我想在日志中将它们对齐到相同的宽度. 看来我可以使用自定义格式化工厂,如本文所述: boost log format single attribute with logging::init_from_stream 这是使用自定义严重性级别的另
例如,’info’和’warning’具有不同的宽度,它在日志中看起来并不可取.我想在日志中将它们对齐到相同的宽度.

看来我可以使用自定义格式化工厂,如本文所述:
boost log format single attribute with logging::init_from_stream

这是使用自定义严重性级别的另一种解决方案
how do I format a custom severity_level using a format string

除此之外,是否有一种更简单的方法来实现这一点,通过像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());
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读