4

I want to generate a log for my Perl script. But when I am using Log::Log4perl how can I capture the errors which will be thrown by the script in any case. How to log that to the log file.Currently whatever I write explicitely in variouys tags like ERROR(),DEBUG() etc. are the only one being printed to the log file.

Is there any way to do this using Log::Log4perl.

For Example in the below code:

use strict;
use warnings;
use Log::Log4perl qw(:easy);

Log::Log4perl->easy_init( { level   => $DEBUG,
                            file    => ">>test.log" });

my $logger = Log::Log4perl->get_logger();                           

$logger->fatal( "This is", " fatal");
$logger->error( "This is error");
$logger->warn(  "This is warn");
$logger->info(  "This is info");
$logger->debug( "This is debug");
$logger->trace( "This is trace");

my $a = 10;

my $b = $a/0; 

The divide by zero error is not logged to the script. Mine original script is too complex to check for each error so want something which logs the error on stderr to the log file also.

Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
Mohit
  • 608
  • 4
  • 19

1 Answers1

5
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;
    }
    $Log::Log4perl::caller_depth++;
    my $logger = get_logger("");
    $logger->fatal(@_);
    die @_; # Now terminate really
};

Also see Log4perl - how can I make sure my application logs a message when it dies unexpectedly?

Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
  • When do we enter the if block in the sub above. As I only want that whenever an error which will trigger the application to die occurs I want to log it and stop the script execution. – Mohit Jan 16 '17 at 10:28
  • @Mohit: `$^S` returns true when it is executing an `eval`. – Chankey Pathak Jan 16 '17 at 10:34