How can I redirect output of die function to a file in Perl?

霸气de小男生 提交于 2019-12-04 04:02:13
wkl

Perl's die prints to STDERR so you could redirect STDERR to a file.

#!/usr/bin/env perl
# the path above depends on your system

open(STDERR, ">>", "errlog.log");
die "Hello";

You can install a $SIG{__DIE__} handler to be run just before the "die" runs. The handler will be called with the error message which you can log:

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

See $SIG{expr} in perlvar for details.

The Log::Log4perl module offers more than a few options.

One can choose to output the error message to both STDERR and the logfile.

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;

While it requires a little bit more effort in terms of setup, its flexibility unlocks a great deal of potential.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!