Log4JavaScript server-side receiving

2.8k Views Asked by At

I'm trying to use Log4Javascript to send client-side errors to the server where results can then be written to file. I'm using the AjaxAppender to try to send the data to the server. I started with a simple "Hello world" to see if I can figure out how to receive error messages because the documentation literally says "no server-side code is provided".

Basically, I'm relatively new to this. A good Java programmer, HTML, CSS, Javascript, etc. But I've recently dived into the world of JSP and I was trying to use that to receive the error messages and (for now) print them to the debug console.

I have minimal code in my index.jsp file. Just an h1 tag that says "Hello World" and links to my javascript and jquery.

My Javascript is as follows:

var url = "logger.jsp";
$(function(){
    var log = log4javascript.getDefaultLogger();
    var ajaxAppender = new log4javascript.AjaxAppender(url);
    ajaxAppender.addHeader("Content-Type", "application/json");
    log.addAppender(ajaxAppender);
    window.onerror = function(errorMsg, url, lineNumber){
        log.fatal("Uncaught error "+errorMsg+" in "+url+", line "+lineNumber);
    };
    log.info("Hello World");
}

And I wasn't sure how the data would be passed to the server so I decided to list all attributes and start there. So far, I have the following as server-side code (logger.jsp):

<%@page import="java.util.*"%>

<%
for (Enumeration e = session.getAttributeNames(); e.hasMoreElements(); ) {     
    String attribName = (String) e.nextElement();
    Object attribValue = session.getAttribute(attribName);
    System.out.println(attribName+" - "+attribValue);
}
%> 

Which prints the following to the console:

logger - test.Logger@5a5517ef

I've done a lot of Google searches but came up with nothing that helps with the server side so far. It's quite possible that I missed something so if anyone has gone through this and has any tips or even a VERY bare-bones example of how to receive messages from the AjaxAppender for Log4JavaScript, I would greatly appreciate it!

1

There are 1 best solutions below

1
On BEST ANSWER

If you want to send JSON, use a JsonLayout in your AjaxAppender:

var log = log4javascript.getDefaultLogger();
var ajaxAppender = new log4javascript.AjaxAppender(url);
var jsonLayout = new log4javascript.JsonLayout();
ajaxAppender.setLayout(jsonLayout);
log.addAppender(ajaxAppender);
log.info("Hello World");

This will send the logging message as HTTP form data with one name/value pair whose name is data and whose value is a JSON representation of your logging message.

This is covered in the documentation for AjaxAppender.