Search code examples
perllog4perl

Can a Log4perl filter access the Mapped Diagnostic Context?


I'm writting some Perl CGI scripts, and am using Log4perl to log to various files. I thought it may be useful to be able to trace a particular (or various) user's activities to a separate log file. I can put a hook into my session routine to stuff the userid into the MDC, but I don't know of any way to access the MDC from a filter. As far as I know, the MDC is only used for pattern creation.

Is this doable with Log4perl?

Per suggestion below I added a filter in my config file, but it's still not working:

log4perl.appender.User           = Log::Log4perl::Appender::File
log4perl.appender.User.filename  = /data/wwwwii/logs/appUser.log
log4perl.appender.User.syswrite  = 1
log4perl.appender.User.Filter    = User
log4perl.appender.User.layout    = PatternLayout
log4perl.appender.User.layout.ConversionPattern=%p{1} %d{ISO8601}Z [%03r] %15X{remoteAddr}/%05P %M %L  --> %m%n

log4perl.filter.User = sub { Log::Log4perl::MDC->get('userId') == 12; }

I stuff the userid as soon as I do the session lookup, but I never do get an appUser.log file created. No errors show up that I can see.


Solution

  • Can't you just do:

    my $value   = Log::Log4perl::MDC->get($key);   # for 1 value, or
    my $hashref = Log::Log4perl::MDC->get_context; # for the whole context