与 Moose 一起使用时,是否可以让 Log4perl 正确显示日志事件的行号和包/类,而不是始终在第 99 行显示 Method::Delegation?
就我而言,我创建了一个属性 isa Log::Log4perl::Logger 并将各种日志记录级别委托给我的类(日志、警告、错误……)。执行此操作还会将 Delegation.pm 显示为文件。
您没有提供足够的信息来诊断您的问题(例如,什么是 Method::Delegation 以及它如何连接到 Log4perl),但我的敏锐感觉告诉我您可能有一个包装方法,您可以从中调用 Log4perl 方法。您应该在此包装器中增加
$Log::Log4perl::caller_depth
的值(并在调用 Log4perl 后减少它),以便确定正确的位置。
例如在 Moose 中,我使用:
package MyApp::Role::Log;
use MooseX::Role::Strict;
use Log::Log4perl;
my @methods = qw(
log trace debug info warn error fatal
is_trace is_debug is_info is_warn is_error is_fatal
logexit logwarn error_warn logdie error_die
logcarp logcluck logcroak logconfess
);
has '_logger' => (
is => 'ro',
isa => 'Log::Log4perl::Logger',
lazy_build => 1,
handles => \@methods,
);
around $_ => sub {
my $orig = shift;
my $this = shift;
# one level for this method itself
# two levels for Class::MOP::Method::Wrapped (the "around" wrapper)
# one level for Moose::Meta::Method::Delegation (the "handles" wrapper)
local $Log::Log4perl::caller_depth += 4;
my $return = $this->$orig(@_);
$Log::Log4perl::caller_depth -= 4;
return $return;
} foreach @methods;
sub _build__logger
{
my $this = shift;
Log::Log4perl->easy_init() if not Log::Log4perl::initialized();
return Log::Log4perl->get_logger(ref $this)
}
no MooseX::Role::Strict;
1;
请注意,CPAN 模块 MooseX::Log::Log4perl 不会增加 caller_depth,而它绝对应该增加。
是的。根据 Log::Log4perl::Layout::PatternLayout 你想要的是
%F
和 %L
的组合。 %L
是“发出日志语句的文件中的行号”,%F
是“发生日志记录事件的文件”。
或者,最简单的方法是使用
%l
,即:
调用者的完全限定名称 方法后跟调用者源 文件名和行号之间 括号。