Flush log on signal

This commit is contained in:
Nikita Lisitsa 2023-01-04 16:06:34 +03:00
parent 267304ce6a
commit d60eb6f659
2 changed files with 40 additions and 0 deletions

View file

@ -43,6 +43,7 @@ namespace psemek::log
struct sink
{
virtual void put_message(message const & msg) = 0;
virtual void flush() = 0;
virtual ~sink() {}
};

View file

@ -10,6 +10,7 @@
#include <thread>
#include <atomic>
#include <vector>
#include <csignal>
namespace psemek::log
{
@ -25,6 +26,39 @@ namespace psemek::log
std::mutex sinks_mutex;
std::vector<std::unique_ptr<sink>> sinks;
std::pair<int, std::string> const signals[] =
{
{SIGSEGV, "Aborting due to SIGSEGV"},
{SIGABRT, "Aborting due to SIGABRT"},
{SIGTERM, "Aborting due to SIGTERM"},
};
struct sinks_flusher
{
sinks_flusher()
{
for (auto const & p : signals)
std::signal(p.first, &handler);
}
private:
static void handler(int signal)
{
for (auto const & p : signals)
{
if (p.first == signal)
{
put_message(level::error, p.second);
break;
}
}
for (auto & sink : sinks)
sink->flush();
std::exit(1);
}
} flusher;
void put_message(level l, std::string const & str, std::string const & thread_name)
{
message msg
@ -76,6 +110,11 @@ namespace psemek::log
stream_->write(str.data(), str.size());
}
void flush() override
{
// stream_->flush();
}
private:
std::unique_ptr<io::ostream> stream_;
level level_;