1

I'm using spdlog and trying to create a logger object to be shared between multiple source files. However, whenever I use the built in spdlog::get() function it results in a segmentation fault error.

foo.cpp

#include "bar.h"

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

int main()
{
    // Create log sinks w/ destinations
    auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
    auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/myLogFile.log", true);
    
    // Format logging statements
    console_sink->set_pattern("[%Y-%m-%d %H:%M:%S] [%n] [%^%l%$] %v");
    file_sink->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [Thread:%t] [%n] [%l] %v");

    // Create multi-sink logger object
    spdlog::logger myLogger("myLogger", {console_sink, file_sink});

    myLogger.info("Hello World! - foo.cpp");

    loggerTest();

    return 0;
}

bar.h

#ifndef BAR_H
#define BAR_H

void loggerTest();

#endif

bar.cpp

#include "bar.h"

#include "spdlog/spdlog.h"

void loggerTest()
{
    std::shared_ptr<spdlog::logger> myLogger = spdlog::get("myLogger");
    myLogger->info("Hello World! - bar.cpp");
}

Why am I getting a segmentation fault error? How do I setup a logger to be shared between multiple source files?

ewaddicor
  • 29
  • 2
  • Read up on `spdlog::register_logger`. – user4581301 Feb 08 '23 at 01:09
  • Hmmm. seems to be easier said than done. When I tried to google up some good documentation to add to that last comment... Not much to be found. Here's a near-duplicate though: https://stackoverflow.com/questions/70663669/how-to-play-with-spdlog – user4581301 Feb 08 '23 at 01:11
  • `std::shared_ptr myLogger = spdlog::get("myLogger");` is awfully suspicious. Is it your intention to delete that logger? – Drew Dormann Feb 08 '23 at 01:15
  • This does lead to an important side note: Unless the documentation says otherwise, you should test smart pointers for null just like you wild with a raw pointer when someone returns one from a function with a possib8lity of failure. Usually null means error. – user4581301 Feb 08 '23 at 01:21

0 Answers0