http://qs321.pair.com?node_id=324272

set_uk has asked for the wisdom of the Perl Monks concerning the following question:

I have code wrapped within a try catch block. The logger instead of using the surrounding method/function name uses ANON when printing with the layout [%d][%p] (%C) %M %m%n. I guess this is because try is the closest control structure to the call. If this is the case and the stack is:-
package method_a try logger_call
I get logger messages package::anon. So if I have a number of try statements wrapping my code its hard to see where the log came from using the pattern layout.
Is there a solution to this?

Edited by BazB fixed square brackets

Replies are listed 'Best First'.
Re: Log4Perl - ANON issue
by BazB (Priest) on Jan 26, 2004 at 21:08 UTC
    Named anonymous subs

    If the information in this post is inaccurate, or just plain wrong, don't just downvote - please post explaining what's wrong.
    That way everyone learns.

      Job done - thanks very much
      I tried to implement the fix for naming an eval statement (found in the thread)- using the line directive - but I cant make it work.
      eval { # line 23 "Name I want to call this eval" code here };
      Any ideas.
Re: Log4Perl - ANON issue
by cees (Curate) on Jan 26, 2004 at 21:26 UTC

    The try catch block is implemented as an anonymous subroutine which is causing your problem. You can specify the caller depth that Log4perl uses in the log entry.

    local $Log::Log4perl::caller_depth = 2;

    Just put this line somewhere before the call to the logger. The local should localize this change to only affect this part of your program.

      You might want to consider to log the call stack when something fails. This way, you will easily see where the error originated, whether in an ANON block or not. Choose log level and error handling wisely..
      _show_call_stack() if (!$retval); [...] sub _show_call_stack { my $max_depth = 7; my $i = 1; if ($log->is_debug()) { $log->debug("--- Begin stack trace ---"); while ( (my @call = (caller($i++))) && ($i<$max_depth)) { $log->debug("$call[1] line $call[2] in function call[3]"); } $log->debug("--- End stack trace ---"); } }