Wednesday, October 4, 2006
4:21 AM

Easy Error Logging in Perl via Log4Perl

Need a quick and dirty tutorial on enabling loggers in your scripts? Here you go.
Download and Install Log-Log4perl-1.06 from CPAN (May prompt you to install IO-Tty-1.07).

The following perl script will let you give you the ability to define 3 filters for your logging: Error, Warn and Info. Warings and Errors are logged to one file and Info messages to the other.

use Log::Log4perl qw(get_logger);

# Define configuration
my $conf = q(
log4perl.logger = INFO, AppInfo, AppWarn, AppError

#filter to match INFO
log4perl.filter.MatchInfo = Log::Log4perl::Filter::LevelMatch
log4perl.filter.MatchInfo.LevelToMatch = INFO
log4perl.filter.MatchInfo.AcceptOnMatch = true

#filter to match Warn
log4perl.filter.MatchWarn = Log::Log4perl::Filter::LevelMatch
log4perl.filter.MatchWarn.LevelToMatch = WARN
log4perl.filter.MatchWarn.AcceptOnMatch = true

# filter to match Error
log4perl.filter.MatchError = Log::Log4perl::Filter::LevelMatch
log4perl.filter.MatchError.LevelToMatch = ERROR
log4perl.filter.MatchError.AcceptOnMatch = true

# Info Appender
log4perl.appender.AppInfo = Log::Log4perl::Appender::File
log4perl.appender.AppInfo.filename = detail.log
log4perl.appender.AppInfo.layout = PatternLayout
log4perl.appender.AppInfo.layout.ConversionPattern = %d %p> %F{1}:%L %M - %m%n
log4perl.appender.AppInfo.Filter = MatchInfo

# Warn Appender
log4perl.appender.AppWarn = Log::Log4perl::Appender::File
log4perl.appender.AppWarn.filename = result.log
log4perl.appender.AppWarn.layout = PatternLayout
log4perl.appender.AppWarn.Filter = MatchWarn

# Error Appender
log4perl.appender.AppError = Log::Log4perl::Appender::File
log4perl.appender.AppError.filename = detail.log
log4perl.appender.AppError.layout = PatternLayout
log4perl.appender.AppError.layout.ConversionPattern = %d %p> %F{1}:%L %M - %m%n
log4perl.appender.AppError.Filter = MatchError
);

# Initialize logging behaviour
Log::Log4perl->init( \$conf );

my $logger = get_logger("issa::test");
$logger->info("License file installed successfully");

0 comments:

Post a Comment