In some code I am writing, I have a logging subroutine which directs messages with a time stamp and process ID to a file. If a file name is not passed to the subroutine, the message is to be directed instead to
STDERR. While I got this code working as desired through a bit of reading through
redirecting STDERR, then back again and
perlfunc:open, I am wondering if there is a cleaner way to implement this solution? The current version of my subroutine code follows:
sub write_logfile ($$) {
use Time::HiRes 'time';
my ($file, $message) = @_;
chomp($message);
if (defined($file)) {
open OLDERR, ">&STDERR";
open STDERR, ">>$file";
flock STDERR, 8;
print OLDERR "";
};
print STDERR time, " [", $$, "] ", $message, "\n";
if (defined($file)) {
close STDERR;
open STDERR, ">&OLDERR";
};
};
The duplication and restoration of STDERR however seems messy and I'm wondering if TAMBWTDI (there's a much better way to do it).
Note: The print OLDERR ""; line is there to prevent the 'Name "main::OLDERR" used only once: possible typo at blah.perl line 162.' error otherwise generated under -w as per melguin's node here.
Ooohhh, Rob no beer function well without!
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.