|
From: Mike S. <m...@pe...> - 2007-03-23 05:46:56
|
On Thu, 22 Mar 2007, Livshits, Alex, GCM wrote:
> I got standard error header message printing environment variables which
> takes either file handle or stdout, stderr. What's the way to print it
> to the logger?
Let me summarize to make sure I understand correctly: You have a function
that prints to a filehandle. You want to tie into that filehandle and
forward all arriving messages to a Log4perl logger.
First, let's write a package that ties a file handle and forwards it
to a Log4perl logger:
package FileHandleLogger;
use Log::Log4perl qw(:levels get_logger);
sub TIEHANDLE {
my($class, %options) = @_;
my $self = {
level => $DEBUG,
category => '',
%options
};
$self->{logger} = get_logger($self->{category}),
bless $self, $class;
}
sub PRINT {
my($self, @rest) = @_;
$Log::Log4perl::caller_depth++;
$self->{logger}->log($self->{level}, @rest);
$Log::Log4perl::caller_depth--;
}
sub PRINTF {
my($self, $fmt, @rest) = @_;
$Log::Log4perl::caller_depth++;
$self->PRINT(sprintf($fmt, @rest));
$Log::Log4perl::caller_depth--;
}
1;
Now, if you have a function like
sub function_printing_to_fh {
my($fh) = @_;
printf $fh "Hi there!\n";
}
which takes a filehandle and prints something to it, it can be used
with Log4perl:
use Log::Log4perl qw(:easy);
usa FileHandleLogger;
Log::Log4perl->easy_init($DEBUG);
tie *SOMEHANDLE, 'FileHandleLogger' or
die "tie failed ($!)";
function_printing_to_fh(*SOMEHANDLE);
# prints "2007/03/22 21:43:30 Hi there!"
If you want, you can even specify a different log level or category:
tie *SOMEHANDLE, 'FileHandleLogger',
level => $INFO, category => "Foo::Bar" or die "tie failed ($!)";
Is this what you're looking for?
-- Mike
Mike Schilli
m...@pe...
|