Reputation: 43673
Redirecting STDERR
to an external file is pretty easy
my $stderr = '/home/logs/stderr.log.txt';
open STDERR, '>' . $stderr;
...
$_ = 1/0; # Error: Illegal division by zero
To make this error log file more readable I want to prepend a timestamp information each time sometimes is sent to STDERR
.
How can be that accomplished?
Upvotes: 3
Views: 79
Reputation: 118615
Easiest way without too many disruptions to the rest of your code is to use tied filehandles. Tied filehandles allow you to write customized functions that are invoked when your filehandle is read from, written to, or has any other operation performed on it.
Proof-of-concept
package TimeStamper;
sub TIEHANDLE {
my ($pkg,$file) = @_;
open my $fh, ">", $file; # the "real" filehandle
return bless [$fh],$pkg;
}
sub PRINT {
my ($self,@msg) = @_;
print {$self->[0]} "[",scalar localtime,"] ",@msg;
}
package main;
my $stderr = "/home/logs/stderr.log.txt";
tie *STDERR, "TimeStamper", $stderr;
print STDERR "Hello world\n";
Upvotes: 3