我正在为我的应用程序的日志记录平台使用 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 消息要多。
最佳答案
通常,在记录日志时,必须评估记录的内容,而该评估发生在实际决定是否记录之前。例如:
log.debug("The current state of the system is: " + system.expensiveFunctionToGatherState());
我们有一个自行开发的日志系统,可以将当前时间添加到日志中,这是对 gettimeofday()
的调用。事实证明,程序中 20% 的 CPU 消耗是调用 gettimeofday()
以获取从未运行过的日志函数。
关于c++ - Boost Log运行时优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24259949/