3

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

ATK
  • 1,296
  • 10
  • 26

2 Answers2

4

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 formatters.

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.

Sprite
  • 3,222
  • 1
  • 12
  • 29
2

Try this:

#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/spdlog.h"

int main() {
  auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
  auto stdout_sink_b = 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_b);

  a->set_pattern("%v");
  b->set_pattern("debug %v");

  a->info("a");
  b->info("b");
}

The output is:

a
debug b
ramsay
  • 3,197
  • 2
  • 14
  • 13
  • That would work yes. Problem is when you want to extend this to log files. Then, you end up having two log files – ATK May 08 '22 at 12:51
  • Do you mean this case: https://github.com/gabime/spdlog#logger-with-multi-sinks---each-with-different-format-and-log-level? – ramsay May 08 '22 at 13:04