草庐IT

c++ - 如何在 boost log 2.0 中设置 std::ios_base 标志,如 std::left?

coder 2024-02-15 原文

我有一个广泛使用 boost log 2.0 的应用程序。现在我想为该应用程序设置一些默认标志,如 std::setprecision(std::numeric_limits<double>::digits10 + 1)std::scientificstd::left 。但是我该怎么做呢?一种方法是在我的主要功能的最开始创建一个记录器并创建一个虚拟日志消息。这将永久设置所需的标志。但是没有更好的方法来做到这一点吗?

编辑回复:“OP should show actual code.”

我有一个全局日志记录单例,称为 L:

class L{
public:
  enum severity_level
  {
      dddebug,
      ddebug,
      debug,
      control,
      iiinfo,
      iinfo,
      info,
      result,
      warning,
      error,
      critical
  };

  typedef boost::log::sources::severity_channel_logger<
      severity_level, // the type of the severity level
      std::string // the type of the channel name
  > logger_t;
  typedef boost::log::sinks::synchronous_sink< boost::log::sinks::text_ostream_backend > text_sink;
  boost::shared_ptr< text_sink > sink_;

  static L& get();
  static boost::shared_ptr<text_sink> sink();
  static double t0();
  static double tElapsed();
private:
  L();
  double t0_p;
  static std::string tElapsedFormat();

  L(const L&) = delete;
  void operator=(const L&) = delete;
};

它提供了一个日志接收器、严重级别并利用 MPI 方法在 MPI 节点之间进行同步计时。类成员的实现如下:

#include "log.h"

#include <iomanip>
#include <limits>
#include <fstream>
#include <boost/log/attributes/function.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/smart_ptr/make_shared_object.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sources/severity_channel_logger.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>


namespace logging = boost::log;
namespace src = boost::log::sources;
namespace expr = boost::log::expressions;
namespace sinks = boost::log::sinks;
namespace attrs = boost::log::attributes;
namespace keywords = boost::log::keywords;

#include "mpiwrap.h"
#include <mpi.h>

BOOST_LOG_ATTRIBUTE_KEYWORD(t, "Time", std::string)
BOOST_LOG_ATTRIBUTE_KEYWORD(rank, "Rank", int)
BOOST_LOG_ATTRIBUTE_KEYWORD(channel, "Channel", std::string)
BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", L::severity_level)

L::L():
  sink_(boost::make_shared< text_sink >()),
  t0_p(MPI_Wtime())
{

  sink_->locked_backend()->add_stream(
    boost::make_shared< std::ofstream >("log." + std::to_string(MpiWrap::getRank())));

  sink_->set_formatter
  (
    expr::stream
      << "< "
      << t << " "
      << "[p:" << rank << "] "
      << "[c:" << channel << "] "
      << "[s:" << severity << "] "
      << expr::smessage
  );

  logging::core::get()->add_sink(sink_);

  logging::core::get()->set_filter(

       (channel == "ChannelName1" && severity >= dddebug)
    || (channel == "ChannelName2" && severity >= info)
    || (channel == "ChannelName3" && severity >= result)

  );

  // Add attributes
  logging::core::get()->add_global_attribute("Time", attrs::make_function(&tElapsedFormat));
  logging::core::get()->add_global_attribute("Rank", attrs::constant<int>(MpiWrap::getRank()));
}

L& L::get(){
  static L instance;
  return instance;
}

boost::shared_ptr<L::text_sink> L::sink(){
  return get().sink_;
}

double L::t0(){
  return get().t0_p;
}

double L::tElapsed(){
  return MPI_Wtime() - t0();
}

std::string L::tElapsedFormat(){
  std::stringstream ss;
  const int prec = std::numeric_limits<double>::digits10;
  ss << std::setw(prec + 2 + 6) << std::left << std::setprecision(prec) << tElapsed();
  return ss.str();
}

std::ostream& operator<< (std::ostream& strm, L::severity_level level)
{
    static const char* strings[] =
    {
        "DBG3",
        "DBG2",
        "DBG1",
        "CTRL",
        "INF3",
        "INF2",
        "INF1",
        "RSLT",
        "WARN",
        "ERRR",
        "CRIT"
    };

    if (static_cast< std::size_t >(level) < sizeof(strings) / sizeof(*strings))
        strm << strings[level];
    else
        strm << static_cast< int >(level);

    return strm;
}

现在开始使用:我的类通常有一个静态 logger_t(boost::log::sources::severity_channel_logger<severity_level, std::string> 的类型定义)成员

class A {
public:
    logger_t logger;
    //other stuff here
    void function_which_does_logging();
};

L::logger_t A::logger(boost::log::keywords::channel = "ClassA");

void A::function_which_does_logging(){
    //do non logging related stuff
    BOOST_LOG_SEV(logger, L::result) << "the error is: " << 0.1234567890;
    //do non logging related stuff
}

我目前对这个问题的解决方案是在我的程序开头放置一个日志语句

int main(){
    L::logger_t logger(boost::log::keywords::channel = "init");
    BOOST_LOG_SEV(logger, L::critical) << "setting up logger" << std::scientific << std::setprecision(std::numeric_limits<double>::digits10 + 1);

    //do stuff
}

最佳答案

@rhashimoto 很好地说明了您当前的解决方案将如何因多线程/并发日志记录操作而崩溃。我觉得最好的解决方案是定义您自己的日志记录宏来替换包含流修饰符的 BOOST_LOG_SEV,如下所示:

#define LOG_SCIENTIFIC(logger, sev) (BOOST_LOG_SEV(logger, sev) << std::scientific)

它可以用作 BOOST_LOG_SEV 的替代品,后者将数字格式化为科学数据。但是,检查您的代码并用新的自定义宏替换每个日志记录操作可能会很痛苦。除了定义自己的宏之外,您还可以重新定义 BOOST_LOG_SEV 以按照您的意愿运行。 boost/log/sources/severity_feature.hpp 定义 BOOST_LOG_SEV 如下:

//! An equivalent to BOOST_LOG_STREAM_SEV(logger, lvl)
#define BOOST_LOG_SEV(logger, lvl) BOOST_LOG_STREAM_SEV(logger, lvl)

因为 BOOST_LOG_STREAM_SEV 仍然是公共(public) boost API 的一部分,您应该能够像这样安全地重新定义 BOOST_LOG_SEV:

#define BOOST_LOG_SEV(logger, lvl) (BOOST_LOG_STREAM_SEV(logger, lvl) << std::scientific)

只要它是在包含 boost 日志 header 之后定义的,它就应该执行您想要的操作。但是,我建议使用具有自定义名称的宏,这样其他人就可以清楚地知道您的代码在做什么。

关于c++ - 如何在 boost log 2.0 中设置 std::ios_base 标志,如 std::left?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23087376/

有关c++ - 如何在 boost log 2.0 中设置 std::ios_base 标志,如 std::left?的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  5. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  6. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  7. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  8. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

  9. ruby-on-rails - 如何在 ruby​​ 交互式 shell 中有多行? - 2

    这可能是个愚蠢的问题。但是,我是一个新手......你怎么能在交互式ruby​​shell中有多行代码?好像你只能有一条长线。按回车键运行代码。无论如何我可以在不运行代码的情况下跳到下一行吗?再次抱歉,如果这是一个愚蠢的问题。谢谢。 最佳答案 这是一个例子:2.1.2:053>a=1=>12.1.2:054>b=2=>22.1.2:055>a+b=>32.1.2:056>ifa>b#Thecode‘if..."startsthedefinitionoftheconditionalstatement.2.1.2:057?>puts"f

  10. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

随机推荐