有没有一种简单的方法来标记错误发送到stderr?为了解决问题,我需要知道何时发生错误.
例:
Dec 10 12:00:00 Can't call method "str" on an undefined value
Run Code Online (Sandbox Code Playgroud)
谢谢!
Mic*_*man 13
定义用于处理警告和致命错误的自定义处理程序:
use strict;
use warnings;
$SIG{__WARN__} = sub { warn sprintf("[%s] ", scalar localtime), @_ };
$SIG{__DIE__} = sub { die sprintf("[%s] ", scalar localtime), @_ };
warn;
die;
Run Code Online (Sandbox Code Playgroud)
输出:
[Fri Dec 11 14:35:37 2009] Warning: something's wrong at c:\temp\foo.pl line 7.
[Fri Dec 11 14:35:37 2009] Died at c:\temp\foo.pl line 8.
Run Code Online (Sandbox Code Playgroud)
您可能想要使用gmtime而不是localtime.
Sch*_*ern 12
__WARN__处理程序只捕获警告.他们没有抓住print STDERR.如果你想抓住一切,你必须绑定STDERR.
#!/usr/bin/perl -w
package Tie::Handle::Timestamp;
use strict;
use warnings;
use base 'Tie::Handle';
sub stamp {
return scalar localtime() .": ";
}
sub TIEHANDLE {
my $class = shift;
my $handle = shift;
# Dup the filehandle otherwise we'll be calling ourself
open my $fh, ">&", $handle or die $!;
return bless $fh, $class;
}
sub PRINT {
my $self = shift;
print { $self } $self->stamp, @_;
}
sub PRINTF {
my $self = shift;
my $format = shift;
printf { $self } $self->stamp . $format, @_;
}
sub CLOSE {
my $self = shift;
close $self;
}
package main;
# Tie it at compile time to catch compile time warnings
BEGIN {
tie *STDERR, "Tie::Handle::Timestamp", *STDERR or die;
}
print STDERR "Foo\n";
warn "Bar";
undef == 2;
Run Code Online (Sandbox Code Playgroud)
这有其自身的危险,因为您现在依赖于您的领带实施有多好.我很惊讶这里还没有CPAN模块,但我不知道我能推荐什么.
为__WARN__信号创建处理程序并在其中添加日期:
use Date::Format;
$SIG{'__WARN__'} = sub { warn time2str( '%C ', time ), $_[0] };
....
# rest of your script here.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1328 次 |
| 最近记录: |