automandc has asked for the wisdom of the Perl Monks concerning the following question:
My program has three log-related options: -l allows the user to specify an output log file and -s instead directs the program output to STDOUT instead of to a file. Throughout the program I print various messages to the log to record the progress. -v specifies a 'verbose' mode where more messages are posted.
I started reading the paltry documentation for the FileHandle module and it has left a lot to be desired (even when going behind it to the IO::File and ::Handle modules). Here is what I have come up with so far, but I feel that there is probably a way to simplify this further.
...during execution optional (verbose) messages are posted (sometimes within subroutines, hence the need for a global filehandle):use FileHandle; our $LOGFH; #can't figure out a way around using a global var here if ( $opt_s ) { $LOGFH = new_from_fd FileHandle fileno(STDOUT), 'a'; } else { $opt_l ||= $DEFAULT_LOG_FILE; $LOGFH = new FileHandle $opt_l, 'a'; } ( ! defined $LOGFH ) and croak 'Could not open logfile, aborting.'; autoflush $LOGFH 1; #autoflush on $LOGFH->print(scalar localtime, ": running MyProgram.\n") or carp 'Could not print to log.';
$opt_v and $LOGFH->print("$count records were processed.\n") or carp 'Could not print to log.';
...and then, after the program does it's thing:
if ( !$opt_s ) { $LOGFH->print(q{-} x 50, "\n") or carp 'Could not print to log.'; close $LOGFH or croak "Could not close the logfile: $!"; }
I have looked at some of the descriptions for the various logging modules on CPAN, and they all seem like overkill for the very basic logging I want to do. My knowledge of perl always grows when I consult the monks, so I am excited to hear any thoughts on the above code snippets and the problem in general, particularly if there is a logging module that is heavily recommended.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Best method for opening/using a log
by ikegami (Patriarch) on Jun 17, 2009 at 00:02 UTC | |
|
Re: Best method for opening/using a log
by targetsmart (Curate) on Jun 17, 2009 at 07:25 UTC |