Logging Perl Errors

You can use our Webhook API to log errors and alerts to ErrLog. This gives you complete customization over the data you send to us. All it involves is crafting a simple JSON package and making a simple web request.
 

Requirements

The only external requirement is LWP::UserAgent.

use LWP::UserAgent;

If this isn't already installed on your system you can install it with one of the following commands.

# Ubuntu
$> sudo apt install libwww-perl
                
# CentOS/Red Hat/Fedora
$> sudo yum install perl-libwww-perl                

# Other Distributions
$> sudo perl -MCPAN -e 'install Bundle::LWP'
 

Crafting the message

Start by creating a request and setting the headertype to "application/json". Note, when you create the request you're specifying the url of our relay host's logging API. For more information on the API, including all the required and optional fields you can use, see Webhooks API.


my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(POST => "https://relay.errlog.io/api/v1/log");
$req->header('content-type' => 'application/json');

From there you can create the json string that will be sent to the api.

my $post_data = "
{\"apikey\": \"[Your-api-key]\",
    \"message\": \"null\",
    \"errordate\": \"2018-05-22 23:27:40\",
    \"applicationname\": \"Perl Sample\",
    \"trace\": \"java.lang.NullPointerException\",
    \"method\": \"main\",
    \"lineno\":  19
}";
                
$req->content($post_data);
 

Send it

That's all the hard work done. Now you just need to send us the data.

my $resp = $ua->request($req);

You can do any error checking on the response. In normal circumstances the API will respond with "OK".

if ($resp->is_success) {
    my $message = $resp->decoded_content;
    print "Received reply: $message\n";
} else {
    print "HTTP code: ", $resp->code, "\n";
    print "HTTP message: ", $resp->message, "\n";
}
 

Complete Code

Below is a complete code listing used in the examples above.

use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
            
my $req = HTTP::Request->new(POST => "https://relay.errlog.io/api/v1/log");
$req->header('content-type' => 'application/json');
            
my $post_data = "
{\"apikey\": \"[Your-api-key]\",
    \"message\": \"null\",
    \"errordate\": \"2018-05-22 23:27:40\",
    \"applicationname\": \"Perl Sample\",
    \"trace\": \"java.lang.NullPointerException\",
    \"method\": \"main\",
    \"lineno\":  19
}";

$req->content($post_data);
            
my $resp = $ua->request($req);
if ($resp->is_success) {
    my $message = $resp->decoded_content;
    print "Received reply: $message\n";
} else {
    print "HTTP code: ", $resp->code, "\n";
    print "HTTP message: ", $resp->message, "\n";
}

 

Discuss this article