2

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;
};
lexu
  • 8,766
  • 5
  • 45
  • 63
weismat
  • 7,195
  • 3
  • 43
  • 58
  • Use surrounding backticks to “mask” underlines in the comments (turn them into the code where no formatting is allowed). // Reply to a comment to a deleted question. – ZyX Oct 10 '12 at 19:01
  • 1
    Your problem is that `$SIG{__DIE__}` has not been set yet at the point your error occurs. Just set `$SIG{__DIE__}` first, then it will work. – dan1111 Oct 15 '12 at 11:51

1 Answers1

4

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

so not liopa
  • 485
  • 2
  • 5
  • This helps in case die gets called, but not when there is an unhandled exception - e.g. calling a method on an undef value. – weismat Oct 11 '12 at 10:28
  • How do you figure? Here is demo of it working `perl -e " $SIG{__DIE__} = sub { warn join q/ /, 666, @_ }; $foo->what; " ` – so not liopa Oct 11 '12 at 12:57
  • I have written a small program and just called print, warn and also just tried to create/write to an error file. – weismat Oct 15 '12 at 06:31
  • 1
    @weismat, this looks like a good answer. If it doesn't meet your needs, I suggest updating your question with a code example that shows a case when this won't work. – dan1111 Oct 15 '12 at 10:02