我一直在许多脚本中广泛使用Log4perl.我想扩充这些脚本以设置错误代码(如果已记录任何消息WARN或ERROR消息).基于现有文档,我找不到任何明显的方法来做到这一点.
我想避免对现有脚本进行暴力重写,以便对每条WARN或ERROR日志消息进行检查; 如果可能的话,我更喜欢在脚本退出之前处理它,就像这个伪代码一样:
if $log->has_warnings_or_errors then
exit 1
else
exit 0
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法来调用Log4Perl来确定当前的记录器是否存在某些级别的消息?
使用appender.
MyCounter.pm:
package MyCounter;
use warnings;
use strict;
use Log::Log4perl::Level;
sub new {
my($class,%arg) = @_;
bless {} => $class;
}
sub log {
my($self,%arg) = @_;
++$self->{ $arg{log4p_level} };
}
sub howmany {
my($self,@which) = @_;
my $total = 0;
$total += ($self->{$_} || 0) for @which;
$total;
}
1;
Run Code Online (Sandbox Code Playgroud)
MYPROG:
#! /usr/bin/perl
use warnings;
use strict;
use Log::Log4perl;
my $conf = q(
log4perl.category.MyLogger = INFO, Screen
log4perl.appender.Screen = Log::Log4perl::Appender::Screen
log4perl.appender.Screen.layout = Log::Log4perl::Layout::SimpleLayout
);
Log::Log4perl->init(\$conf);
my $l = Log::Log4perl->get_logger("MyLogger");
my $counter = Log::Log4perl::Appender->new("MyCounter");
$l->add_appender($counter);
$l->warn("warning");
$l->info("info");
$l->error("incorrect");
$l->fatal("really bad, man");
print $counter->howmany(qw/ WARN ERROR FATAL /), "\n";
exit ($counter->howmany(qw/ WARN ERROR FATAL /) ? 1 : 0);
Run Code Online (Sandbox Code Playgroud)
输出:
$ ./myprog WARN - warning INFO - info ERROR - incorrect FATAL - really bad, man 3 $ echo $? 1
注释掉...->warn,...->error和...->fatal线得到
$ ./myprog INFO - info 0 $ echo $? 0