Logging with JavaScript/ECMA Script

I am sure this has been done a thousand times, I'm posting because I found a really old posting I wrote on the subject. So anyway, for posterity's sake, I'm copying here.


var logAry = new Array();

function log(message){
	var logImg = new Image(1,1);
	logImg.src = "http://url.here.com/?message=" + escape(message);
	logAry[logAry.length] = logImg;
}

It should be pretty clear what this does. Basically, we are appending the log message as a query string parameter and making the browser request it as an image. The images are stored in an array because objects in the function will lose scope when the function ends. This could prevent some requests from being made. The array just lets the image requests queue up.

You should probably have something to receive the request (one pixel gif maybe), just to prevent filling the log with 404 errors. Also, you do not really need to return an image so you could have a servlet/jsp/asp/php handle the request and possibly write a more detailed log outside of the normal web log.

Just for kicks, here is a version that doesn't use the global variable for the image array.


function log(message){
    var callee = arguments.callee;
    if (!callee.logger) {
        callee.logger = new Array();
    }
    logger = callee.logger;
    var logImg = new Image(1,1);
    logImg.src = "http://url.here.com/?message=" + escape(message);
    logger[logger.length] = logImg;
}

This works due to the fact that functions are objects in javascript. The arguments property is a property of the function and the callee is a reference to the object that is the function. Thus we create a property logger if it doesn't exist, and add the Image objects (which make the requests back to the server) to it. You can alert the length of the array at the end of the function to demonstrate that the image objects are not lost.

A word about caching, if there is an expectation that the same messages be logged for a user, consider adding a random number to the end on the query string. This will help to ensure that a caching browser/proxy/web-accelerator actually make the request so your server can log it.

Comments, questions and insults can be posted here: willcode4beer.blogspot.com .





Sponsors:

About willCode4Beer