Simple Node.js Logs

Node.js is a framework that executes Javascript server-side through Google’s V8 Javascript engine. The idea behind node.js, or Node, is to handle a higher number of concurrent server requests than the traditional thread-based servers that are employed today. This is done by running an event loop in a single thread, allowing traditional Javascript callbacks to be employed when events completed their tasks. For my first post regarding Node, I will show how to write to a log file, similar to Apache’s access_log in order to keep track of HTTP requests.

If you are not familiar with Node, be sure to check out the Hello World example on the node homepage. In my access_log, I want to store the date and time, the remote address, the method of the request, and the requested URL. I want to make sure I append to the log file, as I do not want to write over the previous logs, so I will use the ‘a+’ flag to ensure that.

Here is the simple logging function:

//joshdulac.com
function update_log(request) {

  var path = "access_log";
  var now = new Date();
  var dateAndTime = now.toUTCString();
  stream = fs.createWriteStream(path, {
    'flags': 'a+',
    'encoding': 'utf8',
    'mode': 0644
  });

  stream.write(dateAndTime + " ", 'utf8');
  stream.write(request.connection.remoteAddress + ": ", 'utf8')
  stream.write(request.method + " ", 'utf8')
  stream.write(request.url + "\n", 'utf8');
  stream.end();
}

Please note that the ‘request’ parameter in the function is the same variable ‘request’ from within the http.createServer function. For review, here is an example output of the log:

Sun, 11 Jul 2010 16:40:28 GMT 127.0.0.1: GET /readme.html
Sun, 11 Jul 2010 16:40:28 GMT 127.0.0.1: GET /readme.html
Sun, 11 Jul 2010 16:40:31 GMT 127.0.0.1: GET /index.html
Sun, 11 Jul 2010 16:40:31 GMT 127.0.0.1: GET /index.html
Sun, 11 Jul 2010 16:40:33 GMT 127.0.0.1: GET /about.html
Sun, 11 Jul 2010 16:40:34 GMT 127.0.0.1: GET /readme.html
Sun, 11 Jul 2010 16:40:35 GMT 127.0.0.1: GET /about.html
Sun, 11 Jul 2010 16:40:36 GMT 127.0.0.1: GET /index.html

Perhaps you want to find out the total number of hits per page? This is very easy to do with bash:

$ cat access_log | awk '{ print $9 }' | sort | uniq -c
      2 /about.html
      3 /index.html
      3 /readme.html

This is just a very simple logging function, and if you want a more robust tool, please check out the node-elf-logger for more features.

Tags: , , , ,

2 Responses to “Simple Node.js Logs”

  1. Eustolia Casano says:

    This site is so great that i will honor it with my comment :)

  2. Nachrichten says:

    This is great! Thanks for posting the example code.

Leave a Reply

Spam protection by WP Captcha-Free