Forum Moderators: coopster & phranque

Message Too Old, No Replies

Creating an error log for failed require or defined()

         

csdude55

2:15 am on Feb 21, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have several Perl scripts that use something like this:

eval { require 'libs/filter.lib' };

if (eval "defined(&filters)") {
($result1, $result2) = filters($example1, $example2, ...);
}


In this example, sub filters($example1, $example2, ...) { } is a subroutine inside of libs/filter.lib. I honestly don't remember why I use eval... maybe to suppress error messages if there's a problem? It's been awhile since I wrote it, so I honestly don't remember.

Every so often, I have to make a manual modification to filter.lib. What I want to do is, if there's a fatal error in that file, I want to write the error code in a text file within the same directory. It currently writes to the error_log, which is fine, but it's a larger file in a separate directory and it would be a lot easier if I could just write it to its own unique file.

Any suggestions?

phranque

4:30 am on Feb 21, 2017 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



i believe the first eval is in a form to capture any fatal errors from the require function and the second one is to determine the existence of the filters sub after the require is executed.

this may be a useful reference for the error logging question.
How can I capture STDERR from an external command?:
http://perldoc.perl.org/perlfaq8.html#How-can-I-capture-STDERR-from-an-external-command%3F

csdude55

7:11 am on Feb 22, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Thanks for the link, phranque! I'll be honest, though, man, that page is only slightly clearer than mud for me. Perl used to be my go-to but I haven't really done much in it since 2013, so I couldn't follow any of that.

I've been digging on this all day, and the only thing I've come up with (untested) is:


use CGI::Carp qw(carpout);

open(LOG, ">>error_log.txt") or die("Unable to open error_log.txt: $!\n");
carpout(LOG);


I've used CGI::Carp qw(fatalsToBrowser); for development, anyway, so if this just prints the error to a text file instead of to the screen, then that's just dandy.

Thoughts?

csdude55

9:20 am on Feb 22, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Or, maybe this?

use CGI::Carp qw(set_die_handler);

# I don't know the purpose of BEGIN, but it's in the example
BEGIN {
sub handle_errors {
my $msg = shift;

print "Content-type: text/html\n\n";
print "<h1>Oh gosh</h1>";
print "<p>Got an error: $msg</p>";

if (open LOG, ">>error_log.txt" or die("Unable to open error_log.txt: $!\n")) {
print LOG "$msg\n";
close LOG;
}
}

set_die_handler(\&handle_errors);
}