invoke log util, console.log can be switched off

This commit is contained in:
OttoMao
2015-03-23 10:20:04 +08:00
parent bdf5e4fabb
commit 68478cd162
10 changed files with 122 additions and 85 deletions

View File

@@ -6,6 +6,7 @@ var exec = require('child_process').exec,
color = require('colorful'),
readline = require('readline'),
util = require('./util'),
logUtil = require("./log"),
asyncTask = require("async-task-mgr");
//TODO : unstable in windows
@@ -19,10 +20,10 @@ if(!fs.existsSync(certDir)){
try{
fs.mkdirSync(certDir,0777); //may fail in windows
}catch(e){
console.log("===========");
console.log("failed to create cert dir ,please create one by yourself - " + certDir);
console.log("this error will not block main thread unless you use https-related features in anyproxy");
console.log("===========");
logUtil.printLog("===========", logUtil.T_ERR);
logUtil.printLog("failed to create cert dir ,please create one by yourself - " + certDir, logUtil.T_ERR);
logUtil.printLog("this error will not block main thread unless you use https-related features in anyproxy", logUtil.T_ERR);
logUtil.printLog("===========", logUtil.T_ERR);
}
}
@@ -62,7 +63,7 @@ function createCert(hostname,callback){
callback && callback(new Error("error when generating certificate"),null);
}else{
var tipText = "certificate created for __HOST".replace(/__HOST/,hostname);
console.log(color.yellow(color.bold("[internal https]")) + color.yellow(tipText));
logUtil.printLog(color.yellow(color.bold("[internal https]")) + color.yellow(tipText)) ;
callback(null);
}
});
@@ -80,18 +81,19 @@ function isRootCAFileExists(){
}
function checkRootCA(){
if(!isRootCAFileExists()){
console.log(color.red("can not find rootCA.crt or rootCA.key"));
console.log(color.red("you may generate one by the following methods"));
console.log(color.red("\twhen using globally : anyproxy --root"));
console.log(color.red("\twhen using as a module : require(\"anyproxy\").generateRootCA();"));
if(!isRootCAFileExists() || true){
logUtil.printLog(color.red("can not find rootCA.crt or rootCA.key"), logUtil.T_ERR);
logUtil.printLog(color.red("you may generate one by the following methods"), logUtil.T_ERR);
logUtil.printLog(color.red("\twhen using globally : anyproxy --root"), logUtil.T_ERR);
logUtil.printLog(color.red("\twhen using as a module : require(\"anyproxy\").generateRootCA();"), logUtil.T_ERR);
logUtil.printLog(color.red("\tmore info : https://github.com/alibaba/anyproxy/wiki/How-to-config-https-proxy"), logUtil.T_ERR);
process.exit(0);
}
}
function generateRootCA(){
if(isRootCAFileExists()){
console.log(color.yellow("rootCA exists at " + certDir));
logUtil.printLog(color.yellow("rootCA exists at " + certDir));
var rl = readline.createInterface({
input : process.stdin,
output: process.stdout
@@ -101,7 +103,7 @@ function generateRootCA(){
if(/yes/i.test(answer)){
startGenerating();
}else{
console.log("will not generate a new one");
logUtil.printLog("will not generate a new one");
process.exit(0);
}
@@ -114,18 +116,18 @@ function generateRootCA(){
function startGenerating(){
//clear old certs
clearCerts(function(){
console.log(color.green("temp certs cleared"));
logUtil.printLog(color.green("temp certs cleared"));
var spawnSteam = spawn(cmd_genRoot,['.'],{cwd:certDir,stdio: 'inherit'});
spawnSteam.on('close', function (code) {
if(code == 0){
console.log(color.green("rootCA generated"));
console.log(color.green(color.bold("please trust the rootCA.crt in " + certDir)));
console.log(color.green(color.bold("or you may get it via anyproxy webinterface")));
process.exit(0);
logUtil.printLog(color.green("rootCA generated"));
logUtil.printLog(color.green(color.bold("please trust the rootCA.crt in " + certDir)));
logUtil.printLog(color.green(color.bold("or you may get it via anyproxy webinterface")));
}else{
console.log(color.red("fail to generate root CA"));
logUtil.printLog(color.red("fail to generate root CA"),logUtil.T_ERR);
}
process.exit(0);
});
});

View File

@@ -9,6 +9,7 @@ var getPort = require('./getPort'),
crypto = require('crypto'),
color = require('colorful'),
certMgr = require("./certMgr"),
logUtil = require("./log"),
asyncTask = require("async-task-mgr");
var createSecureContext = tls.createSecureContext || crypto.createSecureContext;
@@ -43,11 +44,11 @@ function SNIPrepareCert(serverName,SNICallback){
],function(err,result){
if(!err){
var tipText = "proxy server for __NAME established".replace("__NAME",serverName);
console.log(color.yellow(color.bold("[internal https]")) + color.yellow(tipText));
logUtil.printLog(color.yellow(color.bold("[internal https]")) + color.yellow(tipText));
SNICallback(null,ctx);
}else{
console.log("err occurred when prepare certs for SNI - " + err);
console.log("you may upgrade your Node.js to the lastest version");
logUtil.printLog("err occurred when prepare certs for SNI - " + err, logUtil.T_ERR);
logUtil.printLog("you may upgrade your Node.js to the lastest version", logUtil.T_ERR);
}
});
}

17
lib/log.js Normal file
View File

@@ -0,0 +1,17 @@
var ifPrint = true;
function setPrintStatus(status){
ifPrint = !!status;
}
function printLog(content,type){
if(!ifPrint) return;
var tip = content;
console.log(tip);
}
module.exports.printLog = printLog;
module.exports.setPrintStatus = setPrintStatus;
module.exports.T_TIP = 0;
module.exports.T_ERR = 1;

View File

@@ -3,7 +3,8 @@ var zlib = require('zlib'),
Datastore = require('nedb'),
util = require("util"),
fs = require("fs"),
events = require('events');
events = require('events'),
logUtil = require("./log");
//option.filename
function Recorder(option){
@@ -24,11 +25,11 @@ function Recorder(option){
autoload :true
});
db.persistence.setAutocompactionInterval(5001);
console.log("db file : " + option.filename);
logUtil.printLog("db file : " + option.filename);
}catch(e){
console.log(e);
console.log("Failed to load on-disk db file. Will use in-meomory db instead.");
logUtil.printLog(e, logUtil.T_ERR);
logUtil.printLog("Failed to load on-disk db file. Will use in-meomory db instead.", logUtil.T_ERR);
db = new Datastore();
}

View File

@@ -11,6 +11,7 @@ var http = require("http"),
util = require("./util"),
getPort = require("./getPort"),
Stream = require("stream"),
logUtil = require("./log"),
httpsServerMgr = require("./httpsServerMgr");
var defaultRule = require("./rule_default.js"),
@@ -40,7 +41,7 @@ function userRequestHandler(req,userRes){
resourceInfoId = GLOBAL.recorder.appendRecord(resourceInfo);
}
console.log(color.green("\nreceived request to : " + host + path));
logUtil.printLog(color.green("\nreceived request to : " + host + path));
//get request body and route to local or remote
async.series([fetchReqData,routeReq],function(){});
@@ -63,10 +64,10 @@ function userRequestHandler(req,userRes){
//route to dealing function
function routeReq(callback){
if(userRule.shouldUseLocalResponse(req,reqData)){
console.log("==>use local rules");
logUtil.printLog("==>use local rules");
dealWithLocalResponse(callback);
}else{
console.log("==>will forward to real server by proxy");
logUtil.printLog("==>will forward to real server by proxy");
dealWithRemoteResonse(callback);
}
}
@@ -163,7 +164,7 @@ function userRequestHandler(req,userRes){
//get custom response
},function(callback){
if(userRule.replaceServerResData){
console.log(color.red("replaceServerResData is deprecated, and will be unavilable soon. Use replaceServerResDataAsync instead."));
logUtil.printLog(color.red("replaceServerResData is deprecated, and will be unavilable soon. Use replaceServerResDataAsync instead."), logUtil.T_ERR);
serverResData = userRule.replaceServerResData(req,res,serverResData) || serverResData;
callback();
}else if(userRule.replaceServerResDataAsync){
@@ -225,13 +226,13 @@ function userRequestHandler(req,userRes){
});
res.on('error',function(error){
console.log('error',error);
logUtil.printLog('error' + error, logUtil.T_ERR);
});
});
proxyReq.on("error",function(e){
console.log("err with request :" + e + " " + req.url);
logUtil.printLog("err with request :" + e + " " + req.url, logUtil.T_ERR);
userRes.end();
});
@@ -252,11 +253,11 @@ function connectReqHandler(req, socket, head){
shouldIntercept = false; // TODO : a more general solution?
}
console.log(color.green("\nreceived https CONNECT request " + host));
logUtil.printLog(color.green("\nreceived https CONNECT request " + host));
if(shouldIntercept){
console.log("==>will forward to local https server");
logUtil.printLog("==>will forward to local https server");
}else{
console.log("==>will bypass the man-in-the-middle proxy");
logUtil.printLog("==>will bypass the man-in-the-middle proxy");
}
//record
@@ -334,10 +335,10 @@ function connectReqHandler(req, socket, head){
});
conn.on("error",function(e){
console.log("err when connect to %j, %j" , host , e);
logUtil.printLog("err when connect to + " + host + " , " + e, logUtil.T_ERR);
});
}catch(e){
console.log("err when connect to remote https server (__host)".replace(/__host/,host));
logUtil.printLog("err when connect to remote https server (__host)".replace(/__host/,host), logUtil.T_ERR);
}
//update record
@@ -354,7 +355,7 @@ function connectReqHandler(req, socket, head){
}
],function(err,result){
if(err){
console.log("err " + err);
logUtil.printLog("err " + err, logUtil.T_ERR);
throw err;
}
});
@@ -381,13 +382,13 @@ function setRules(newRule){
}
if('function' == typeof(userRule.summary)){
functions.push(function(cb){
console.log(userRule.summary());
logUtil.printLog(userRule.summary());
cb(null);
});
}
async.series(functions,function(errors,result){
if(!errors){
console.log(color.green('Anyproxy rules initialize finished, have fun!'));
logUtil.printLog(color.green('Anyproxy rules initialize finished, have fun!'));
}
});