【发布时间】:2023-03-15 05:40:01
【问题描述】:
我尝试使用 Boost Log V2 设置记录器。输出应如下所示(文件 blubb.log):
2019-08-24 23:24:08 - 错误:来自源代码的您好。
我目前正在与严重级别的大写字母作斗争。其余的工作到目前为止。
severity level 提供 ::to_string() 对话,但我没有让它在 severity_type 中工作。所以我试图把数据放到一个字符串流中。
logger.cpp(不包含)
namespace logging = boost::log;
namespace src = boost::log::sources;
namespace expr = boost::log::expressions;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;
BOOST_LOG_ATTRIBUTE_KEYWORD(att_channel, "Channel", std::string);
typedef src::severity_channel_logger<logging::trivial::severity_level, std::string> severity_channel_logger_t;
typedef sinks::synchronous_sink< sinks::text_ostream_backend > synchronous_sink_t;
static std::map<std::string, severity_channel_logger_t> map_logger;
static std::unordered_set<std::string> profiles = { "blubb", "configreader", "connector", "downloader", "mlog", "output", "provider", "rest" };
static std::unordered_map<std::string, logging::trivial::severity_level> levels = {
{ "trace" , logging::trivial::trace},
{ "debug" , logging::trivial::debug},
{ "info" , logging::trivial::info},
{ "warning" , logging::trivial::warning},
{ "error" , logging::trivial::error},
{ "fatal" , logging::trivial::fatal}
};
Logger::Logger()
{
for (std::unordered_set<std::string>::iterator it = profiles.begin(); it != profiles.end(); it++)
{
map_logger[*it] = severity_channel_logger_t(keywords::channel = *it);
create_channel_logger(*it);
}
logging::add_common_attributes();
}
std::stringstream Logger::sev_toupper(logging::trivial::severity_type severity)
{
std::stringstream in;
std::stringstream out;
char c;
in << severity;
while (in >> c)
{
out << toupper(c);
}
return out;
}
void Logger::logmsg(std::string channel, const std::string level, const std::string message)
{
// fallback channel, if not in list
if (profiles.find(channel) == profiles.end())
channel = "rest";
BOOST_LOG_SEV(map_logger[channel], levels[level]) << message;
}
void Logger::create_channel_logger(std::string channel)
{
logging::add_file_log
(
keywords::file_name = channel+".log",
keywords::open_mode = std::ios_base::app,
keywords::filter = att_channel == channel,
keywords::auto_flush = true,
keywords::format =
(
expr::stream
<< expr::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S")
<< " - "
<< std::right << std::setw(7) << sev_toupper(logging::trivial::severity).str().c_str()
<< std::left << ": " << expr::smessage
)
);
}
main.cpp
int main(int, char*[])
{
Logger * lg = new Logger();
lg->logmsg("blubb", "error", "Hi, from Source Code!");
delete lg;
}
我的函数 sev_toupper() 产生 gargabe。 expr::stream 似乎以不同于 std::stringstream 的方式处理 logging::trivial::severity。
【问题讨论】:
-
你现在得到什么输出?这是数字序列吗?
-
我猜,severity_type 还是有问题的。在格式化流 (expr::stream) 中,它被转换为一些文本。但是当我尝试以任何其他方式转换它时,我只得到 \0 或任何垃圾字符。
标签: c++ c++11 logging boost-log