0

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);
mortymacs
  • 3,456
  • 3
  • 27
  • 53

2 Answers2

3

Tell spdlog to format a single string, rather than interpreting the string itself as the format string:

spdlog::info("{}", data);
Eric
  • 95,302
  • 53
  • 242
  • 374
  • Thanks for your answer, I've tried it but it doesn't work. This is the result: `{"message": "hi"hi"}`. I got the data by `std::cin` (`hi"hi`). – mortymacs Oct 05 '19 at 18:17
  • How are you constructing your JSON? It sounds like you're looking for json escaping, not spdlog escaping. Can you clarify your question? I was under the impresssion that `data` itself contained json, and you were running into trouble with embedded `{}` characters. – Eric Oct 05 '19 at 21:20
  • My data is not a JSON, actually, my spdlog pattern is a JSON format. For example: `{"message": "%v"}`. My data is a string. – mortymacs Oct 06 '19 at 12:53
  • 1
    @mortezaipo: That would be good to edit into your question. You're right, my answer does not help you for that case. – Eric Oct 06 '19 at 21:20
  • your answer did help me though! Thank you – Dávid Tóth May 29 '22 at 17:05
0

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.

mortymacs
  • 3,456
  • 3
  • 27
  • 53
  • In case you had to do it the hard way... here's the easy explaination for it: https://github.com/gabime/spdlog/wiki/3.-Custom-formatting :-) – andreee Oct 04 '19 at 10:55
  • @andreee I exactly followed that road. but with a little customization – mortymacs Oct 04 '19 at 11:00