How can I enter two different files in Log4perl?

I have a Perl script that creates two different data streams.

I need to write them to two separate log files.

I am aware of two approaches that lead to different log files, but none of them seem useful to me in my situation:

  • Using categories (which are Perl module names).

    In my case, the threads are created in the same code (the "main" package, but it does not matter, the important thing is that literally I have lines of code next to each other, registered in 2 locations that cannot be divided into different Perl modules).

  • Using different loglevels.

    However, both must be logged with the same priority (for example, both record info()calls and error()as necessary), so I can not use the FAQ recipe to write WARN / ERROR to different files .

+4
source share
1 answer

Categories in Log4perl are arbitrary and not related to the class hierarchy of your application.

use strict;
use warnings;

use Log::Log4perl qw(get_logger);

my $conf = q(
log4perl.category.first  = DEBUG, FileAppender1
log4perl.category.second = DEBUG, FileAppender2

log4perl.appender.FileAppender1          = Log::Log4perl::Appender::File
log4perl.appender.FileAppender1.filename = first.log
log4perl.appender.FileAppender1.layout   = Log::Log4perl::Layout::SimpleLayout

log4perl.appender.FileAppender2          = Log::Log4perl::Appender::File
log4perl.appender.FileAppender2.filename = second.log
log4perl.appender.FileAppender2.layout   = Log::Log4perl::Layout::SimpleLayout
);

Log::Log4perl::init(\$conf);

my $logger1 = get_logger('first');
my $logger2 = get_logger('second');

$logger1->debug('foo');
$logger2->info('bar');
$logger1->error('baz');

first.log

DEBUG - foo
ERROR - baz

second.log

INFO - bar
+2
source

Source: https://habr.com/ru/post/1676088/


All Articles