使用附加程序。
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;
我的程序:
#! /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);
输出:
$ ./myprog
WARN - 警告
信息 - 信息
错误 - 不正确
致命 - 真的很糟糕,伙计
3
$回声$?
1
注释掉...->warn
, ...->error
, 和...->fatal
行以获得
$ ./myprog
信息 - 信息
0
$回声$?
0