Home > Net >  Make spdlog save the file before app crashes
Make spdlog save the file before app crashes

Time:02-21

I added logging capabilities to my application and it working fine. However in one particular case it is crashing, and in that case I cannot see the logs.

Looks like my application is crashing before the log file is saved (I guess). Can I force spdlog to save the file?

CodePudding user response:

you could call the logger->flush() function to manual flush. or you could use my_logger->flush_on(spdlog::level::err) to set the minimum log level that will trigger automatic flush.

CodePudding user response:

I believe the best way is to implement the memory mapped file sink an use it instead of file sink. The reason is when application writes the data to the memory mapped file, the data written is available for read to the kernel/other app right away and you do not have to flush it.

I do not have an implementation for the memory mapped file sink, but you can start with boost::ostream adapter for the boost::mapped_file and create spdlog::ostream_sink_mt

// https://stackoverflow.com/questions/33051067/c-boost-write-memory-mapped-file
// https://spdlog.docsforge.com/v1.x/4.sinks/#available-sinks

#include <spdlog/spdlog.h>
#include <spdlog/sinks/ostream_sink.h>

#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/iostreams/stream.hpp>

#include <vector>
#include <memory>

namespace bio = boost::iostreams;

int main() {
    using namespace std;
    vector<string> strArray(2000000);

    bio::mapped_file_params params;
    params.path          = "text.txt";
    params.new_file_size = 65536;
    params.flags         = bio::mapped_file::mapmode::readwrite;

    bio::stream<bio::mapped_file_sink> out(params);
    auto ostream_sink = std::make_shared<spdlog::sinks::ostream_sink_mt> (out);
    auto logger = std::make_shared<spdlog::logger>("my_logger", ostream_sink);
    logger->info("Test message");
}

Credits:

  • Related