In a perl script, I am capturing all the STDOUT and STDERR using the below code:

open STDOUT, '>>', "$log_file" or die "Can't redirect STDOUT: $!";
open STDERR, ">&STDOUT"  or die "Can't add to  STDOUT: $!";

Here I am logging all those are generated from main() but how can I add a timestamp infront of each line of STDOUT ?


I'm assuming that the reason you want to do this is so that you don't have to include "print scalar localtime" for each print statement. If so, I'd recommend doing this in a simpler fashion.

Instead of using print on each print statement, make separate functions for logging error messages, informational messages and printing output. Like this:

sub logmsg {
  print (scalar localtime() . " @_\n");

sub logerr {
  print STDERR (scalar localtime() . "ERROR: @_\n");

sub debug {
  if ($debug) {
    print "DEBUG: @_\n";

Then, within the script I will always use logmsg or logerr as appropriate. This makes it easy to change where the log messages go by altering those few functions. In your case, you could also change the log functions to write directly to the file instead of to STDOUT/STDERR. (In my own case, I will often use syslog instead, so I will remove the timestamp code and instead use e.g. Sys::Syslog with appropriate facility and log level.)

  • Yes I have actually more than hundreds of prints from the main() in to the log file. So I dont want to use print date infront of each. – kumarprd Mar 21 '14 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.