The following code :
#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"
int main() {
auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
auto a = std::make_shared<spdlog::logger>("a", stdout_sink);
auto b = std::make_shared<spdlog::logger>("b", stdout_sink);
a->set_pattern("%v");
b->set_pattern("debug %v");
a->info("a");
b->info("b");
}
outputs
debug a
debug b
rather than
a
debug b
It seems as though the spdlogger only remembers the last registered pattern. How do I achieve the intended as in having two loggers with different patterns
That would work yes. Problem is when you want to extend this to log files. Then, you end up having two log files
The answer is you can't, directly.
set_formatter
is just a wrapper of set_formatter(pattern_formatter{})
. In spdlog, a formatter is stored in a sink
rather than a logger
.
Just thought of a workaround if you really need this feature.
You can implement your own file_sink
, and then you can have multiple formatter
s.
There is a field logger_name
in struct log_msg
, you can use it to determine which logger the message came from, and use a different formatter. Note that if you did not set a name for a logger, the field is an empty string.