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;
};
2
  • 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. Commented Oct 10, 2012 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. Commented Oct 15, 2012 at 11:51

1 Answer 1

4
+100

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

Sign up to request clarification or add additional context in comments.

4 Comments

This helps in case die gets called, but not when there is an unhandled exception - e.g. calling a method on an undef value.
How do you figure? Here is demo of it working perl -e " $SIG{__DIE__} = sub { warn join q/ /, 666, @_ }; $foo->what; "
I have written a small program and just called print, warn and also just tried to create/write to an error file.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.