Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
up vote 3 down vote accepted
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?

share|improve this answer
    
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 at 10:28
    
@Mohit: $^S returns true when it is executing an eval. – Chankey Pathak Jan 16 at 10:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.