7

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

这是我的代码的一部分:

#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 );
}
4

1 回答 1

1

你应该添加

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

在调用 LOG_CREATE_SINK 方法之前。像这样:

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
于 2014-06-05T12:15:20.197 回答