in reply to my homemade solution to logging (module writes to same log file as the script). What do you think?

That's fine, although the logging module usually handles the formatting. It saves you from writing the formating code in every script.
use My::Logger; open(my $log_fh, '>>', 'blah.log') or die "Couldn't open log file."; My::Logger->set_handle($log_fh); My::Logger->log("Processing..."); ... My::Logger->log("done.");
package My::Logger; my $fh = *STDERR; sub set_handle { my ($class, $new_fh) = @_; $fh = $new_fh; } sub log { my $msg = join('', @_); $msg =~ s/\n+\z/\n/; print $fh $msg; } 1;

You might want to let the module handle opening the file too (passing it a file name).

  • Comment on Re: my homemade solution to logging (module writes to same log file as the script). What do you think?
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: my homemade solution to logging (module writes to same log file as the script). What do you think?
by Anonymous Monk on Feb 25, 2010 at 20:28 UTC

    Ah! I don't know why I didn't see that. I could just use a separate MyLoggingModule.pm:

    package MyLoggingModule; use strict; use warnings; # ---------- my $logfile; # ---------- sub init { my ($logfile_name) = @_; open($logfile, '>>', $logfile_name) or die "Couldn't open log file."; } sub loggit { my ($log_msg) = @_; print {$logfile} $log_msg, "\n"; } # ---------- 1;

    and then my script looks like this:

    #!/opt/perl/bin/perl use strict; use warnings; use lib '.'; use MyLoggingModule; use MyModule; use MyOtherModule; # ---------- MyLoggingModule::init('blah.log'); MyLoggingModule::loggit("Doing something in the script..."); MyModule::foo(); MyOtherModule::bar(); MyLoggingModule::loggit("My work here is done.");

    and my modules look like this:

    package MyModule; use strict; use warnings; use lib '.'; use MyLoggingModule; # ---------- sub foo { # ... # write a log message. MyLoggingModule::loggit("Doing some work in MyModule::foo()"); # ... } 1;

    and this:

    package MyOtherModule; use strict; use warnings; use lib '.'; use MyLoggingModule; # ---------- sub bar { # ... # write a log message. MyLoggingModule::loggit("Doing some work in MyOtherModule::bar()") +; # ... } 1;

    Thanks!