Permalink
Browse files

Making socket-logger buffer messages to the network client

  • Loading branch information...
1 parent 10036b7 commit bb9e45316af46fc077ed2843710320846040c9aa @saikat committed Sep 13, 2010
Showing with 23 additions and 10 deletions.
  1. +23 −10 lib/socket-logger.js
View
33 lib/socket-logger.js
@@ -1,5 +1,6 @@
var bufferDuration = 1000;
+var clientPrototypeSend = null;
function makeLogger() {
var logger = {
stream : process.stdout,
@@ -9,9 +10,17 @@ function makeLogger() {
failSilently : true,
buf : [],
messageFormatter : null,
+ responseFormatter : null,
+ socketLoggerSyncer : null,
flushBuffer : function() {
if (logger.buf.length) {
- logger.stream.write(logger.buf.join(''), 'utf8');
+ var newArr = logger.buf.map(function(obj) {
+ return JSON.stringify(obj) + '\n';
+ });
+ logger.stream.write(newArr.join(''), 'utf8');
+ if (logger.socketLogger && logger.socketLogger.send) {
+ logger.socketLogger.send(JSON.stringify(logger.buf));
+ }
logger.buf = [];
}
},
@@ -24,13 +33,17 @@ function makeLogger() {
};
socket.on('connection', function(client) {
logger.log(['connect', client.sessionId]);
- var previousSend = client.send;
+ if (!clientPrototypeSend)
+ clientPrototypeSend = client.send;
client.send = function(msg) {
- previousSend.apply(client, [msg]);
+ clientPrototypeSend.apply(client, [msg]);
// Don't log heartbeats
if (msg.indexOf("~h~") == -1) {
var parsedMsg = JSON.parse(msg);
- logger.log(["response", client.sessionId, parsedMsg]);
+ if (logger.responseFormatter)
+ logger.log(["response", client.sessionId, logger.responseFormatter(parsedMsg)]);
+ else
+ logger.log(["response", client.sessionId, parsedMsg]);
}
}
client.on('message', function(message) {
@@ -40,8 +53,12 @@ function makeLogger() {
var theMessage = ['message'];
if (message === logger.authToken) {
logger.socketLogger = client;
- client.send = Client.prototype.send;
+ client.send = clientPrototypeSend;
+ if (logger.socketLoggerSyncer)
+ logger.socketLogger.send(logger.socketLoggerSyncer());
+ return;
}
+
theMessage.push(client.sessionId);
if (logger.logLevel == 2) {
var parsedMsg = JSON.parse(message);
@@ -69,12 +86,8 @@ function makeLogger() {
return;
var currentTime = new Date(),
- timestamp = currentTime.getFullYear() + "/" + (currentTime.getMonth() + 1) + "/" + currentTime.getDate() + ":" + currentTime.getHours() + ":" + currentTime.getMinutes() + ":" + currentTime.getSeconds();
+ timestamp = currentTime.getFullYear() + "/" + (currentTime.getMonth() + 1) + "/" + currentTime.getDate() + ":" + currentTime.getHours() + ":" + currentTime.getMinutes() + ":" + currentTime.getSeconds() + "." + currentTime.getMilliseconds();
msg.unshift(timestamp);
- msg = JSON.stringify(msg) + '\n';
- if (logger.socketLogger && logger.socketLogger.send) {
- logger.socketLogger.send(msg);
- }
logger.buf.push(msg);
} catch (ex) {
if (!logger.failSilently)

0 comments on commit bb9e453

Please sign in to comment.