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!


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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.