【发布时间】:2025-12-15 04:50:02
【问题描述】:
我正在尝试使用具有从流初始化功能的 Boost Log 库。 我这里有一些问题。我的代码很简单,基于 Boost Log 文档。
#include <boost/log/core.hpp>
#include <boost/log/utility/setup/from_stream.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/move/utility.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <iostream>
#include <fstream>
namespace logging = boost::log;
namespace src = boost::log::sources;
using namespace boost::log::trivial;
int main(int, char*[])
{
logging::add_common_attributes();
logging::register_simple_filter_factory<logging::trivial::severity_level, char>("Severity");
logging::register_simple_formatter_factory<logging::trivial::severity_level, char>("Severity");
std::ifstream file("settings.ini");
logging::init_from_stream(file);
src::severity_logger<logging::trivial::severity_level> lg;
BOOST_LOG_SEV(lg, error) << "test" << std::endl;
return 0;
}
我的 settings.ini 文件也很简单,取自 boost 文档:
[Core]
DisableLogging=false
#Filter="%Severity% > 3"
# Sink settings sections
[Sinks.MySink1]
# Sink destination type
Destination=Console
# Sink-specific filter. Optional, by default no filter is applied.
#Filter="%Target% contains \"MySink1\""
# Formatter string. Optional, by default only log record message text is written.
Format="<%TimeStamp%> - %Severity% - %Message%"
# The flag shows whether the sink should be asynchronous
Asynchronous=false
# Enables automatic stream flush after each log record.
AutoFlush=true
请注意核心部分中带有“过滤器”的注释行。如果它被评论,那么一切都很完美。但是,当我取消注释时,我收到一条错误消息:
在抛出一个实例后调用终止 'boost::exception_detail::clone_impl
' what(): bad lexical cast: 源类型值无法解释为目标 Aborted (core dumped)
我在论坛和 Boost Log 文档中读到,我应该在调用 init_from_stream 函数之前注册过滤器和格式化程序工厂,即使对于像 boost::log::trivial::severity_level 这样的内置类型也是如此。我就是这样做的。这有助于打印严重性(格式化),但对阅读严重性(解析)没有帮助。 文档说还需要从 istream 读取 Severity 的功能,但我检查了它在 boost 中的 trivial.hpp 中,所以我想我不应该自己定义它。
我在这里缺少什么?
【问题讨论】: