Logging Java 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.

As Java has a native Exception object and error-handling capabilities, you can use try/catch statements to handle errors in a simple way and log the data with ErrLog. You could even create your own Exception class to handle all exceptions in your project.

 

Package Imports

You'll need to import a few namespaces.

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.net.ssl.HttpsURLConnection;
 

Java Usage

First you have to have something go wrong. In the below example we're forcing a NullReferenceException in a try/catch block where the ErrLog functionality will be in the catch part.

Normally you don't want to cause an exception but in this case this is how we do it.

try {
    String str = null;

    System.out.println(str.toUpperCase());
} catch (Exception ex) {
    ...
}
 

Crafting the package

You can put all the variables in-line, however for readabilities-sake we're defining them at the beginning.

Date now = new Date();
String message = ex.getMessage();
String stackTrace = ex.toString();
StackTraceElement ste = ex.getStackTrace()[0];
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(now);
String apikey = "[Your-api-key]";

Now that has been done, we can create the JSON message that will be sent to ErrLog. You can see only a few of the potential properties have been used below. For a full list of available fields see our Webhook API documentation.

 String postString =  
"{" + 
    "\"apikey\": \"" + apikey + "\",\n" +
    "\"message\": \"" + message + "\",\n" +
    "\"errordate\": \"" + formattedDate + "\",\n" +
    "\"applicationname\": \"Java Sample\",\n" + 
    "\"trace\": \"" + stackTrace + "\",\n"                        +
    "\"method\": \"" + ste.getMethodName() + "\",\n" + 
    "\"lineno\":  "+ ste.getLineNumber() + "\n" + 
"}";
 

Send the message

Prepare the message to be POSTed to ErrLog

byte[] postData = postString.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;

Create a connection to the ErrLog relay host.

URL url = new URL("https://relay.errlog.io/api/v1/log");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

Send the data to ErrLog

conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));

DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.write(postData);

You need to specify that you're expecting a response.

int responseCode = conn.getResponseCode();

If you want to, you can get the response message from ErrLog. In most cases this will be "OK"

String responseMessage = conn.getResponseMessage();
 

Complete Code

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


import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.net.ssl.HttpsURLConnection;

public class ErrLogSample {
    public static void main(String[] args) throws Exception {
        System.out.println("About to create an exception that will be sent to ErrLog.IO..");

        try {
            String str = null;

            System.out.println(str.toUpperCase());
        } catch (Exception ex) {
            // Set up some variables
            Date now = new Date();
            String message = ex.getMessage();
            String stackTrace = ex.toString();
            StackTraceElement ste = ex.getStackTrace()[0];
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = df.format(now);
            String apikey = "[Your-api-key]";

            String postString =  
            "{" + 
                "\"apikey\": \"" + apikey + "\",\n" +
                "\"message\": \"" + message + "\",\n" +
                "\"errordate\": \"" + formattedDate + "\",\n" +
                "\"applicationname\": \"Java Sample\",\n" + 
                "\"trace\": \"" + stackTrace + "\",\n"                        +
                "\"method\": \"" + ste.getMethodName() + "\",\n" + 
                "\"lineno\":  "+ ste.getLineNumber() + "\n" + 
            "}";

            // Displays the string to console so you can see what's being sent.
            System.out.println(postString);
         
            byte[] postData = postString.getBytes(StandardCharsets.UTF_8);
            int postDataLength = postData.length;

            URL url = new URL("https://relay.errlog.io/api/v1/log");
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("User-Agent", "Java Test Application");
            conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));

            DataOutputStream os = new DataOutputStream(conn.getOutputStream());
            os.write(postData);

            int responseCode = conn.getResponseCode();
            String responseMessage = conn.getResponseMessage();

            System.out.println("");
            System.out.println("ResponseCode: " + responseCode);
            System.out.println("Message: " + responseMessage);

            os.flush();
            os.close();
        }
    }
}

 

Discuss this article