Search code examples
perllogginglog4perl

Use Log4Perl in sub routine?


If I make an abstraction function with Log4Perl inside, then it will output the line number where the $logger->error_die($m) line is, and not where the fatalError() function is.

sub fatalError {
    my $m = shift;
    email($m, $c->{subject});
    unlink $c->{lock};
    $logger->error_die($m);
}

fatalError("Directory $d ...");

In Bash have I solved the problem by writing [###] at the end of each error message, and parse the Bash script after wards to replace [###] with unique numbers. That way I knew exactly where the error output were from. However it is not optimal to have a second script modify your source code.

Question

Is there a way to have Log4Perl to write the line number where my fatalError() function were called, or how should the problem be solved?


Solution

  • The easy way is to add this line to your fatalError method:

    local $Log::Log4perl::caller_depth++;
    

    This will make Log4perl "skip" the current subroutine from the caller context.

    Alternatively, if you have many such wrapper methods, encapsulate them in a single package, and register them with Log4perl like this:

    Log::Log4perl->wrapper_register('My::Logger');
    

    This topic is covered in the Log::Log4perl documentation.