In Boost Log, how do I format a custom severity_level using a format string?
Asked Answered
T

1

7

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?

Here's a portion of my code:

#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 );
}
Tuba answered 29/7, 2013 at 17:37 Comment(1)
Question seems to be related to #15854481. I have the same problem, providing %Severity% in the format string together with severity_logger does not work.Backrest
G
3

You should add

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

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

Result:

[] TRACE  - text message
Grandson answered 5/6, 2014 at 12:15 Comment(1)
Replace severity_level with boost::log::trivial::severity_level and this answer works for me.Happygolucky

© 2022 - 2024 — McMap. All rights reserved.