簡體   English   中英

如何將Linux上的Perl腳本的輸出轉儲到日志文件中,文件名為時間戳

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

我有一個在Linux機器上運行的perl腳本example.pl。 我需要從perl腳本的執行中捕獲輸出並為其名稱加上時間戳。 我知道輸出重定向方法,但我正在尋找一種方法來從腳本example.pl本身進行操作(如果可能)

將STDOUT重定向到文件很容易。 只需在腳本開頭執行此操作:

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

這是一個返回帶有時間戳的文件名的函數:

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";
}

這是最快的方法:

 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

另一種選擇是使用select

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

# Done capturing output
select $old;

您可以使用Typeglobs 重定向輸出和錯誤流,也可以執行以下操作。

#!/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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM