bombela / backward-cpp

A beautiful stack trace pretty printer for C++
MIT License
3.68k stars 467 forks source link

How to store back trace info to a file? #260

Open Allen1218 opened 2 years ago

Allen1218 commented 2 years ago

How to store back trace info to a file?

I want to store this segment fault info to a file, how to realize(or configuration) it ? Thanks!

oold commented 2 years ago

This is not a help forum, but here's a minimal example of how to do it for one signal.

#include <backward.hpp>

#include <csignal>
#include <cstdlib>
#include <fstream>

// This is definitely not async-signal-safe. Let's hope it doesn't crash or hang.
void handler(int signo) {
    if (std::ofstream file_stream("my_stacktrace.log", std::ios::trunc); file_stream.is_open()) {
        file_stream << "Caught signal " << signo << ".\nTrace:\n";
        backward::StackTrace st;
        st.load_here(32);
        backward::Printer p;
        p.print(st, file_stream);
    }

    // Raise signal again. Should usually terminate the program.
    std::raise(signo);
}

int main() {
    // Repeat this for each signal you want to catch and log.
    struct sigaction act {};
    // Allow signal handler to re-raise signal and reset to default handler after entering.
    act.sa_flags = SA_NODEFER | SA_RESETHAND;
    act.sa_handler = &handler;
    sigfillset(&act.sa_mask); 
    sigdelset(&act.sa_mask, SIGSEGV /* or other signal */);
    if (sigaction(SIGSEGV /* or other signal */, &act, nullptr) == -1)
        std::exit(EXIT_FAILURE);

    int* invalid_ptr = nullptr;
    *invalid_ptr = 0; // Cause SIGSEGV. Could also std::raise(SIGSEGV).
}
bombela commented 1 year ago

Pass a file descriptor to the Printer.

Read the code source of the Printer part to make your very own printer/savefile.

On Sun, 10 Apr 2022, 20:56 Allen, @.***> wrote:

How to store back trace info to a file?

I want to store this segment fault info to a file, how to realize(or configuration) it ? Thanks!

— Reply to this email directly, view it on GitHub https://github.com/bombela/backward-cpp/issues/260, or unsubscribe https://github.com/notifications/unsubscribe-auth/AABUZDFG46ARZJY3TF5CPHLVEOPHLANCNFSM5TB32JJQ . You are receiving this because you are subscribed to this thread.Message ID: @.***>