spdlog icon indicating copy to clipboard operation
spdlog copied to clipboard

Multi-sink logger behavior with File and line number set in the pattern

Open python152 opened this issue 4 years ago • 4 comments

hi all -

Using the multi-sink logger example, I'd like to add %g %# in the file_sink pattern to print out file and line number. However, it seems the only way to call this is through SPDLOG_LOGGER_TRACE(logger, ...). If I use logger->trace(), it will not honor the pattern. Is this correct behavior? or am I missing something here?

// A logger with multiple sinks (stdout and file) - each with a different format and log level.
void multi_sink_example()
{
    auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
    console_sink->set_level(spdlog::level::warn);
    console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v");

    auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/multisink.txt", true);
    file_sink->set_level(spdlog::level::trace);

    spdlog::logger logger("multi_sink", {console_sink, file_sink});
    logger.set_level(spdlog::level::debug);
    logger.warn("this should appear in both console and file");
    logger.info("this message should not appear in the console, only in the file");
}

TIA

python152 avatar Aug 11 '21 13:08 python152

Right. This is a specification. See Wiki: https://github.com/gabime/spdlog/wiki/3.-Custom-formatting#pattern-flags

Another way. you can use logger->log(spdlog::source_loc{__FILE__, __LINE__, SPDLOG_FUNCTION}, spdlog::level::trace, other arguments...) instead of logging macro such as SPDLOG_LOGGER_TRACE and SPDLOG_LOGGER_DEBUG.

https://github.com/gabime/spdlog/blob/v1.9.1/include/spdlog/spdlog.h#L291-L299

tt4g avatar Aug 12 '21 11:08 tt4g

@tt4g thanks for the clarification. A quick follow up, If I call my logger directly for tracing (writing to file), can I still compile away? (like SPDLOG_XXX). I can't set spdlog::level::off because I want to info to show up; and if I set to spdlog::level::info, am I paying the performance penalty for tracing calls? TIA

python152 avatar Aug 12 '21 14:08 python152

Logging macros (SPDLOG_TRACE, SPDLOG_LOGGING_TRACE, etc...) less than or equal to the log level of the SPDLOG_ACTIVE_LEVEL macro are converted to (void) 0 in preprocessing, so there is no cost to call the function. https://github.com/gabime/spdlog/wiki/0.-FAQ#how-to-remove-all-debug-statements-at-compile-time-

Calling the log function in any other way incurs costs such as comparing log levels.

tt4g avatar Aug 12 '21 14:08 tt4g

super, in that case, I think I can do the same by defining my own macros using mylogger, and compile away it. thanks a lot!

python152 avatar Aug 13 '21 01:08 python152