我正在为我的应用程序的日志记录平台使用 Boost-Log 和全局严重性记录器。分析表明,boost::log::v2s_mt_posix::core::open_record
最多可以占用总执行时间的 25%。
我确实有许多日志消息,但我不希望它们如此昂贵,因为它们的严重性较低并且已被过滤。
有没有办法让这些消息在运行时不那么昂贵?(再次:我希望即使在过滤时也会有很小的开销,当然在未过滤时会有更大的开销)。
通过创建一些包装宏,编译时相对容易“修复”这个问题。
更新了示例工作代码:
#include <cmath>
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
#include <boost/log/sources/global_logger_storage.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/sources/severity_channel_logger.hpp>
#include <boost/log/common.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/utility/empty_deleter.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
// severity levels
enum severity_level {INFO};
// Logging macro
#define LOG(level) BOOST_LOG_SEV(global_logger::get(), level)
// Initializing global boost::log logger
typedef boost::log::sources::severity_channel_logger_mt<
severity_level, std::string> global_logger_type;
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(global_logger, global_logger_type)
{
return global_logger_type(boost::log::keywords::channel = "global_logger");
}
// Initialize terminal logger
void init_logger(int verbosity)
{
namespace bl = boost::log;
typedef bl::sinks::synchronous_sink<bl::sinks::text_ostream_backend>
text_sink;
boost::shared_ptr<text_sink> sink = boost::make_shared<text_sink>();
sink->locked_backend()->add_stream(
boost::shared_ptr<std::ostream>(&std::cout, boost::empty_deleter()));
sink->locked_backend()->auto_flush(true);
sink->set_formatter(bl::expressions::stream << bl::expressions::message);
sink->set_filter(bl::expressions::attr<severity_level>("Severity")
< (severity_level) verbosity);
bl::core::get()->add_sink(sink);
bl::add_common_attributes();
}
int main(int argc, char* argv[])
{
init_logger(boost::lexical_cast<int>(argv[1]));
for(int i = 0; i < 200; ++i)
{
std::sin(std::sin(17.2)); // dummy processing
LOG(INFO) << "A message!";
}
return 0;
}
使用参数运行0
不会打印任何日志消息,但与注释掉 LOG 消息相比,它需要两倍(!)的时间。