boost版本:1.67
编译器:gcc 4.9.4
使用boost log输出__FILE__,__LINE__,__func__,可以简单的采用以下方式
#define LOG_TRACE BOOST_LOG_SEV(*(crush::common::get_glog()), crush::common::SL_TRACE)// \
<< "(" << __FUNCTION__ << " "<< __FILE__ << ", " << __LINE__ << ") |
还可以通过扩展属性来实现.
二者实现上差别是:
BOOST_LOG_SEV使用BOOST_LOG_STREAM_SEV.通过operator <<输出.
扩展属性利用BOOST_LOG_STREAM_WITH_PARAMS,属性作为参数传入.
(BOOST_LOG_STREAM_WITH_PARAMS内部逻辑与operator<<可能相当,两种方法应该没有什么优劣之分)
以下描述通过扩展属性的实现.
代码来自:
boost log to print source code file name and line number
https://stackoverflow.com/questions/24750218/boost-log-to-print-source-code-file-name-and-line-number
代码不是完整的,供实现参考.
- 输出格式增加属性File,Function,Line,对应宏__FILE__,__func__,__LINE__.
void Log::init_logfile() {
logging::add_file_log(
keywords::format =
(
expr::stream
<< expr::attr< unsigned int >("LineID")<<"|"
<< expr::format_date_time(expr::attr< boost::posix_time::ptime >("TimeStamp"),"%Y-%m-%d,%H:%M:%S.%f") << "|"
<< boost::phoenix::bind(&get_native_process_id, process_id.or_none()) << "|"
<< boost::phoenix::bind(&get_native_thread_id, thread_id.or_none()) << "|"
<< expr::attr< severity_level, severity_tag >("Severity") << "|"
<< expr::attr<std::string>("File") << "|"
<< expr::attr<const char*>("Function") << "|"
<< expr::attr<int>("Line") << "|"
<< expr::smessage
)
);
}
11-13行:增加几个属性的输出
- 定义宏及相关函数
#define LOG_TRACE \
BOOST_LOG_STREAM_WITH_PARAMS( \
*(crush::common::get_glog()), \
(set_get_attrib("File", path_to_filename(__FILE__))) \
(set_get_attrib("Line", __LINE__)) \
(set_get_attrib("Function", __func__)) \
(::boost::log::keywords::severity = (crush::common::SL_TRACE)) \
)
// Set attribute and return the new value
template<typename ValueType>
ValueType set_get_attrib(const char* name, ValueType value) {
auto attr = logging::attribute_cast<attrs::mutable_constant<ValueType>>(logging::core::get()->get_global_attributes()[name]);
attr.set(value);
return attr.get();
}
// Convert file path to only the filename
std::string path_to_filename(std::string path) {
return path.substr(path.find_last_of("/\\")+1);
}
使用
以下是扩展属性方式输出的测试代码.
void test() {
logging::core::get()->add_global_attribute("File", attrs::mutable_constant<std::string>(""));
logging::core::get()->add_global_attribute("Line", attrs::mutable_constant<int>(0));
logging::core::get()->add_global_attribute("Function", attrs::mutable_constant<const char*>(""));
const size_t LOG_RECORD_NUM = 10;
for (size_t i=0; i<LOG_RECORD_NUM; i++) {
uint8_t index = random() % 6;
severity_level level = (severity_level)index;
LOG_TRACE << std_string_format("A %s severity message",get_severity_tag(level));
}
}
2-4:用add_global_attribute增加扩展属性.
7-11:.随机生成日志级别,LOG_TRACE输出日志
注意:属性值类型与宏定义LOG_TRACE中必须一致.
如果把Function值的类型若从const char*修改为std::string,则会导致set_get_attrib中attr的指针为nullptr.产生异常.