提升日志严重级别与系统日志严重级别

时间:2018-11-19 17:10:49

标签: c++ boost boost-log

我正在尝试修改我的应用程序以使用Boost Log库,而不是登录syslog。 Boost Log严重性级别在boost/log/trivial.hpp中定义,其中最严重的级别具有最大数字(5):

enum severity_level
{
    trace,
    debug,
    info,
    warning,
    error,
    fatal
};

但是,syslog定义了更多的严重性级别,实际上由RFC5424进行了标准化-最严重的级别具有最小数字(0)。

有没有办法定义自己的MySeverityLevels枚举类型(可能接近RFC5424)并使用各种Boost Log记录器(例如severity_logger)与此新类型一起使用,包括通过严重程度?

2 个答案:

答案 0 :(得分:1)

<boost_root>/libs/log/example/native_syslog包含自定义日志级别的示例,即为您的严重性级别创建一个枚举:

//! Define application-specific severity levels
enum severity_levels
{
    /* your own level */
    normal = 2,
    warning = 1,
    error = 0
};

并将其注册到您的接收器中

    // Create a syslog sink
    shared_ptr< sinks::synchronous_sink< sinks::syslog_backend > > sink(
        new sinks::synchronous_sink< sinks::syslog_backend >(
            keywords::use_impl = sinks::syslog::native,
            keywords::facility = sinks::syslog::local7));
     ........................
    // We'll have to map our custom levels to the syslog levels
    sinks::syslog::custom_severity_mapping< severity_levels > mapping("Severity");
    mapping[normal] = sinks::syslog::info;
    mapping[warning] = sinks::syslog::warning;
    mapping[error] = sinks::syslog::critical;

    sink->locked_backend()->set_severity_mapper(mapping);

    // Add the sink to the core
    logging::core::get()->add_sink(sink);

答案 1 :(得分:0)

我在回答自己的问题。下面的代码实现了我想要的:

#include <boost/log/common.hpp>
#include <boost/log/utility/setup/file.hpp>

namespace logging = boost::log;
namespace src = boost::log::sources;
namespace keywords = boost::log::keywords;

enum class MySeverityLevel
{
  panic,
  alert,
  critical,
  error,
  warning,
  notice,
  info,
  debug
};

BOOST_LOG_ATTRIBUTE_KEYWORD(Severity, "Severity", MySeverityLevel)

int main()
{
  // ------ define sink
  logging::add_file_log
  (
    keywords::file_name = "test.log",
    keywords::filter = (Severity <= MySeverityLevel::error)
  );
  // ------ define logger
  src::severity_logger<MySeverityLevel> lg;
  // ------ output logging messages
  BOOST_LOG_SEV(lg, MySeverityLevel::panic) << "This is panic";
  BOOST_LOG_SEV(lg, MySeverityLevel::debug) << "This is debug";
}

不需要使用任何映射。