http://www.perlmonks.org?node_id=617396


in reply to Choosing logging module

Using the easy interface is a good way to start with Log::Log4perl, but to get much out of it you need to put a little more work into customizing it.

The approach I like is to use the class name as the generic logger, and to create subcategories for the certain types of logs in that class. A recent module I wrote used HTML::Parser for event based parsing, and I wanted to select which events were logged. Here is a very stripped down snippet that shows the logging definitions:

package SomeParser; use strict; use warnings; use Log::Log4perl; my $logger = Log::Log4perl->get_logger('parser'); my $logexport = Log::Log4perl->get_logger('parser.export'); my $logtext = Log::Log4perl->get_logger('parser.events.text'); my $logstart = Log::Log4perl->get_logger('parser.events.start'); my $logend = Log::Log4perl->get_logger('parser.events.end'); # stuff sub tag_opened { my ($self, $parser, $tag, $attr, $text) = @_; $logstart->is_debug && $logstart->debug(sprintf "<%s>", $tag); } sub tag_closed { my ($self, $parser, $tag) = @_; $logend->is_debug && $logend->debug(sprintf "</%s>", $tag); } 1;
I follow similar approaches throughout the code so I can selectively enable categories such as 'parser.events'.

Another area that I find useful is to have a base class for my test cases (or a library to load), and have the following snippet in it:

if ($ENV{TEST_VERBOSE}) { Log::Log4perl->easy_init({ level => $DEBUG, layout => '#%5p %F(%L) + - %m%n'}); } else { Log::Log4perl->easy_init({ level => $WARN, layout => '#%5p %F(%L) +- %m%n'}); }
This will set the log level to debug when the tests are run in verbose mode (e.g. prove -v t/*.t), otherwise it will be set to warn. In both cases it will have a # before the log message to fit in with the TAP output.