I'd take a bit of a different approach, and have the logging module create a default log handle internally, with a log() function that takes a message and an optional filename. If the optional filename is sent in, we create a new handle internally and log to it, otherwise we log to the default handle. Here's some code I put together very hastily as an example:
use warnings;
use strict;
package Log; {
sub new {
my $self = bless {}, shift;
my $log_file = shift;
open my $fh, '>', $log_file or die $!;
$self->{default_log} = $fh;
return $self;
}
sub log {
my ($self, $msg, $log) = @_;
my $log_fh;
if (defined $log){
# filename sent in
open my $fh, '>>', $log or die $!;
$log_fh = $fh;
}
else {
# use the default fh
$log_fh = $self->{default_log};
}
print $log_fh "$msg\n";
}
}
package main; {
my $log = Log->new('default.log');
$log->log('default log message');
$log->log('alternate log file msg', 'not-default.log');
}
Default log file:
$ cat default.log
default log message
Alternate log file:
$ cat non-default.log
alternate log file msg
Is that kind of the idea you're after? Something along these lines prevents the user of the module of having to create and send in their own handles. If I'm off-base, just let us know.
update: If you want the user to be able to send in their own file handle instead of just a file name, the log() method could be changed like this:
sub log {
my ($self, $msg, $log) = @_;
my $log_fh;
if (defined $log && ref $log ne 'GLOB'){
# filename sent in
open my $fh, '>>', $log or die $!;
$log_fh = $fh;
}
elsif (defined $log && ref $log eq 'GLOB'){
# file handle sent in
$log_fh = $log;
}
else {
# use the default fh
$log_fh = $self->{default_log};
}
...and called like this (continuing on with the main example above):
open my $fh, '>>', 'alternate.log' or die $!;
$log->log('msg', $fh);
/update |