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

I've been using log4perl to help keep debugging logs for a web application. Recently, I decided that it would be helpful to include the session ID in every log entry. I thought it would be as simple as declaring a cspec like this: log4perl.PatternLayout.cspec.s = sub {return $session->id}

However, when I run the application, I recieve the following error: Can't evaluate 'sub {return $session->id}' (Global symbol "$session" requires explicit package name at (eval 37) line 1.)at /usr/lib/perl5/site_perl/5.8.0/Log/Log4perl/Config.pm line 708. Initially, I though this was because I was initalizing the log before I had initalized the session. However, after reviewing my code, this is not the case.

Is there some way to make log4perl aware of the value of the session variable? I've included the relevant code below, but I'm not sure what I could do differently.

# Check to see if we have a session. If so, load it's information. # If not, we need to create one and then cookie the user. my $session = new CGI::Session("driver:DB_File", $cgi, {Directory=>'/u +sr/local/apache/htdocs/addressbook'}); # Init the logger Log::Log4perl->init("/usr/local/apache/htdocs/addressbook/log4perl.con +f");

Replies are listed 'Best First'.
Re: Custom cspec's in Net::Log4perl
by jimbojones (Friar) on Apr 21, 2005 at 20:34 UTC
    Hi

    I'm not too sure about this, since I'm not famaliar with Log4Perl ...

    isn't $session in your main package? If so, try

    log4perl.PatternLayout.cspec.s = sub {return $::session->id}

      I tried that, and it silenced strict's complaint, but it now gives Can't call method "id" on an undefined value at (eval 36) line 1.. So, apparently the value still isn't avalible to the module.

        Hi,

        Sorry, I didn't read your code carefully enough.

        # Check to see if we have a session. If so, load it's information. # If not, we need to create one and then cookie the user. #### JJ comment #### 'my' makes this lexically scoped #### change to 'our' or $::session to be visible #### in other scopes my $session = new CGI::Session("driver:DB_File", $cgi, {Directory=>'/u +sr/local/apache/htdocs/addressbook'}); # Init the logger Log::Log4perl->init("/usr/local/apache/htdocs/addressbook/log4perl.con +f");
        you need to change my $session to something package scoped, like $::session. Then, it's somewhat of a global variable, so be carefull.

        - j