E
Eduard W. Lohmann
Hello. I write this little thing to help me log from several instances of
the same class in apache, mod_perl. But I can't figure one thing out.
package Logger;
require Carp;
# Write the message to the file pointed to by $fh with the time prepended
# and the place appended
sub log_ {
my $fh = shift;
print( $fh scalar(localtime()), ': ', Carp::shortmess("@_") );
};
Now this works fine, but if I replace this with:
sub log_ {
print( $_[0] scalar(localtime()), ': ', Carp::shortmess("@_") );
};
I get print on unopened filehandle. I can't seem figure out why.
# Turn array into a nice string, like (1, 2, 3) and log it
sub log_ARRAY {
log_($_[0], '('.join(', ', @{$_[1]}).')');
};
# Turn hash into a nice string, like { 1 => 'one', 2 => 'two' } and log it
sub log_HASH {
log_($_[0],'{ '.join(', ', map("$_ => ".$_[1]{$_},sort keys %{$_[1]})).' }');
};
# Treat anything else as a string and log it
sub AUTOLOAD {
goto &log_ if $AUTOLOAD =~ /^log_/;
};
# Logger::method('command', 'filename')
# Open 'filename' and create a sub in the callers package named 'command'
# that logs to it, nicely formatted.
sub method {
open(my $fh, ">> $_[1]") or $fh = \*STRERR;
*{ caller().'::'.$_[0]} = sub {
&{'log_'.ref($_) }($fh, $_) foreach (@_);
};
};
1;
the same class in apache, mod_perl. But I can't figure one thing out.
package Logger;
require Carp;
# Write the message to the file pointed to by $fh with the time prepended
# and the place appended
sub log_ {
my $fh = shift;
print( $fh scalar(localtime()), ': ', Carp::shortmess("@_") );
};
Now this works fine, but if I replace this with:
sub log_ {
print( $_[0] scalar(localtime()), ': ', Carp::shortmess("@_") );
};
I get print on unopened filehandle. I can't seem figure out why.
# Turn array into a nice string, like (1, 2, 3) and log it
sub log_ARRAY {
log_($_[0], '('.join(', ', @{$_[1]}).')');
};
# Turn hash into a nice string, like { 1 => 'one', 2 => 'two' } and log it
sub log_HASH {
log_($_[0],'{ '.join(', ', map("$_ => ".$_[1]{$_},sort keys %{$_[1]})).' }');
};
# Treat anything else as a string and log it
sub AUTOLOAD {
goto &log_ if $AUTOLOAD =~ /^log_/;
};
# Logger::method('command', 'filename')
# Open 'filename' and create a sub in the callers package named 'command'
# that logs to it, nicely formatted.
sub method {
open(my $fh, ">> $_[1]") or $fh = \*STRERR;
*{ caller().'::'.$_[0]} = sub {
&{'log_'.ref($_) }($fh, $_) foreach (@_);
};
};
1;