Search code examples
perlfatal-errorlog4perl

Perl: Log4Perl call log4perl in case of unhandled error


Is there a way in log4Perl that I can force my programs to log fatal even outside an eval clause? I want to achieve to call log4perl also in case of any unhandled program termination. Prefereably I would like to add the related error handler inside my standard module which is loaded with all my Perl programs.
The Perl version is currently 5.8, but I am upgrading soon.
This the test code for the given answer. I see neither a DIE on the screen nor that die.txt is created.

 use Log::Log4perl qw(get_logger);
$a->test();
$SIG{__DIE__} = sub {
 warn "DIE";
 open DIE,">die.txt";
 print DIE "died\n";
 close DIE;
};

Solution

  • Looks like the FAQ How can I make sure my application logs a message when it dies unexpectedly?

    use Log::Log4perl qw(get_logger);
    
    $SIG{__DIE__} = sub {
        if($^S) {
            # We're in an eval {} and don't want log
            # this message but catch it later
            return;
        }
        local $Log::Log4perl::caller_depth =
              $Log::Log4perl::caller_depth + 1;
        my $logger = get_logger("");
        $logger->fatal(@_);
        die @_; # Now terminate really
    };
    

    See perlipc for more