本文介绍了在Boost Log中,如何使用格式字符串格式化自定义的严重性级别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++程序中使用了增强日志,并且有一个自定义的 severity_logger<严重性级别> 使用我定义的严重性级别枚举。然后,我用格式字符串%TimeStamp%[%ThreadID%]%Severity%%Module%-%Message% 创建我的日志接收器,但是它不显示我有%Severity%的严重性,但是在那个位置只是空白。例如, 2013-07-29 10:31 [0xDEADBEEF] my.Module-Hello World 。我需要在格式字符串中执行什么操作才能使其显示严重性级别?

I'm using boost log in my C++ program, and I have a custom severity_logger< severity_level > using a severity_level enum that I defined. Then I create my log sink with the format string "%TimeStamp% [%ThreadID%] %Severity% %Module% - %Message%" but it doesn't display the severity where I have %Severity% but instead is just blank in that position. For example, 2013-07-29 10:31 [0xDEADBEEF] my.Module - Hello World. What do I need to do in my format string to make it display the severity level?

这是我代码的一部分:

#define NUM_SEVERITY_LEVELS 6
enum severity_level
{ 
  // These are deliberately the same levels that log4j uses
  trace = 0,
  debug = 1,
  info = 2,
  warning = 3,
  error = 4,                  
  fatal = 5                   
};  

typedef src::severity_logger< severity_level > logger_t;

const char* severity_level_str[NUM_SEVERITY_LEVELS] = {
  "TRACE",
  "DEBUG",
  "INFO",
  "WARNING",
  "ERROR",
  "FATAL" 
};

template< typename CharT, typename TraitsT >
std::basic_ostream< CharT, TraitsT >&
operator<< (
  std::basic_ostream< CharT, TraitsT >& strm,
  severity_level lvl
)
{
    const char* str = severity_level_str[lvl];
    if (lvl < NUM_SEVERITY_LEVELS && lvl >= 0)
        strm << str;
    else
        strm << static_cast< int >(lvl);
    return strm;
}

#define FORMAT_STRING "%TimeStamp% [%ThreadID%] %Severity% %Module% - %Message%"

boost::shared_ptr< sinks::synchronous_sink< sinks::text_file_backend > >
LOG_CREATE_SINK(const std::string& strLogFilename, bool fAutoFlush)
{ 
  return logging::add_file_log(
    keywords::file_name = strLogFilename,
    keywords::open_mode = (std::ios_base::app | std::ios_base::out) & ~std::ios_base::in,
    keywords::auto_flush = fAutoFlush,
    keywords::format = FORMAT_STRING );
}


推荐答案

您应该添加

boost::log::register_simple_formatter_factory< severity_level, char >("Severity");

,然后再调用LOG_CREATE_SINK方法。像这样:

before calling LOG_CREATE_SINK method. Like this:

int main(int argc, char* argv[])
{
    boost::log::register_simple_formatter_factory< severity_level, char >("Severity");
    LOG_CREATE_SINK("log_file.txt", true);
    logger_t logger;
    BOOST_LOG_SEV(logger, trace)
           << "text message";
    return 0;
}

结果:

[] TRACE  - text message

这篇关于在Boost Log中,如何使用格式字符串格式化自定义的严重性级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 05:30