Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log to two different files in Log4perl?

Tags:

I have a Perl script that produces two different streams of data.

I need to log them to two separate log files.

I'm aware of 2 approaches that result in different log files but neither one seems helpful in my situation:

  1. Using categories (which are Perl module names).

    In my case, the streams are both produced in the same code ("main" package, but that's irrelevant, what matters is that literally I have lines of code next to each other logging to 2 locations that can't be separated into different Perl modules).

  2. Using different loglevels.

    However, both should log with the same priority (e.g. both are logging info() calls and error() as appropriate) so I can't use the FAQ recipe for logging WARN/ERROR to different files.

like image 994
DVK Avatar asked May 01 '17 21:05

DVK


1 Answers

Categories in Log4perl are arbitrary and aren't 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
like image 165
Matt Jacob Avatar answered Sep 23 '22 11:09

Matt Jacob