Skip to content

Instantly share code, notes, and snippets.

@netshade
Created May 16, 2012 17:30
Show Gist options
  • Save netshade/2712435 to your computer and use it in GitHub Desktop.
Save netshade/2712435 to your computer and use it in GitHub Desktop.
console.log to your node app
// In your connect middleware setup in development mode
app.use(require("./lib/console.log.remote/middleware")());
// Your pages will have to include /console.log.js to override console.log
window.console = window.console || {}
window.console.actual_log = window.console.log || function(){};
window.console._sprintf = function(format){
var return_str = new String(format);
var match;
var reg = /%([osif])/i;
var before, after, replacement;
var argIndex = 1;
do {
match = reg.exec(return_str);
if(match){
before = return_str.substr(0, match.index);
after = return_str.substr(match.index + match[0].length, return_str.length);
replacement = "";
switch(match[1]){
case "o":
if(window.JSON && window.JSON.stringify){
replacement = JSON.stringify(arguments[argIndex]);
} else {
replacement = arguments[argIndex].toString();
}
break;
case "i":
replacement = parseInt(arguments[argIndex]).toString()
break;
case "f":
replacement = arguments[argIndex].toFixed(3)
break;
case "s":
replacement = String(arguments[argIndex])
}
return_str = before + replacement + after;
argIndex ++ ;
}
} while(match);
return return_str;
};
window.console.log = function(format){
var to_server = window.console._sprintf.apply(null, arguments);
window.console.actual_log.apply(window.console, arguments);
var req = new XMLHttpRequest();
req.open("POST", "/console.log", true);
req.setRequestHeader("Content-type", "text/plain");
req.send(to_server);
}
var fs = require("fs");
var remote_console_log_js = fs.readFileSync(__dirname + "/client.js");
module.exports = function(){
return function(req, res, next){
if(req.url == "/console.log.js" && req.method == "GET"){
res.writeHead(200, { 'Content-Type' : 'text/javascript' })
res.end(remote_console_log_js);
} else if(req.url == "/console.log" && req.method == "POST"){
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
console.log("console.log: [",
new Date().getTime(),
req.connection.remoteAddress,
req.header("User-Agent").substring(0, 64) + "...",
"]: ",
data);
res.writeHead(200, { 'Content-Type' : 'text/plain' })
res.end("OK");
});
} else {
next();
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment