Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
I needed a super-simple way to have a log file for a script that uses some modules of mine, and I wanted the modules to write to the same log file as the script. Here's what I came up with.
In my script:
#!/opt/perl/bin/perl use strict; use warnings; use lib '.'; use MyModule; # ---------- open(my $logfile, '>>', 'blah.log') or die "Couldn't open log file."; sub my_logging_fn { my ($log_msg) = @_; print {$logfile} $log_msg, "\n"; } # ---------- # Set up MyModule to use our logging function. MyModule::set_logger_fn(\&my_logging_fn); # ---------- # main my_logging_fn("Doing something in the script."); MyModule::do_some_work(); my_logging_fn("Ok, that's all for now.");
And in MyModule.pm:
package MyModule; # Before calling any functions in this module, # be sure to first call `set_logger_fn(...)`. my $log_fn_ref; sub set_logger_fn { my ($fn_ref) = @_; $log_fn_ref = $fn_ref; } # ---------- sub do_some_work { # ... # write a log message. $log_fn_ref->("Doing some work in MyModule::do_some_work()"); # ... } 1;
If you see any ways this is broken, please let me know!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: my homemade solution to logging (module writes to same log file as the script). What do you think?
by ikegami (Patriarch) on Feb 25, 2010 at 18:53 UTC | |
by Anonymous Monk on Feb 25, 2010 at 20:28 UTC |