代码之家  ›  专栏  ›  技术社区  ›  Aakash Goel

如何将die函数的输出重定向到perl中的文件?

  •  7
  • Aakash Goel  · 技术社区  · 15 年前

    我想重定向 die 将消息发送到一个单独的文件,以便以后可以比较该文件以确定出了什么问题。

    但这段代码给了我错误:

    $ cat test.pl
    use strict;
    use warnings;
    
    my $log = "msglog.log";
    die $log "DEAD$!";
    
    $ perl test.pl
    Missing comma after first argument to die function at test.pl line 5, near ""DEAD$!";"
    Execution of test.pl aborted due to compilation errors.
    $ 
    

    我不想做 2> 从呼叫者那里。有什么方法可以从脚本中重定向它们吗?

    3 回复  |  直到 15 年前
        1
  •  10
  •   rafl    15 年前

    珀尔 die 打印到 STDERR 所以你可以重新定向 斯代尔 一个文件。

    #!/usr/bin/env perl
    # the path above depends on your system
    
    open(STDERR, ">>", "errlog.log");
    die "Hello";
    
        2
  •  15
  •   Eugene Yarmash    15 年前

    您可以安装 $SIG{__DIE__} 要在“die”运行之前运行的处理程序。将使用您可以记录的错误消息调用处理程序:

    local $SIG{__DIE__} = sub {
        my ($message) = @_;
        # log the message        
    };
    

    $SIG{expr} 在Perlvar中查看详细信息。

        3
  •  9
  •   Zaid    15 年前

    这个 Log::Log4perl 模块提供多个选项。

    可以选择将错误消息同时输出到stderr和日志文件。

    my $logger = Log::Log4perl->init ( 'log.conf' );
    # Configuration file controls what to output, like time, line number, class...
    
    $logger->get_logger ( 'Hello::World' );  # Define which class logger to use
    
    .
    .
    .
    
    open my $fh, '<', $file
      or $logger->logdie ( "Log the demise: $!" );  # ... and die;
    

    虽然它在设置方面需要更多的努力,但它的灵活性释放了很大的潜力。