我通常使用以下样板通过Log::Log4perl 登录脚本。您可以从命令行覆盖日志库/日志配置位置(或者,更常见的是,在部署时将适当的位置设置为默认位置),并在为脚本提供一个或多个 -verbose 标志后,覆盖该日志记录并登录到屏幕,使用4 个详细信息为您提供屏幕输出。这使您可以轻松地从调试过渡到通过提供详细标志来获取每个日志输出,将其传递给自定义日志处理程序配置以调试子系统,再到在生产部署中设置日志记录,所有这些都只需很少/没有代码更改。
use Getopt::Long;
use Pod::Usage;
use Log::Log4perl qw/:easy/;
my $opts = { logconf => undef,
logbase => 'corp.team.app.appname'
debug => 0,
};
GetOptions ( 'logconf|l=s' => \$opts->{logconf},
'logbase=s' => \$opts->{logbase},
'verbose|v+' => \$opts->{debug}, ### debug levels - 0 = off (default), 1 = error, 2 = warn, 3 = info, 4 = debug.
### Ignored if a logconf is provided.
) or pod2usage(0);
### Initialize logging subsystem
init_logger();
### Usage
logger('app_subsystem')->info('some message...');
logger()->debug('debug message...');
### Initialize logging system
sub init_logger {
### If a log configuration is found, and debug was not set, use it
if ( $opts->{logconf}
and -e $opts->{logconf}
and ! $opts->{debug}
) {
Log::Log4perl->init($opts->{logconf});
}
### Otherwise fall through to easy_init a screen logger based on the verboseness level
### Logging off if no config found and no verboseness set
else {
my ($min, $max) = ( 0, 4 );
my %levels;
@levels{$min .. $max} = ( $OFF, $ERROR, $WARN, $INFO, $DEBUG );
my $log_level = $opts->{debug};
if ($log_level < $min) {
$log_level = $min;
}
elsif ($log_level > $max) {
$log_level = $max;
}
Log::Log4perl->easy_init($levels{$log_level});
}
}
### Shorthand shim sub to get a logger
### Always returns a Log::Log4perl logger object
sub logger {
my ($category) = @_;
if ($category) {
return Log::Log4perl->get_logger($opts->{logbase} . '.' . $category);
}
return Log::Log4perl->get_logger($opts->{logbase});
}