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

Boost Log severity levels versus syslog severity levels

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

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

但是,syslog defines more severity levels, which are actually standardized by the RFC5424 - 最严重的级别具有 最小 数字 (0)。

有什么方法可以定义我自己的 MySeverityLevels 枚举类型(可能接近 RFC5424)并使用各种 Boost Log 记录器(例如 severity_logger)和这个新类型,包括按严重级别过滤?

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

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

#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";
}

不需要使用任何映射。