Skip to content

Instantly share code, notes, and snippets.

@eklitzke
Created January 27, 2010 06:39
Show Gist options
  • Save eklitzke/287599 to your computer and use it in GitHub Desktop.
Save eklitzke/287599 to your computer and use it in GitHub Desktop.
/* Super simple logging module */
var posix = require('posix');
/* Create a function for logging. This is asynchronous, and will queue up
* pending log messages if log messages are submitted faster than they can be
* written to disk. */
var log = function () {
/* initialize logging (blocks) */
var log_fd = posix.open('ss.log', process.O_WRONLY | process.O_APPEND | process.O_CREAT, process.S_IRUSR | process.S_IWUSR).wait();
/* The queue of existing log messages. this chains requests in an mbuf-like
* manner, to avoid expensive memory allocations if the buffer gets
* large. */
var log_queue = new Array();
/* Write as much of the first log entry as possible, and try to requeue if
* there's more work to be done. */
function write_log () {
posix.write(log_fd, log_queue[0], null, "ascii").addCallback(function(bytes) {
var remaining = log_queue[0].slice(bytes);
if (remaining)
log_queue[0] = remaining;
else
log_queue = log_queue.slice(1);
if (log_queue.length)
write_log();
});
}
return function(msg) {
var dispatch = (log_queue.length == 0);
log_queue.push(msg + '\n');
if (dispatch)
write_log();
};
}();
/* Test it out */
log('foo');
log('bar');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment