Printing to multiple files ... without changing my code.

Eric Wilhelm scratchcomputing at
Fri Sep 15 17:38:42 BST 2006

# from Dan Rowles
# on Friday 15 September 2006 07:58 am:

>Would you be willing to replace your print statements with something
>like Log::Log4perl?

I'll second that, but add that these maybe should have been warn() 
instead of print.  I never use print for anything besides output, and 
then usually only to a filehandle variable (which might = \*STDOUT.)

This allowed us to install a $SIG{__WARN__} which calls the logger as we 
phase into only using logger calls.

>Much more heavyweight than just using print, 

And that.

>but *very* flexible :) 

And that.

If you think doing "my $logger = Log... ... ... (man, this is way too 
long) ... ->new()" is a bit tedious, make your own frontend (e.g. 
My::Logger) which exports something like "sub L (@) {...}".  This also 
makes a great wafer-thin layer in which to store your policy, 
$SIG{__WARN__}, etc.  (Partly inspired by Jifty::Logger.)

I set mine up to use caller() as the log class, optionally appending 
whatever tag is in the L($tag) call.

  sub L (@) {
    my $caller = caller;
    my @tags = @_;
    Log::Log4perl->get_logger(join('.', $caller, map({"#$_"} @tags)));

I also have a "root logger" RL() which doesn't do the $caller stuff in 
the get_logger() call (for tags that span multiple modules -- 
unfortunately a requirement for subclasses unless you want to write 
logger wrappers into all of your base classes.)

So, instead of:

  warn "foo";

You do:

  use My::Logger;

"Everything goes wrong all at once."
--Quantized Revision of Murphy's Law

More information about the mailing list