Search code examples
c++spdlog

How to play with spdlog?


I downloaded and followed the example 1.

Moved to example 2 (Create stdout/stderr logger object) and got stuck. Actually I can run it as it is but if I change

spdlog::get("console") to spdlog::get("err_logger") it crashes.

Am I supposed to change it like that?

#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"

void stdout_example()
{
    // create color multi threaded logger
    auto console = spdlog::stdout_color_mt("console");
    auto err_logger = spdlog::stderr_color_mt("stderr");
    spdlog::get("err_logger")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name)");
}

int main()
{
    stdout_example();
    return 0;
}

I also tried Basic file logger example:

#include <iostream>
#include "spdlog/sinks/basic_file_sink.h"

void basic_logfile_example()
{
    try
    {
        auto logger = spdlog::basic_logger_mt("basic_logger", "logs/basic-log.txt");
    }
    catch (const spdlog::spdlog_ex &ex)
    {
        std::cout << "Log init failed: " << ex.what() << std::endl;
    }
}

int main()
{
    basic_logfile_example();
    return 0;
}

And I see it creates basic-log.txt file but there is nothing on it.


Solution

  • Because you need to register err_logger logger first. There is no default err_logger as far as I know. spdlog::get() returns logger based on its registered name, not variable.

    You need a code like this. Code is complex and you may not need all of it though:

    #include "spdlog/sinks/stdout_color_sinks.h"
    #include "spdlog/sinks/rotating_file_sink.h"
    
    void multi_sink_example2()
    {
        spdlog::init_thread_pool(8192, 1);
        auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt >();
        auto rotating_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>("mylog.txt", 1024*1024*10, 3);
        std::vector<spdlog::sink_ptr> sinks {stdout_sink, rotating_sink};
        auto logger = std::make_shared<spdlog::async_logger>("err_logger", sinks.begin(), sinks.end(), spdlog::thread_pool(), spdlog::async_overflow_policy::block);
        spdlog::register_logger(logger); //<-- this line registers logger for spdlog::get
    }
    

    and after this code, you can use spdlog::get("err_logger").

    You can read about creating and registering loggers here.

    I think spdlog::stderr_color_mt("stderr"); registers logger with name stderr so spdlog::get("stderr") may work, but have not tested myself.