Matthew Cotton
Matthew Cotton

Reputation: 75

spdlog custom log tags

I would like to add some extra data to my log output depending on where it was logged. For instance I might have System A and System B, both spitting out log data, but perhaps I'm only interested in System B's log lines now so I could filter based on the tag.

In a previous system I had a log function that looked like LOG(level, tag, message) but I could also see a solution that could involve instantiating a logger with a tag for each system that would pipe to a default logger that catches all messages. So spdlog::tagged_logger systemALogger("System A");

This is almost the answer since loggers can have names, I could use the names as a tag, but can loggers redirect to a default logger? The default logger has several sinks that I would have to attach to the named logging solution.

So the final question would be, is there a way to add a custom tag to log messages in spdlog?

Upvotes: 0

Views: 2146

Answers (1)

kyku
kyku

Reputation: 6042

Once you have your log configured, you can clone() it and pass a custom logger name that will appear in the log output (given you have not change the formatting).

  auto logger = spdlog::default_logger()->clone("my_logger");
  logger->info("message from custom logger");
  spdlog::info("message from default logger");

The contents of the basic-log.txt is as follows:

[2020-12-02 09:35:58.801] [my_logger] [info] message from custom logger
[2020-12-02 09:35:58.802] [info] message from default logger

Upvotes: 2

Related Questions