spdlog icon indicating copy to clipboard operation
spdlog copied to clipboard

How can I get this output format?

Open nyckmaia opened this issue 2 years ago • 1 comments

Hi, I would like to know how can I set different formats for each spdlog level. By default, I got this output format:

[2022-07-05 14:25:26.685] [info] Welcome to spdlog!

What I would like

  • For level: info
Welcome to spdlog!
  • For level: warning
[warning] Welcome to spdlog!
  • For levels: error, critical and debug
[filename:lineNumber] [error] Welcome to spdlog!

Second question

Is there a way to add the function name (PRETTY_FUNCTION) in the log? Like:

[filename:lineNumber] [functionName] [error] Welcome to spdlog!

Could you help me?

Thank you,

nyckmaia avatar Jul 05 '22 17:07 nyckmaia

Per-log-level formatting is not supported. However, you can create your own custom sink and format it specifically for each log level. Wiki: https://github.com/gabime/spdlog/wiki/4.-Sinks#implementing-your-own-sink

Use the format flags %@ and %! . Note that these flags will not show anything unless you use the logging macro such as SPDLOG_INFO and SPDLOG_LOGGER_INFO. Wiki: https://github.com/gabime/spdlog/wiki/3.-Custom-formatting

tt4g avatar Jul 05 '22 20:07 tt4g

If you don't like the awkwardness of typing the ALL CAPS macro (I don't), you can write your own macro, like so:

#define debug(...) log(spdlog::source_loc{FILE, LINE, static_cast<const char *>(FUNCTION)}, spdlog::level::debug, VA_ARGS)

This will work with logger.debug("Hello macro");

or even logger.debug(format("Hello {} macro", "formatted")); with #define format fmt::format just to save some keystrokes.

Getting my logger static spdlog::logger logger = getLog();

So I end up with a very log4j like syntax that gives line numbers, file, method.

See also related open issue #1823. Output with file:linenumber is extremely useful in an IDE in order for the log output to link to the source. Wouldn't take a big effort to make something like the above configurable in spdlog if they thought it was important, one would think. Meaning just to make the file and line number accessible with less awkward macro identifier.

oct15demo avatar Aug 21 '22 19:08 oct15demo

@Thank you so much @oct15demo ! Great!

nyckmaia avatar Aug 22 '22 12:08 nyckmaia