提升日志,为什么不打印threadid和processid

时间:2017-09-21 06:56:44

标签: c++ logging boost

我在使用升级日志库时遇到问题,如下所示:

BOOST_LOG_ATTRIBUTE_KEYWORD(log_severity, "Severity", SeverityLevel)
BOOST_LOG_ATTRIBUTE_KEYWORD(log_timestamp, "TimeStamp", boost::posix_time::ptime)
BOOST_LOG_ATTRIBUTE_KEYWORD(log_uptime, "Uptime", attrs::timer::value_type)
BOOST_LOG_ATTRIBUTE_KEYWORD(log_scope, "Scope", attrs::named_scope::value_type)
BOOST_LOG_ATTRIBUTE_KEYWORD(line_id, "LineID", unsigned int)
BOOST_LOG_ATTRIBUTE_KEYWORD(thread_id, "ThreadID", unsigned int)
BOOST_LOG_ATTRIBUTE_KEYWORD(process_id, "ProcessID", unsigned int)

    auto file_sink=logging::add_file_log
        (
        keywords::file_name="%Y-%m-%d_%N.log",     
        keywords::rotation_size=100*1024*1024,       
        keywords::time_based_rotation=sinks::file::rotation_at_time_point(0,0,0)   
        );



    file_sink->set_filter(log_severity>= Log_Info);   

    file_sink->locked_backend()->scan_for_files();

    logging::formatter formatter = expr::stream << "[" << log_timestamp << "] [" << line_id << "] [" << log_scope << "] [" << log_severity << "] [" << thread_id << "] [" << process_id << "] " << expr::message;

    file_sink->set_formatter(formatter);

    file_sink->locked_backend()->auto_flush(true);
    logging::core::get()->add_sink(console_sink);
    logging::add_common_attributes();

我对mian函数的调用如下:

src::severity_logger<SeverityLevel>lg;
BOOST_LOG_FUNCTION();
BOOST_LOG_SEV(lg, Log_Info) << "====main";

输出消息:

enter image description here

1 个答案:

答案 0 :(得分:2)

您不必创建自定义属性关键字ThreadIDProcessIDTimeStamp。只需使用common attributes构建格式化程序,如下所示:

logging::formatter formatter = expr::stream << 
    "[" << log_timestamp << 
    "] [" << line_id << 
    "] [" << log_scope << 
    "] [" << log_severity <<
    "] [" << logging::expressions::attr<logging::attributes::current_thread_id::value_type>("ThreadID") << 
    "] [" << logging::expressions::attr<logging::attributes::current_process_id::value_type>("ProcessID") << 
    "] " << expr::message;

然而正如安德烈指出的那样,如果您仍想创建已存在的自定义关键字,则必须指定其类型:

BOOST_LOG_ATTRIBUTE_KEYWORD(thread_id, "ThreadID", logging::attributes::current_thread_id::value_type)
BOOST_LOG_ATTRIBUTE_KEYWORD(process_id, "ProcessID", logging::attributes::current_process_id::value_type)

工作示例是here