Search code examples
c++c++17spdlog

How to escape spdlog message?


I'm using spdlog to log all messages. My log pattern is a JSON format. I'm escaping messages manually in all log calls. Is there any way exists to escape messages automatically in spdlog layer?

Sample of manually escaping:

spdlog::info(escape_message(data));

It should be automatically handled inside spdlog layer:

spdlog::info(data);

Solution

  • I've found a way to solve it.

    I should implement a custom formatter class and then in the format method, I escape the message by for example escape_message(msg.payload.data()) and then call spdlog::log(msg.source, msg.level, escape_message(msg.payload.data())), spdlog::info or ... inside this method.

    Note: inside the format method I set a log pattern, because outside of the class, if I call set_formatter, then calling set_pattern, doesn't work well.