gpt4 book ai didi

c++ - boost 日志 : Why it is showing duplicate the message?

转载 作者:行者123 更新时间:2023-11-30 05:23:33 25 4
gpt4 key购买 nike

我正在学习 Boost.Log 库。我想将消息发送到文件和 std::clog。我有以下类(class):

class logger
{
public:
explicit logger(
const std::string& tag,
const std::string& file,
bool console
)
{
boost::log::register_simple_formatter_factory< boost::log::trivial::severity_level, char >("Severity");

std::string the_format = "[%TimeStamp%] (%LineID%) [%Severity%]";
if(!tag.empty()) {
m_log_.add_attribute(
"Tag",
boost::log::attributes::constant< std::string >( tag )
);
the_format += " [%Tag%]";
}

the_format += ": %Message%";

if(console) {
boost::log::add_console_log(
std::clog,
boost::log::keywords::auto_flush = true,
boost::log::keywords::format = the_format
);
}

if(!file.empty()) {
boost::log::add_file_log(
boost::log::keywords::file_name = file,
boost::log::keywords::auto_flush = true,
boost::log::keywords::open_mode = (std::ios::out | std::ios::app),
boost::log::keywords::format = the_format
);
}

}

~logger(void)
{ }

void log(
const std::string& msg
)
{
BOOST_LOG_SEV ( m_log_, boost::log::trivial::info ) << msg;
}

private:
boost::log::sources::severity_logger< boost::log::trivial::severity_level > m_log_;

}; // logger

我有以下 main() 函数:

void x()
{
logger lg("omega", "", true);
lg.log( "Goodbye" );
}

int main(int argc, char** argv)
{
logger lg( "alfa", "", true );
lg.log( "Hello world!!!");
x();
return 0;
}

我不明白为什么会显示重复的消息:“Hello world!!!”:

[2016-Aug-23 17:51:36.852912] (1) [info] [alfa]: Hello world!!!
[2016-Aug-23 17:51:36.853359] (2) [info] [omega]: Goodbye
[2016-Aug-23 17:51:36.853359] (2) [info] [omega]: Goodbye

更新:抱歉,示例不完整。

最佳答案

logger 的构造函数正在调用 add_console_log()add_file_log()。如果你两次构造logger,这些函数也会被调用两次。由于它们添加了全局接收器,因此每个日志条目都将在控制台和您的文件中复制两次。

int main(int argc, char** argv)
{
logger lg1("1", "", true);
logger lg2("2", "", true);
logger lg3("3", "", true);
logger lg4("4", "", true);

lg1.log("test");
}

这将输出:

[2016-Aug-23 13:25:56.468382] (1) [info] [1]: test
[2016-Aug-23 13:25:56.468382] (1) [info] [1]: test
[2016-Aug-23 13:25:56.468382] (1) [info] [1]: test
[2016-Aug-23 13:25:56.468382] (1) [info] [1]: test

您可能需要某种引用计数或标志来仅调用这些函数一次。

关于c++ - boost 日志 : Why it is showing duplicate the message?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39106077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com