Dcoder
Dcoder

Reputation: 379

how to dump output of a perl script on linux into a log file with file name as timestamp

I have a perl script example.pl that I run on linux box. I need to capture the output from the execution of the perl script and timestamp its name. I know the output redirection method but I am looking for a way to do it from the script example.pl itself (if possible)

Upvotes: 1

Views: 6371

Answers (3)

arunxls
arunxls

Reputation: 124

You can redirect output and error streams using Typeglobs or you can do the following.

#!/bin/perl 

open(STDOUT, '>',time.".out") or die $!; #the time function gives you the timestamp
open(STDERR, '>',time.".err") or die $!;
print "output"; #goes to <timestamp>.out
warn "error";   #goes to <timestamp>.err

Upvotes: 1

Miguel Prz
Miguel Prz

Reputation: 13792

It's easy to redirect the STDOUT to a file. Just do this at the beginning of the script:

open STDOUT, '>', "my_stdout_file.txt";

And this is a function that returns a file name with a timestamp:

sub generate_timestamp_filename {
    my $tstamp = sprintf( "%04d%02d%02d%02d%02d%02d", 
                                $now[5]+1900, 
                                $now[4]+1, 
                                $now[3],
                                $now[2],      
                                $now[1],   
                                $now[0] );

    return "my_prefix_$tstamp.txt";
}

Upvotes: 2

KateYoak
KateYoak

Reputation: 1731

Here is the quickest way to do this:

 open(STDOUT, ">myfile") or die $!;
 print "Hello world"; #now goes to myfile

 open(STDERR, ">hisfile") or die $!;
 warn "Error here"; #and that's in hisfile

The other alternative is to use select:

open(my $FILE, ">stdout") or die $!;
my $old = select($FILE);

# Done capturing output
select $old;

Upvotes: 0

Related Questions