Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGI: Redirecting STDERR to file with an alteration

Tags:

perl

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?

like image 925
Ωmega Avatar asked Nov 24 '25 13:11

Ωmega


1 Answers

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";
like image 182
mob Avatar answered Nov 27 '25 04:11

mob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!