Log4perl is a great tool for logging.
The warnings pragma is also an essential tool.
However, when Perl scripts are running as daemons, the Perl warnings, are printed into STDERR where nobody can see them, and not into the Log4perl log file of the relevant program.
Is there a way to catch Perl warnings into the Log4perl log?
For example, this code will log just fine to the log file, but in case this is run as a daemon, the Perl warnings will be not be included in the log:
#!/usr/bin/env perl
use strict;
use warnings;
use Log::Log4perl qw(get_logger);
# Define configuration
my $conf = q(
log4perl.logger = DEBUG, FileApp
log4perl.appender.FileApp = Log::Log4perl::Appender::File
log4perl.appender.FileApp.filename = test.log
log4perl.appender.FileApp.layout = PatternLayout
);
# Initialize logging behaviour
Log::Log4perl->init( \$conf );
# Obtain a logger instance
my $logger = get_logger("Foo::Bar");
$logger->error("Oh my, an error!");
$SIG{__WARN__} = sub {
#local $Log::Log4perl::caller_depth = $Log::Log4perl::caller_depth + 1;
$logger->warn("WARN @_");
};
my $foo = 100;
my $foo = 44;
This still prints out to STDERR:
"my" variable $foo masks earlier declaration in same scope at log.pl line 27.
And the log file does not catch this warning.
Log::Log4perl lets you remote-control and fine-tune the logging behaviour of your system from the outside. It implements the widely popular (Java-based) Log4j logging package in pure Perl.
In the most simple case we use it to add logging messages to a script. We need to load the module importing the :easy key that will import 6 functions for the 6 logging levels provided by Log::Log4perl and 6 variables with corresponding names. In the code we can use any of the 6 methods to send logging messages.
You could install a WARN
handler to do this. It's mentioned in the Log4perl FAQ.
My program already uses warn() and die(). How can I switch to Log4perl?
If your program already uses Perl's warn() function to spew out error messages and you'd like to channel those into the Log4perl world, just define a WARN handler where your program or module resides:
use Log::Log4perl qw(:easy);
$SIG{__WARN__} = sub {
local $Log::Log4perl::caller_depth =
$Log::Log4perl::caller_depth + 1;
WARN @_;
};
This will capture any explicit use of warn
in your program, as well as Perlish warnings about use of uninitialized values and the like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With