In my script, I am logging errors (warnings and dies) to a log file. I want every message in the log to be preceded by a timestamp. So this is what I have come up with:
open (STDERR, '>>', $log_file) or die "Can't write to $log_file: $!";
die log_error ("This error will have a timestamp.");
sub log_error {
return "@{[scalar(localtime(time))]}: $_[0]";
}
The problem with this approach is that if my script unexpectingly dies or there is warning that I didn't anticipate (for example, the use of an unintialized variable or a bare word), the error message will appear in the log file, but without a timestamp. How can I make everything written to the log automatically have a timestamp?