2

I have the following log4perl.conf configuration file that I'm using for multiple scripts. It is configured to show messages from all log levels.

# Log4perl configuration file

log4perl.rootLogger = ALL, screen, file

log4perl.appender.screen = Log::Log4perl::Appender::Screen
log4perl.appender.screen.stderr = 0
log4perl.appender.screen.layout = PatternLayout
log4perl.appender.screen.layout.ConversionPattern = %d %p> %m%n

log4perl.appender.file = Log::Log4perl::Appender::File
log4perl.appender.file.filename = sub { my $script=$0; $script =~ s/(dev|test|prod)\/script/log/; $script =~ s/\.[^.]+$//; return "$script.log" }
log4perl.appender.file.mode = append
log4perl.appender.file.layout = PatternLayout
log4perl.appender.file.layout.ConversionPattern = %d %p> %m%n

The scripts use this code snippet to initialize it:

use Log::Log4perl;
# Logger configuration
Log::Log4perl->init('/etc/log4perl.conf');
$logger = Log::Log4perl->get_logger();

What is the best way to adjust the logging level without having to modify the configuration file each time since there are multiple scripts using the same config.

Can I create a new logger and have the script use that one instead of the root logger?

A_B
  • 1,009
  • 3
  • 15
  • 37
  • Are you saying you want to temporarily change the logging level (like in a small section of a single script) without making changes to the config? Or do you want a separate logger for each script? – ThisSuitIsBlackNot Jan 25 '17 at 14:44
  • I'd like to be able to temporarily change the logging level for a single script without affecting the other scripts. Not sure the best way to accomplish that. – A_B Jan 25 '17 at 14:50

1 Answers1

0

You can use the level method to adjust the logging level inside your program:

use strict;
use warnings 'all';

use Log::Log4perl;
use Log::Log4perl::Level;

Log::Log4perl->init(\*DATA);

my $logger = Log::Log4perl->get_logger;

$logger->info('before');
$logger->level($INFO);
$logger->info('after');

__DATA__
log4perl.rootLogger             = WARN, Screen
log4perl.appender.Screen        = Log::Log4perl::Appender::Screen
log4perl.appender.Screen.layout = Log::Log4perl::Layout::PatternLayout
log4perl.appender.Screen.layout.ConversionPattern = %d %p> %m%n

Output:

2017/01/25 12:59:58 INFO> after

This will not affect other scripts that use the same config file, since they will each have their own Log::Log4perl instance.

Alternatively, you can use the more_logging/inc_level or less_logging/dec_level methods, which take a delta value instead of an absolute logging level.

ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110