如何使用Log4perl登录不同的文件

时间:2017-11-08 09:32:18

标签: perl logging perl-module cpan log4perl

在perl中,有没有办法在不同的路径中记录两个不同的文件?

例如,我必须在文件中记录详细的服务器查询和响应,并在其他文件中记录脚本流(第二个文件将只包含抽象信息)。我如何在Log4Perl中实现这一目标。

sub getLogger
{
    my ( $paramA, $paramB, $type ) = @_;
        my $conf = ("
            log4perl.rootLogger =INFO, LOGFILE
            log4perl.rootLogger1 =ALL, REPFILE

            log4perl.appender.LOGFILE=Log::Log4perl::Appender::File
            log4perl.appender.LOGFILE.filename = sub { getLogFileName(\"$paramA\", \"$paramB\", \"$type\"); };
            log4perl.appender.LOGFILE.mode=append
            log4perl.appender.LOGFILE.autoflush = 1
            log4perl.appender.LOGFILE.size      = 1M
            log4perl.appender.LOGFILE.layout=PatternLayout
            log4perl.appender.LOGFILE.layout.ConversionPattern=[%c] %d %H - %m%n

            log4perl.appender.REPFILE=Log::Log4perl::Appender::File
            log4perl.appender.REPFILE.filename = sub { getLogFileName(\"$paramA\", \"$paramB\", \"$type\"); };
            log4perl.appender.REPFILE.mode=append
            log4perl.appender.REPFILE.autoflush = 1
            log4perl.appender.REPFILE.size      = 1M
            log4perl.appender.REPFILE.layout=PatternLayout
            log4perl.appender.REPFILE.layout.ConversionPattern=[%c] %d %H - %m%n
        ");
        Log::Log4perl::init(\$conf);
        my $logger1 = Log::Log4perl->get_logger('rootLogger');
        my $logger2 = Log::Log4perl->get_logger('rootLogger1');
        if($type == 1)
        {
            return $logger1;
        }
        else
        {
            return $logger2;
        }
}

当我尝试在脚本的不同位置获取logger1和logger2时,最后获取的实例将复制到两个记录器。例如,

my $logger1 = getLogger($paramA, $paramB, $type);
$logger1->info("This is log 1"); #printed in file 1 correctly
my $logger2 = getLogger($paramA, $paramB, $type);
$logger2->info("This is log 2"); #printed in file 2 correctly
$logger1->info("Again trying to print in file1"); #printed in file2 - expected to print in file1.
$logger2->info("Again trying to print in file2"); #printed in file2 - expected to print in file2.

我被困在这里。出了什么问题?!

0 个答案:

没有答案