在我的程序中,目前我正在使用boost :: log来编写日志。如果像log4cxx一样,我想通过在运行时修改配置来动态更新日志输出级别,我该怎么办?另一个问题是输出日志级别是1,2,3这样的数字,不是信息,调试这样的字符串,不知道怎么解决,谢谢大家,这里是我的代码:
BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(lg, boost::log::sources::severity_logger_mt< >)
int init_logger(const std::string& file_name_of_cfg) {
if (file_name_of_cfg.empty()) {
std::cerr << "FAILURE: Filename of config for logger is empty." << std::endl;
return -1;
}
try
{
// Open the file
std::ifstream file_of_cfg(file_name_of_cfg);
if (!file_of_cfg.is_open())
{
std::cerr << "FAILURE: Could not open " << file_name_of_cfg << " file" << std::endl;
return -1;
}
// Read the file_of_cfg and initialize logging library
boost::log::init_from_stream(file_of_cfg);
// Add some attributes
boost::log::add_common_attributes();
return 0;
}
catch (const std::exception& e)
{
std::cerr << "FAILURE: " << e.what() << std::endl;
return -1;
}
}
这是我的设置:
[Core]
Filter="%Severity% >= 1"
[Sinks.1]
Filter="%Severity% >= 1"
Destination=Console
AutoFlush=true
Format="[%TimeStamp%] [%ThreadID%] <%Severity%> %Message%"
Asynchronous=false
[Sinks.2]
Filter="%Severity% >= 2"
Destination=TextFile
AutoFlush=true
Format="[%TimeStamp%] [%ThreadID%] <%Severity%> %Message%"
Asynchronous=false
Target="logs"
FileName="logs/cple.logger.%Y%m%dT%H%M%S.%a.%5N.log"
RotationTimePoint="00:00:00"
RotationSize=104857600
MinFreeSpace=4294967296
Boost.Log不提供用于从文件更新配置的API。您最接近的方法是删除所有接收器,然后重新读取配置文件,这将创建并向核心添加新接收器。
boost::log::core::get()->remove_all_sinks();
boost::log::init_from_stream(file_of_cfg);
您无需触摸记录器或属性,因为它们不受配置文件管理。但请注意,由于此操作不是原子操作,因此您可能会错过在核心中未注册接收器时发出的一些日志记录。
更正确的解决方案是避免直接从设置初始化日志库并自行解释配置文件。您可以通过调用parse_settings
来读取设置文件,然后遍历设置容器以创建和初始化接收器。库中的Filter and formatter parsers可用于初始化过滤器和格式化程序。在注册核心之前,您可以将共享指针保存到数据结构中的接收器。当您需要更新配置时,您只需阅读配置文件并通过您保存的指针更新接收器。您发现需要更新配置的确切方式特定于应用程序与用户的交互方式。
另一个问题是输出日志级别是1,2,3这样的数字,而不是信息,调试这样的字符串
如果你想在配置文件的过滤器中使用你的枚举的字符串表示,那么你应该为你的枚举类型注册a filter factory。该工厂应该能够解析字符串中的枚举值。同样,如果要在日志文件中查看枚举值的字符串,则应注册a formatter factory。