【问题标题】:how to dump output of a perl script on linux into a log file with file name as timestamp如何将 linux 上的 perl 脚本的输出转储到文件名作为时间戳的日志文件中
【发布时间】:2013-04-25 15:16:52
【问题描述】:

我有一个在 linux 机器上运行的 perl 脚本 example.pl。我需要捕获执行 perl 脚本的输出并为其名称加上时间戳。我知道输出重定向方法,但我正在从脚本 example.pl 本身寻找一种方法(如果可能)

【问题讨论】:

    标签: linux perl logging


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以使用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
      

      【讨论】:

        【解决方案3】:

        这是最快的方法:

         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;
        

        【讨论】:

        • select如果有人直接使用STDOUT会失败,不会被子进程继承,但是很容易恢复。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-11
        • 1970-01-01
        • 2017-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多