gabime / spdlog

Fast C++ logging library.
Other
24k stars 4.5k forks source link

Why customized logger can't print function name? #3148

Closed xudooo closed 2 months ago

xudooo commented 2 months ago

I'm a beginner and I'm wondering why the default logger prints the information about function name and line number, while the customized logger doesn't. How should I set it up to be able to print this information? Thanks.

code

void configLog(const int &logLevel, const std::string &fileName, const int &maxFiles, const bool &enableConsole)
    // xxx
    spdlog::set_pattern(*spdlog::default_logger(), "[%Y-%m-%d %H:%M:%S.%e] [%n] [%t] [%^%l%$] [%s:%#:%!] %v"); // this works
    spdlog::default_logger()->flush_on(spdlog::level::info);
}

SPDLOG_INLINE std::shared_ptr<spdlog::logger> &another_logger() {
    static auto s_logger = spdlog::stdout_color_mt("");
    return s_logger;
}

SPDLOG_INLINE void set_another_logger(std::shared_ptr<spdlog::logger> new_logger) {
    another_logger() = std::move(new_logger);
}

void configAnotherLogger() {
    using stdout_color_sink_mt = spdlog::sinks::ansicolor_stdout_sink_mt;
    std::vector<spdlog::sink_ptr> sinks;
    auto                          console_sink = std::make_shared<stdout_color_sink_mt>();
    sinks.emplace_back(console_sink); // no file_sink
    spdlog::logger logger("another", sinks.begin(), sinks.end());
    set_another_logger(std::make_shared<spdlog::logger>(logger));
    spdlog::set_pattern(*another_logger(), "[%Y-%m-%d %H:%M:%S.%e] [%n] [%t] [%^%l%$] [%s:%#:%!] %v");  // here ' [%s:%#:%!]' doesn't work
    another_logger()->set_level(spdlog::level::debug);
    another_logger()->flush_on(spdlog::level::info);
}

void test() {
    // default logger
    configLog(atoi(argv[1]), "test.log", 24 * 14, true);
    SPDLOG_INFO("{:>8} aligned, {:<8} aligned", "right", "left");

    // another logger
    configAnotherLogger();
    another_logger()->info("Hi, I am another logger");
}

result

[2024-07-29 11:33:02.433] [test] [438187] [info] [main.cpp:68:main] right aligned, left aligned [2024-07-29 11:33:02.433] [another] [438187] [info] [::] Hi, I am another logger image

version

2.0.0

tt4g commented 2 months ago

Logging macros such as SPDLOG_LOGGER_INFO working for you. See wiki: https://github.com/gabime/spdlog/wiki/0.-FAQ#source-information-do-not-appear-when-using-custom-format

-    another_logger()->info("Hi, I am another logger");
+    std::shared_ptr<spdlog::logger> another = another_logger();
+    SPDLOG_LOGGER_INFO(another, "Hi, I am another logger");

BTW: latest version is 1.14.1, version 2 not released.

xudooo commented 2 months ago

Thanks, that worked for me. BTW, I was seeing the version in version.h as 2.0.0: image but that doesn't matter, anyway thanks!

tt4g commented 2 months ago

Maybe using master branch, current working branch is v1.x.