Well, I would not think that putting the string 'This is a bad thing you did!' that is output by $logger->error() into the 'error' field of the thrown exception would be equivalent to having the logging statement actually throw the exception itself. I still think there is a way to write a Log4perl appender to accomplish what I want, so that my exception classes don't have to use Log4perl themselves.
However, thanks to your suggestion I did come up with something easy. I overrode the full_message() exception object method to use Log4perl to output the 'error' field/message of the object. The message will get output again to stdout by the exception object but without all the fancy Log4perl formatting, but that is OK by me at this point.
The other down side is that if I want my exception messages to have different logging levels (FATAL, ERR, WARN), then the exceptions must hand that off to Log4perl, also.
#!/usr/bin/perl -w
use strict;
use warnings;
package ThisException; {
use Log::Log4perl;
our $logger = Log::Log4perl->get_logger('test1');
use Exception::Class (
'ThisException' => {
description => 'Parent class.',
},
);
sub full_message {
my $self = shift;
$logger->fatal($self->message);
return $self->message;
}
}
use Log::Log4perl;
Log::Log4perl::init_and_watch('/etc/log4perl.conf', 'HUP');
our $logger = Log::Log4perl->get_logger('test1');
$logger->info('This is my INFO message!');
ThisException->throw(
error => "This will be a Log4perl FATAL message.",
);
exit 0;
|