unknown 4 лет назад
Родитель
Сommit
148aa9a095

+ 4 - 0
.vscode/settings.json

@@ -0,0 +1,4 @@
+{
+    "php.validate.executablePath": "D:\\Program Files\\php-7.4.14\\php.exe",
+    "php.executablePath": "D:\\Program Files\\php-7.4.14\\php.exe"
+}

+ 0 - 209
chrome/background.js

@@ -1,209 +0,0 @@
-/**
- * github: https://github.com/luofei614/SocketLog
- * @author luofei614<weibo.com/luofei614>
- */ 
-var websocket=null;
-var websocket_timeout=0;
-function ws_init()
-{
-    if(websocket)
-    {
-        //避免重复监听
-        websocket.onclose=function(){};//onclose 函数置空,防止重复链接
-        websocket.close(); 
-    }
-    var address=localStorage.getItem('address');
-    var client_id=localStorage.getItem('client_id');
-    if(!address)
-    {
-        address="ws://localhost:1229"; 
-    }
-    if(client_id)
-    {
-        //client_id作为地址
-        address+='/'+client_id;     
-    }
-    websocket=new WebSocket(address);
-
-    websocket.onerror=function(msg)
-    {
-        clearTimeout(websocket_timeout);
-        websocket_timeout=setTimeout(ws_init,2000);
-        localStorage.setItem('status','error');
-        disable_icon();
-    };
-
-    websocket.onclose=function()
-    {
-        setTimeout(function(){
-            clearTimeout(websocket_timeout);
-            websocket_timeout=setTimeout(ws_init,2000);
-        },1000);
-        localStorage.setItem('status','close');
-        disable_icon();
-    }
-
-    websocket.onopen=function()
-    {
-        localStorage.setItem('status','open');
-        enable_icon(); 
-    }
-
-
-    websocket.onmessage=function(event){
-
-        var check_error=function()
-        {
-            if(event.data.indexOf('SocketLog error handler')!='-1')
-            {
-               var opt = {
-                  type: "basic",
-                  title: "注意",
-                  message: "有异常报错,请注意查看console 控制台中的日志",
-                  iconUrl: "logo.png"
-                };
-                chrome.notifications.create('',opt,function(id){
-                    setTimeout(function(){
-                        chrome.notifications.clear(id,function(){});
-                    },3000);
-                });
-
-            }
-
-
-            if(event.data.indexOf('[NO WHERE]')!='-1')
-            {
-                var opt = {
-                  type: "basic",
-                  title: "注意",
-                  message: "存在没有WHERE语句的操作sql语句",
-                  iconUrl: "logo.png"
-                };
-                chrome.notifications.create('',opt,function(id){
-                    setTimeout(function(){
-                        chrome.notifications.clear(id,function(){});
-                    },3000);
-                });
-            }
-
-        };
-       
-        try
-        {
-                  var data=JSON.parse(event.data);
-        }
-        catch(e)
-        {
-           if(0==event.data.indexOf('close:')){
-             websocket.onclose=function(){};//onclose 函数置空,防止重复链接
-             alert('此client_id不允许连接服务');
-           }else{
-             alert('日志格式错误,'+event.data);
-           }
-           return ; 
-        }
-        var client_id=localStorage.getItem('client_id');
-        //判断是否有强制日志
-        if(client_id && data.force_client_id==client_id)
-        {
-          //将强制日志输出到当前的tab页
-          chrome.tabs.query(
-                {currentWindow: true, active: true},
-                function(tabArray) {
-                    if (tabArray && tabArray[0])
-                    {
-                        //延迟保证日志每次都能记录
-                        setTimeout(function(){
-                            check_error();
-                            chrome.tabs.sendMessage(tabArray[0].id,data.logs);
-                        },100);
-                    }
-                }
-            );
-          return ;
-        }
-
-        if((client_id  && data.client_id!=client_id) || !data.tabid)
-        {
-           //不是当前用户的日志不显示。 
-           return ; 
-        }
-        //延迟保证日志每次都能记录
-        setTimeout(function(){
-            check_error();
-            chrome.tabs.sendMessage(parseInt(data.tabid),data.logs);
-        },100);
-    };
-}
-
-function ws_restart()
-{
-    ws_init();
-}
-
-
-function enable_icon() {
-    chrome.browserAction.setIcon({
-        path: "logo.png"
-    });
-}
-
-function disable_icon() {
-    chrome.browserAction.setIcon({
-        path: "logo_disabled.png"
-    });
-}
-
-
-
-ws_init();
-
-
-function url_exp(url)
-{
-    var splatParam    = /\*/g;
-    var escapeRegExp  = /[-[\]{}()+?.,\\^$#\s]/g;
-    url = url.replace(escapeRegExp, '\\$&')
-        .replace(splatParam, '(.*?)');
-    return new RegExp(url, 'i');
-} 
-
-chrome.webRequest.onBeforeSendHeaders.addListener(
-  function(details) {
-
-        var header="tabid="+details.tabId;
-
-        var client_id=localStorage.getItem('client_id');
-        if(!client_id)
-        {
-            client_id='';
-        }
-
-
-        header+="&client_id="+client_id;
-
-        //将Header隐藏在User-Agent中, 不能使用自定义Header了, 不让HTTPS情况下会报不安全
-        for (var i = 0; i < details.requestHeaders.length; ++i) 
-        {
-            if (details.requestHeaders[i].name === 'User-Agent') 
-            {
-                details.requestHeaders[i].value+=" SocketLog("+header+")";
-                break;
-            }
-        }
-
-       return {requestHeaders: details.requestHeaders};
-  },
-  {urls: ["<all_urls>"]},
-  ["blocking", "requestHeaders"]);
-
-chrome.webRequest.onCompleted.addListener(function(details){
-    var online_domain=localStorage.getItem('online_domain');
-    if(online_domain){
-        var exp=url_exp(online_domain);
-        if(exp.test(details.url))
-        {
-                chrome.tabs.sendMessage(details.tabId,'online_evn');
-        }
-    }
-},{urls: ["<all_urls>"],types:['main_frame','sub_frame']});

+ 0 - 38
chrome/evn.js

@@ -1,38 +0,0 @@
-//环境标示,识别正式环境
-chrome.extension.onMessage.addListener(
-function(logs)
-{
-    if('online_evn'==logs)
-    {
-        if('complete'!=document.readyState){
-            document.addEventListener('DOMContentLoaded', show_online_evn, true);
-        }
-        else
-        {
-            show_online_evn();
-        }
-    }
-});
-
-function show_online_evn()
-{
-    if(window.top==window ||  window.top.document.getElementsByTagName('frameset').length>0)
-    {
-        if(!document.getElementById('_socketlog_online_evn_span'))
-        {
-            //标记正式环境
-            var mySpan = document.createElement("span");
-            mySpan.innerHTML = "正式环境,请谨慎操作!";
-            mySpan.style.color = "#fff";
-            mySpan.id="_socketlog_online_evn_span";
-            mySpan.style.backgroundColor = "red";
-            mySpan.style.position="absolute";
-            mySpan.style.top="10px";
-            mySpan.style.left="10px";
-            mySpan.style.padding="5px";
-            mySpan.style.zIndex="10000";
-            document.body.appendChild(mySpan);
-        }
-    }
-}
-

BIN
chrome/images/logo_128.png


BIN
chrome/images/logo_16.png


BIN
chrome/images/logo_64.png


BIN
chrome/images/logo_disabled_128.png


BIN
chrome/images/logo_disabled_16.png


BIN
chrome/images/logo_disabled_64.png


+ 207 - 0
chrome/js/background.js

@@ -0,0 +1,207 @@
+/**
+ * github: https://github.com/luofei614/SocketLog
+ * @author luofei614<weibo.com/luofei614>
+ */
+var websocket = null;
+var websocket_timeout = 0;
+var limit_connect = 1;  // 断线重连次数
+var count = 0;  // 重连计数
+
+function ws_init() {
+    if (websocket) {
+        //避免重复监听
+        websocket.onclose = function() {}; //onclose 函数置空,防止重复链接
+        websocket.close();
+    }
+    var protocol = localStorage.getItem("protocol");
+    var address = localStorage.getItem("address");
+    var port = localStorage.getItem("port");
+    var full_address = "";
+    var client_id = localStorage.getItem("client_id");
+    var open = localStorage.getItem("open");
+
+    if (!protocol) {
+        protocol = "ws";
+    }
+    if (!address) {
+        address = "localhost";
+    }
+    if (!port) {
+        port = "1229";
+    }
+
+    full_address = protocol + "://" + address + ":" + port;
+
+    if (client_id) {
+        //client_id作为地址
+        full_address += "/" + client_id;
+    }
+
+    if (open == "false" || open == null) {
+        disable_icon();
+        localStorage.setItem("status", "close");
+        return false;
+    }
+
+    websocket = new WebSocket(full_address);
+
+    websocket.onerror = function(msg) {
+        localStorage.setItem("status", "error");
+        disable_icon();
+    };
+
+    websocket.onclose = function() {
+        localStorage.setItem("status", "close");
+        disable_icon();
+    };
+
+    websocket.onopen = function() {
+        localStorage.setItem("status", "open");
+        enable_icon();
+    };
+
+    websocket.onmessage = function(event) {
+        var check_error = function() {
+            if (event.data.indexOf("SocketLog error handler") != "-1") {
+                var opt = {
+                    type: "basic",
+                    title: "注意",
+                    message: "有异常报错,请注意查看 Console 控制台中的日志",
+                    iconUrl: "logo.png",
+                };
+                chrome.notifications.create("", opt, function(id) {
+                    setTimeout(function() {
+                        chrome.notifications.clear(id, function() {});
+                    }, 3000);
+                });
+            }
+
+            if (event.data.indexOf("[NO WHERE]") != "-1") {
+                var opt = {
+                    type: "basic",
+                    title: "注意",
+                    message: "存在没有 WHERE 条件的操作 SQL 语句",
+                    iconUrl: "logo.png",
+                };
+                chrome.notifications.create("", opt, function(id) {
+                    setTimeout(function() {
+                        chrome.notifications.clear(id, function() {});
+                    }, 3000);
+                });
+            }
+        };
+
+        try {
+            var data = JSON.parse(event.data);
+        } catch (e) {
+            if (0 == event.data.indexOf("close:")) {
+                websocket.onclose = function() {}; //onclose 函数置空,防止重复链接
+                alert("此 client_id 不允许连接服务");
+            } else {
+                alert("日志格式错误," + event.data);
+            }
+            return;
+        }
+        var client_id = localStorage.getItem("client_id");
+        //判断是否有强制日志
+        if (client_id && data.force_client_id == client_id) {
+            //将强制日志输出到当前的tab页
+            chrome.tabs.query({ currentWindow: true, active: true },
+                function(tabArray) {
+                    if (tabArray && tabArray[0]) {
+                        //延迟保证日志每次都能记录
+                        setTimeout(function() {
+                            check_error();
+                            chrome.tabs.sendMessage(tabArray[0].id, data.logs);
+                        }, 100);
+                    }
+                }
+            );
+            return;
+        }
+
+        if ((client_id && data.client_id != client_id) || !data.tabid) {
+            //不是当前用户的日志不显示。
+            return;
+        }
+        //延迟保证日志每次都能记录
+        setTimeout(function() {
+            check_error();
+            chrome.tabs.sendMessage(parseInt(data.tabid), data.logs);
+        }, 100);
+    };
+}
+
+function ws_restart() {
+    ws_init();
+}
+
+function enable_icon() {
+    chrome.browserAction.setIcon({
+        path: "images/logo_16.png",
+    });
+}
+
+function disable_icon() {
+    chrome.browserAction.setIcon({
+        path: "images/logo_disabled_16.png",
+    });
+}
+
+ws_init();
+
+function url_exp(url) {
+    var splatParam = /\*/g;
+    var escapeRegExp = /[-[\]{}()+?.,\\^$#\s]/g;
+    url = url.replace(escapeRegExp, "\\$&").replace(splatParam, "(.*?)");
+    return new RegExp(url, "i");
+}
+
+chrome.webRequest.onBeforeSendHeaders.addListener(
+    function(details) {
+        var header = "tabid=" + details.tabId;
+        var client_id = localStorage.getItem("client_id");
+
+        if (!client_id) {
+            client_id = "";
+        }
+
+        header += "&client_id=" + client_id;
+
+        var special_domain = localStorage.getItem("special_domain");
+        if (!special_domain) {
+            special_domain = "*.sinaapp.com";
+            localStorage.setItem("special_domain", special_domain);
+        }
+        var exp = url_exp(special_domain);
+        if (exp.test(details.url)) {
+            //如果是特殊环境域名
+            for (var i = 0; i < details.requestHeaders.length; ++i) {
+                if (details.requestHeaders[i].name === "User-Agent") {
+                    //将参数放在User-agent中,兼容SAE的情况
+                    details.requestHeaders[i].value += " SocketLog(" + header + ")";
+                    break;
+                }
+            }
+        } else {
+            details.requestHeaders.push({
+                name: "SocketLog",
+                value: " SocketLog(" + header + ")",
+            });
+        }
+
+        return { requestHeaders: details.requestHeaders };
+    }, { urls: ["<all_urls>"] }, ["blocking", "requestHeaders"]
+);
+
+chrome.webRequest.onCompleted.addListener(
+    function(details) {
+        var online_domain = localStorage.getItem("online_domain");
+        if (online_domain) {
+            var exp = url_exp(online_domain);
+            if (exp.test(details.url)) {
+                chrome.tabs.sendMessage(details.tabId, "online_evn");
+            }
+        }
+    }, { urls: ["<all_urls>"], types: ["main_frame", "sub_frame"] }
+);

+ 29 - 0
chrome/js/evn.js

@@ -0,0 +1,29 @@
+//环境标示,识别正式环境
+chrome.extension.onMessage.addListener(function(logs) {
+    if ("online_evn" == logs) {
+        if ("complete" != document.readyState) {
+            document.addEventListener("DOMContentLoaded", show_online_evn, true);
+        } else {
+            show_online_evn();
+        }
+    }
+});
+
+function show_online_evn() {
+    if (window.top == window || window.top.document.getElementsByTagName("frameset").length > 0) {
+        if (!document.getElementById("_socketlog_online_evn_span")) {
+            //标记正式环境
+            var mySpan = document.createElement("span");
+            mySpan.innerHTML = "正式环境,请谨慎操作!";
+            mySpan.style.color = "#fff";
+            mySpan.id = "_socketlog_online_evn_span";
+            mySpan.style.backgroundColor = "red";
+            mySpan.style.position = "absolute";
+            mySpan.style.top = "10px";
+            mySpan.style.left = "10px";
+            mySpan.style.padding = "5px";
+            mySpan.style.zIndex = "10000";
+            document.body.appendChild(mySpan);
+        }
+    }
+}

+ 27 - 0
chrome/js/log.js

@@ -0,0 +1,27 @@
+/**
+ * github: https://github.com/luofei614/SocketLog
+ * @author luofei614<weibo.com/luofei614>
+ */
+chrome.extension.onMessage.addListener(
+    function(logs) {
+        if ("object" != typeof logs) {
+            return;
+        }
+        logs.forEach(function(log) {
+            if (console[log.type]) {
+                if (log.css) {
+                    console[log.type]("%c" + log.msg, log.css);
+                } else {
+                    console[log.type](log.msg);
+                }
+                return;
+            }
+
+            if ("alert" == log.type) {
+                alert(log.msg);
+            } else {
+                alert("SocketLog type error, " + log.type);
+            }
+        });
+    }
+);

+ 19 - 0
chrome/js/options.js

@@ -0,0 +1,19 @@
+document.addEventListener('DOMContentLoaded', init, false);
+
+function init() {
+    if (localStorage.getItem('online_domain')) {
+        document.getElementById('online_domain').value = localStorage.getItem('online_domain');
+    }
+
+    if (localStorage.getItem('special_domain')) {
+        document.getElementById('special_domain').value = localStorage.getItem('special_domain');
+    }
+
+    document.getElementById('save').addEventListener('click', save, false);
+}
+
+function save() {
+    localStorage.setItem('online_domain', document.getElementById('online_domain').value);
+    localStorage.setItem('special_domain', document.getElementById('special_domain').value);
+    alert('保存成功');
+}

+ 176 - 0
chrome/js/popup.js

@@ -0,0 +1,176 @@
+/**
+ * github: https://github.com/luofei614/SocketLog
+ * @author luofei614<weibo.com/luofei614>
+ */
+document.addEventListener('DOMContentLoaded', init, false);
+/**
+ * 初始化函数
+ * @return {[type]} [description]
+ */
+function init() {
+    var protocol = document.getElementById('protocol');
+    var address = document.getElementById('address');
+    var port = document.getElementById('port');
+    var full_address = document.getElementById('full_address');
+    var client_id = document.getElementById('client_id');
+    var open = document.getElementById('open');
+
+    if (localStorage.getItem('protocol')) {
+        protocol.value = localStorage.getItem('protocol');
+    }
+    if (localStorage.getItem('address')) {
+        address.value = localStorage.getItem('address');
+    }
+    if (localStorage.getItem('port')) {
+        port.value = localStorage.getItem('port');
+    }
+
+    full_address.value = protocol.value + '://' + address.value + ':' + port.value;
+
+    if (localStorage.getItem('client_id')) {
+        client_id.value = localStorage.getItem('client_id');
+    }
+    if (localStorage.getItem('open')) {
+        open.checked = localStorage.getItem('open') == 'false' ? false : true;
+    }
+    // 显示连接状态
+    var status = localStorage.getItem('status');
+    viewStatusNotic(status);
+
+    document.getElementById('save').addEventListener('click', save, false);
+
+    protocol.addEventListener('input', addressChange, false);
+    address.addEventListener('input', addressChange, false);
+    port.addEventListener('input', addressChange, false);
+
+    protocol.addEventListener('porpertychange', addressChange, false);
+    address.addEventListener('porpertychange', addressChange, false);
+    port.addEventListener('porpertychange', addressChange, false);
+
+}
+/**
+ * 检测主机地址变化,实时各项配置值
+ * @param  {[type]} e [description]
+ * @return {[type]}   [description]
+ */
+function addressChange(e) {
+    var protocol = document.getElementById('protocol').value;
+    var address = document.getElementById('address').value;
+    var port = document.getElementById('port').value;
+    document.getElementById('full_address').value = protocol + '://' + address + ':' + port;
+}
+/**
+ * 辅助函数,检测一个值 IP 是否合法
+ * @param  {[type]}  ip [description]
+ * @return {Boolean}    [description]
+ */
+function isValidIP(ip) {
+    var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
+    return reg.test(ip);
+}
+/**
+ * 辅助函数,检测一个值域名是否合法
+ * @param  {[type]}  domain [description]
+ * @return {Boolean}        [description]
+ */
+function isValidDomain(domain) {
+    var reg = /^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+.?$/;
+    return reg.test(domain);
+}
+/**
+ * 辅助函数,检测一个值是否在数组中
+ * @param  {[type]} search [description]
+ * @param  {[type]} array  [description]
+ * @return {[type]}        [description]
+ */
+function inArray(search, array) {
+    for (var i in array) {
+        if (array[i] == search) {
+            return true;
+        }
+    }
+    return false;
+}
+
+/**
+ * 显示弹窗
+ * @param  {[type]} status [description]
+ * @return {[type]}        [description]
+ */
+function viewStatusNotic(status) {
+    if (status) {
+        var text = '', color = '';
+
+        switch (status) {
+            case "connecting":
+                text = '正在连接...';
+                color = '#64bd63';
+                break;
+            case "open":
+                text = '链接成功';
+                color = '#64bd63';
+                break;
+            case "close":
+                text = '链接断开';
+                color = 'gray';
+                break;
+            case "error":
+                text = '链接失败';
+                color = 'red';
+                break;
+            default:
+                alert('运行状态异常');
+                break;
+        }
+        document.getElementById('status-div').style.color = color;
+        document.getElementById('status').innerHTML = text;
+    }
+}
+
+/**
+ * 保存配置项
+ * @return {[type]} [description]
+ */
+function save() {
+    // 获取配置项的值
+    var protocol = document.getElementById('protocol').value;
+    var address = document.getElementById('address').value;
+    var port = document.getElementById('port').value;
+    var client_id = document.getElementById('client_id').value;
+    var open = document.getElementById('open').checked;
+
+    // 校验主机地址和协议
+    var allow_protocols = ['ws', 'wss'];
+    var ipOk = isValidIP(address);
+    var domainOk = isValidDomain(address);
+
+    if (!inArray(protocol, allow_protocols)) {
+        alert('不支持的协议类型');
+        var status = 'error';
+        viewStatusNotic(status);
+        return false;
+    }
+    if (!ipOk || !domainOk) {
+        alert('不是合法的 IP 地址或域名');
+        var status = 'error';
+        viewStatusNotic(status);
+        return false;
+    }
+
+    // 保存配置项的值
+    localStorage.setItem('protocol', protocol);
+    localStorage.setItem('address', address);
+    localStorage.setItem('port', port);
+    localStorage.setItem('client_id', client_id);
+    localStorage.setItem('open', open);
+    // 触发重新连接
+    chrome.extension.getBackgroundPage().ws_restart();
+    // 显示连接状态
+    var status = localStorage.getItem('status');
+    console.log(status);
+    viewStatusNotic(status);
+    // 如果连接成功,关闭当前设置弹出
+    if (status == 'open') {
+        window.close();
+    }
+}

+ 0 - 38
chrome/log.js

@@ -1,38 +0,0 @@
-/**
- * github: https://github.com/luofei614/SocketLog
- * @author luofei614<weibo.com/luofei614>
- */ 
-chrome.extension.onMessage.addListener(
-function(logs)
-{
-    if('object'!=typeof(logs))
-    {
-        return ;
-    }
-    logs.forEach(function(log)
-    {
-            if(console[log.type])
-            {
-              if(log.css)
-              {
-                console[log.type]('%c'+log.msg,log.css);
-              }
-              else
-              {
-                console[log.type](log.msg);
-              }
-              return ;
-            }
-
-            if('alert'==log.type)
-            {
-                alert(log.msg); 
-            }
-            else
-            {
-                alert('SocketLog type error, '+log.type); 
-            }
-    });
-});
-
-

+ 33 - 26
chrome/manifest.json

@@ -1,30 +1,37 @@
 {
-  "manifest_version": 2,
+    "manifest_version": 2,
 
-  "name": "SocketLog",
-  "description": "SocketLog是FirePHP和ChromePHP的替代者,不仅能做ajax调试,还能做API调试。",
-  "version": "2.2.0",
-  "permissions": [ "webRequest","webRequestBlocking", "tabs","notifications", "http://*/*", "https://*/*" ],
-  "content_scripts": [ 
-    {
-      "js": [ "log.js" ],
-      "matches": [ "http://*/*", "https://*/*" ],
-      "run_at": "document_start"
+    "name": "SocketLog",
+    "description": "SocketLog 是 FirePHP 和 ChromePHP 的替代者,不仅能做 ajax 调试,还能做 API 调试。",
+    "version": "2.2.0",
+    "permissions": ["webRequest", "webRequestBlocking", "tabs", "notifications", "http://*/*", "https://*/*"],
+    "content_scripts": [{
+            "js": ["js/log.js"],
+            "matches": ["http://*/*", "https://*/*"],
+            "run_at": "document_start"
+        },
+        {
+            "js": ["js/evn.js"],
+            "matches": ["http://*/*", "https://*/*"],
+            "run_at": "document_start",
+            "all_frames": true
+        }
+    ],
+    "background": {
+        "scripts": ["js/background.js"]
     },
-    {
-      "js": [ "evn.js" ],
-      "matches": [ "http://*/*", "https://*/*" ],
-      "run_at": "document_start",
-      "all_frames":true
+    "options_page": "options.html",
+    "icons": {
+        "16": "images/logo_16.png",
+        "64": "images/logo_64.png",
+        "128": "images/logo_128.png"
+    },
+    "browser_action": {
+        "default_icon": {
+            "16": "images/logo_16.png",
+            "64": "images/logo_64.png",
+            "128": "images/logo_128.png"
+        },
+        "default_popup": "popup.html"
     }
-  ],
-  "background":{
-    "scripts":["background.js"]
-   },
-  "options_page": "options.html",
-  "browser_action": {
-    "default_icon": "logo.png",
-    "default_popup": "popup.html"
-  }
-  
-}
+}

+ 108 - 104
chrome/options.html

@@ -1,119 +1,123 @@
 <!DOCTYPE HTML>
 <html lang="zh-cn">
+
 <head>
     <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,user-scalable=no,target-densitydpi=medium-dpi">
     <meta charset="UTF-8">
-<head>
-    <title>Chrome Logger options</title>
-    <style>
-        body {
-            font-family: helvetica, sans-serif;
-            width: 800px;
-            margin: auto;
-        }
-
-        h1 {
-            font-weight: normal;
-        }
-
-        form {
-            margin: 0;
-        }
-
-        .swatch {
-            position: relative;
-            display: inline-block;
-            border: 1px solid #555;
-            top: 2px;
-            height: 12px;
-            width: 12px;
-        }
-
-        #info {
-            color: red;
-            padding-top: 10px;
-            display: none;
-            text-align: right;
-        }
-
-        header {
-            width: 488px;
-            margin: auto;
-            margin-top: 20px;
-            overflow: hidden;
-        }
-
-        header h1 {
-            margin: 4px 0px 0px 0px;
-        }
 
-        header img {
-            float: left;
-            margin-right: 20px;
-        }
-
-        .content {
-            width: 400px;
-            margin: auto;
-            margin-top: 30px;
-            background: #eee;
-            -webkit-border-radius: 5px;
-            padding: 15px;
-            border: 2px solid #999;
-            overflow: hidden;
-            /*transition: all 0.5s ease-in-out;*/
-        }
-
-        p {
-            margin: 0px 0px 20px 0px;
-            color: #888;
-            padding: 0px;
-        }
-
-        input {
-            margin-bottom: 10px;
-        }
-
-        .buttons {
-            overflow: hidden;
-        }
-
-        button {
-            float: right;
-            margin-left: 10px;
-        }
-
-        p.info {
-            font-size: .8em;
-        }
-    </style>
-
-    <script src="options.js"></script>
-</head>
-<body>
-    <header>
-        <h1>SocketLog Options</h1>
-    </header>
-    <div class="content">
-        <form>
-            <label>
+    <head>
+        <title>Chrome Logger options</title>
+        <style>
+            body {
+                font-family: helvetica, sans-serif;
+                width: 800px;
+                margin: auto;
+            }
+            
+            h1 {
+                font-weight: normal;
+            }
+            
+            form {
+                margin: 0;
+            }
+            
+            .swatch {
+                position: relative;
+                display: inline-block;
+                border: 1px solid #555;
+                top: 2px;
+                height: 12px;
+                width: 12px;
+            }
+            
+            #info {
+                color: red;
+                padding-top: 10px;
+                display: none;
+                text-align: right;
+            }
+            
+            header {
+                width: 488px;
+                margin: auto;
+                margin-top: 20px;
+                overflow: hidden;
+            }
+            
+            header h1 {
+                margin: 4px 0px 0px 0px;
+            }
+            
+            header img {
+                float: left;
+                margin-right: 20px;
+            }
+            
+            .content {
+                width: 400px;
+                margin: auto;
+                margin-top: 30px;
+                background: #eee;
+                -webkit-border-radius: 5px;
+                padding: 15px;
+                border: 2px solid #999;
+                overflow: hidden;
+                /*transition: all 0.5s ease-in-out;*/
+            }
+            
+            p {
+                margin: 0px 0px 20px 0px;
+                color: #888;
+                padding: 0px;
+            }
+            
+            input {
+                margin-bottom: 10px;
+            }
+            
+            .buttons {
+                overflow: hidden;
+            }
+            
+            button {
+                float: right;
+                margin-left: 10px;
+            }
+            
+            p.info {
+                font-size: .8em;
+            }
+        </style>
+
+        <script src="js/options.js"></script>
+    </head>
+
+    <body>
+        <header>
+            <h1>SocketLog Options</h1>
+        </header>
+        <div class="content">
+            <form>
+                <label>
                 特殊环境域名:
                 <input type="text" value="*.sinapp.com" id="special_domain">
             </label>
-            <p class="info">如果你的网站是像SAE一样,不支持传递自定义Header的环境,请在这里填写域名,多个用"|"隔开,支持通配符*</p>
+                <p class="info">如果你的网站是像SAE一样,不支持传递自定义Header的环境,请在这里填写域名,多个用"|"隔开,支持通配符*</p>
 
-            <label>
+                <label>
                 正式环境域名:
                 <input type="text" id="online_domain">
             </label>
-            <p class="info">设置正式环境域名后,在访问时能区别正式环境和开发环境,防止误操作,多个域名用"|"隔开,支持通配符*</p>
+                <p class="info">设置正式环境域名后,在访问时能区别正式环境和开发环境,防止误操作,多个域名用"|"隔开,支持通配符*</p>
+
+                <div class="buttons">
+                    <button id="save">保存</button>
+                </div>
 
-            <div class="buttons">
-                <button id="save">保存</button>
-            </div>
+                <div id="info"></div>
+            </form>
+        </div>
+    </body>
 
-            <div id="info"></div>
-        </form>
-    </div>
-</body>
-</html>
+</html>

+ 0 - 25
chrome/options.js

@@ -1,25 +0,0 @@
-document.addEventListener('DOMContentLoaded', init, false);
-function init()
-{
-    
-    if(localStorage.getItem('online_domain'))
-    {
-        document.getElementById('online_domain').value=localStorage.getItem('online_domain'); 
-    }
-
-    
-    if(localStorage.getItem('special_domain'))
-    {
-        document.getElementById('special_domain').value=localStorage.getItem('special_domain'); 
-    }
-
-    document.getElementById('save').addEventListener('click',save,false);
-}
-
-
-function save()
-{
-    localStorage.setItem('online_domain',document.getElementById('online_domain').value);
-    localStorage.setItem('special_domain',document.getElementById('special_domain').value);
-    alert('保存成功');
-}

+ 185 - 63
chrome/popup.html

@@ -1,71 +1,193 @@
-<!DOCTYPE HTML>
+<!DOCTYPE html>
 <html lang="zh-cn">
+
 <head>
-    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,user-scalable=no">
-    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,user-scalable=no" />
+    <meta charset="UTF-8" />
     <title></title>
-    <script src="popup.js"></script>
+    <script src="js/popup.js"></script>
     <style>
-         body{
-            margin:0px;
-            padding:4px;
-            font-size:14px;
-            color:#333;
-            width:150px;
-            background:url(bg_off.png);
-         }
-         .wrapper{
-            background:#fff;
-            padding:5px 10px;
-         }
-         .status{
-            font-size:12px;
-            color:#ccc;
-            padding-top:10px;
-         }
-         .title{
-           border-bottom:1px solid #ccc;
-           padding:5px;
-           font-size:14px;
-           font-weight:bold;
-           margin-bottom:10px;
-         }
-         .clearfix{
-         
-         }
-         .clearfix:before,
-         .clearfix:after {
-               display: table;
-                 content: " ";
-         }
-
-         .clearfix:after {
-               clear: both;
-         }
-         .help{
-            position:relative;
-            top:-3px;
-            float:right;
-         }
-         input {
-            width:100%;
-         }
+        html,
+        body,
+        div,
+        form,
+        span,
+        input,
+        select,
+        button,
+        a {
+            box-sizing: border-box;
+        }
+        
+        body {
+            margin: 0px;
+            padding: 4px;
+            font-size: 14px;
+            color: #333;
+            width: 200px;
+            background: url(bg_off.png);
+        }
+        
+        .wrapper {
+            background: #fff;
+            padding: 5px 10px;
+        }
+        
+        .status {
+            font-size: 12px;
+            color: #ccc;
+            /*background-color: #ccc;*/
+            padding: 5px 0;
+            margin-top: 5px;
+        }
+        
+        .title {
+            border-bottom: 1px solid #ccc;
+            padding: 5px;
+            font-size: 14px;
+            font-weight: bold;
+            margin-bottom: 10px;
+            text-align: center;
+        }
+        
+        .clearfix {}
+        
+        .clearfix:before,
+        .clearfix:after {
+            display: table;
+            content: " ";
+        }
+        
+        .clearfix:after {
+            clear: both;
+        }
+        
+        .help {
+            position: relative;
+            top: -3px;
+            float: right;
+        }
+        
+        input {
+            width: 100%;
+        }
+        
+        .open {
+            line-height: 40px;
+            width: 100%;
+            position: relative;
+        }
+        
+        .save {
+            margin: 0 auto;
+            display: block;
+        }
+        
+        .mui-switch {
+            width: 36px;
+            height: 24px;
+            position: absolute;
+            top: 5px;
+            right: 0;
+            border: 1px solid #dfdfdf;
+            background-color: #fdfdfd;
+            box-shadow: #dfdfdf 0 0 0 0 inset;
+            border-radius: 10px;
+            border-top-left-radius: 12px;
+            border-top-right-radius: 12px;
+            border-bottom-left-radius: 12px;
+            border-bottom-right-radius: 12px;
+            background-clip: content-box;
+            display: inline-block;
+            -webkit-appearance: none;
+            user-select: none;
+            outline: none;
+        }
+        
+        .mui-switch:before {
+            content: "";
+            width: 22px;
+            height: 22px;
+            position: absolute;
+            top: 0px;
+            left: 0;
+            border-radius: 12px;
+            border-top-left-radius: 12px;
+            border-top-right-radius: 12px;
+            border-bottom-left-radius: 12px;
+            border-bottom-right-radius: 12px;
+            background-color: #fff;
+            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
+        }
+        
+        .mui-switch:checked {
+            border-color: #64bd63;
+            box-shadow: #64bd63 0 0 0 8px inset;
+            background-color: #64bd63;
+        }
+        
+        .mui-switch:checked:before {
+            left: 14px;
+        }
+        
+        .mui-switch.mui-switch-animbg {
+            transition: background-color ease 0.4s;
+        }
+        
+        .mui-switch.mui-switch-animbg:before {
+            transition: left 0.3s;
+        }
+        
+        .mui-switch.mui-switch-animbg:checked {
+            box-shadow: #dfdfdf 0 0 0 0 inset;
+            background-color: #64bd63;
+            transition: border-color 0.4s, background-color ease 0.4s;
+        }
+        
+        .mui-switch.mui-switch-animbg:checked:before {
+            transition: left 0.3s;
+        }
+        
+        .mui-switch.mui-switch-anim {
+            transition: border cubic-bezier(0, 0, 0, 1) 0.4s, box-shadow cubic-bezier(0, 0, 0, 1) 0.4s;
+        }
+        
+        .mui-switch.mui-switch-anim:before {
+            transition: left 0.3s;
+        }
+        
+        .mui-switch.mui-switch-anim:checked {
+            box-shadow: #64bd63 0 0 0 16px inset;
+            background-color: #64bd63;
+            transition: border ease 0.4s, box-shadow ease 0.4s, background-color ease 1.2s;
+        }
+        
+        .mui-switch.mui-switch-anim:checked:before {
+            transition: left 0.3s;
+        }
     </style>
 </head>
+
 <body>
-   <div class="wrapper clearfix">
-   <div class="title">SocketLog 设置</div>
-   <form action="">
-      监听地址: <input type="input" id="address" value="ws://localhost:1229" /> <br />
-      Client_ID: <input type="input" id="client_id"  value="" /> <br />
-      <button type="button" id="save">保 存</button>
-      <div class="status">
-      状态:<span id="status">正在连接...</span>
-      <div class="help">
-        <a href="https://github.com/luofei614/SocketLog" title="帮助" target="_blank"><img width="16" height="16" src="help.png" /></a>
-      </div><!--/help-->
-     </div><!--/status-->
-   </form> 
-   </div>
+    <div class="wrapper clearfix">
+        <div class="title">SocketLog 设置</div>
+        <form action="">
+            监听主机: <input type="input" id="address" value="localhost" /> <br /> 监听协议: <input type="input" id="protocol" value="ws" /> <br /> 监听端口: <input type="input" id="port" value="1229" /> <br /> 监听地址:
+            <input type="input" id="full_address" value="ws://localhost:1229" disabled="" readonly="" /> Client_ID: <input type="input" id="client_id" value="" /> <br />
+            <div class="open">
+                开启:<input id="open" class="mui-switch mui-switch-anim" type="checkbox" />
+            </div>
+            <button type="button" id="save" class="save">保 存</button>
+            <div class="status" id="status-div">
+                状态:<span id="status">正在连接...</span>
+                <div class="help">
+                    <a href="https://github.com/luofei614/SocketLog" title="帮助" target="_blank"><img width="16" height="16" src="help.png" /></a>
+                </div>
+                <!--/help-->
+            </div>
+            <!--/status-->
+        </form>
+    </div>
 </body>
-</html>
+
+</html>

+ 0 - 49
chrome/popup.js

@@ -1,49 +0,0 @@
-/**
- * github: https://github.com/luofei614/SocketLog
- * @author luofei614<weibo.com/luofei614>
- */ 
-document.addEventListener('DOMContentLoaded', init, false);
-function init()
-{
-    if(localStorage.getItem('address'))
-    {
-        document.getElementById('address').value=localStorage.getItem('address'); 
-    }
-
-    if(localStorage.getItem('client_id'))
-    {
-        document.getElementById('client_id').value=localStorage.getItem('client_id'); 
-    }
-    var status=localStorage.getItem('status');
-    if(status)
-    {
-        var text='';
-
-        switch(status)
-        {
-            case "open":
-                text='链接成功';
-            break;
-            case "close":
-                text='链接断开';
-            break;
-            case "error":
-                text='链接失败';
-            break;
-            default:
-              alert('运行状态异常');
-            break;
-        }
-        document.getElementById('status').innerHTML=text; 
-    }
-
-    document.getElementById('save').addEventListener('click',save,false);
-}
-
-function save()
-{
-    localStorage.setItem('address',document.getElementById('address').value);
-    localStorage.setItem('client_id',document.getElementById('client_id').value);
-    chrome.extension.getBackgroundPage().ws_restart();
-    window.close();
-}

+ 20 - 22
composer.json

@@ -1,24 +1,22 @@
 {
-  "name": "luofei614/socketlog",
-  "description": "debug tool for api , ajax,wechat ,v2.3",
-  "keywords": ["SocketLog", "slog", "api"],
-  "license": "MIT",
-  "authors": [
-    {
-      "name": "luofei",
-      "email": "upfy@qq.com"
-    }
-  ],
-  "require":{
-    "php": ">=5.4.0"
-  },
-  "autoload": {
-    "psr-4": {
-      "think\\org\\": "php/"
-    }
-  },
-  "archive" : {
-     "exclude":["!/php"]  
-  },
- "minimum-stability": "dev"
+    "name": "luofei614/socketlog",
+    "description": "debug tool for api , ajax,wechat ,v2.3",
+    "keywords": ["SocketLog", "slog", "api"],
+    "license": "MIT",
+    "authors": [{
+        "name": "luofei",
+        "email": "upfy@qq.com"
+    }],
+    "require": {
+        "php": ">=5.4.0"
+    },
+    "autoload": {
+        "psr-4": {
+            "think\\org\\": "php/"
+        }
+    },
+    "archive": {
+        "exclude": ["!/php"]
+    },
+    "minimum-stability": "dev"
 }

+ 2 - 2
demo.php

@@ -10,12 +10,12 @@ slog(array(
     'force_client_ids'    => array(//日志强制记录到配置的client_id,默认为空,client_id必须在allow_client_ids中
         //'client_01',
         //'client_02',
-    ), 
+    ),
     'allow_client_ids'    => array(//限制允许读取日志的client_id,默认为空,表示所有人都可以获得日志。
         //'client_01',
         //'client_02',
         //'client_03',
-    ), 
+    ),
 ),'config');
 
 //输出日志


+ 16 - 19
php/slog.function.php

@@ -1,34 +1,31 @@
 <?php
 require 'slog.php';
+
 use think\org\Slog;
-function slog($log,$type='log',$css='')
+
+function slog($log, $type = 'log', $css = '')
 {
-    if(is_string($type))
-    {
-        $type=preg_replace_callback('/_([a-zA-Z])/',function($matches){
-            return strtoupper($matches[1]);  
-        } ,$type);
-        if(method_exists('\think\org\Slog',$type) || in_array($type,Slog::$log_types))
-        {
-           return  call_user_func(array('\think\org\Slog',$type),$log,$css);
+    if (is_string($type)) {
+        $type = preg_replace_callback('/_([a-zA-Z])/', function ($matches) {
+            return strtoupper($matches[1]);
+        }, $type);
+        if (method_exists('\think\org\Slog', $type) || in_array($type, Slog::$log_types)) {
+            return  call_user_func(array('\think\org\Slog', $type), $log, $css);
         }
     }
 
-    if(is_object($type) && 'mysqli'==get_class($type))
-    {
-           return Slog::mysqlilog($log,$type);
+    if (is_object($type) && 'mysqli' == get_class($type)) {
+        return Slog::mysqlilog($log, $type);
     }
 
-    if(is_resource($type) && ('mysql link'==get_resource_type($type) || 'mysql link persistent'==get_resource_type($type)))
-    {
-           return Slog::mysqllog($log,$type);
+    if (is_resource($type) && ('mysql link' == get_resource_type($type) || 'mysql link persistent' == get_resource_type($type))) {
+        return Slog::mysqllog($log, $type);
     }
 
 
-    if(is_object($type) && 'PDO'==get_class($type))
-    {
-           return Slog::pdolog($log,$type);
+    if (is_object($type) && 'PDO' == get_class($type)) {
+        return Slog::pdolog($log, $type);
     }
 
-    throw new Exception($type.' is not SocketLog method');
+    throw new Exception($type . ' is not SocketLog method');
 }

+ 238 - 246
php/slog.php

@@ -1,67 +1,66 @@
 <?php
+
 /**
  * github: https://github.com/luofei614/SocketLog
  * @author luofei614<weibo.com/luofei614>
  */
+
 namespace think\org;
+
 class Slog
 {
-    public static $start_time=0;
-    public static $start_memory=0;
-    public static $port=1116;//SocketLog 服务的http的端口号
-    public static $log_types=array('log','info','error','warn','table','group','groupCollapsed','groupEnd','alert');
+    public static $start_time = 0;
+    public static $start_memory = 0;
+    public static $port = 1116; //SocketLog 服务的http的端口号
+    public static $log_types = array('log', 'info', 'error', 'warn', 'table', 'group', 'groupCollapsed', 'groupEnd', 'alert');
 
     protected static $_allowForceClientIds = array();    //配置强制推送且被授权的client_id
 
     protected static $_instance;
 
-    protected static $config=array(
-        'enable'=>true, //是否记录日志的开关
-        'host'=>'localhost',
+    protected static $config = array(
+        'enable' => true, //是否记录日志的开关
+        'host' => 'localhost',
         //是否显示利于优化的参数,如果允许时间,消耗内存等
-        'optimize'=>false,
-        'show_included_files'=>false,
-        'error_handler'=>false,
+        'optimize' => false,
+        'show_included_files' => false,
+        'error_handler' => false,
         //日志强制记录到配置的client_id
-        'force_client_ids'=>array(),
+        'force_client_ids' => array(),
         //限制允许读取日志的client_id
-        'allow_client_ids'=>array()
+        'allow_client_ids' => array()
     );
 
-    protected static $logs=array();
+    protected static $logs = array();
 
-    protected static $css=array(
-        'sql'=>'color:#009bb4;',
-        'sql_warn'=>'color:#009bb4;font-size:14px;',
-        'error_handler'=>'color:#f4006b;font-size:14px;',
-        'page'=>'color:#40e2ff;background:#171717;'
+    protected static $css = array(
+        'sql' => 'color:#009bb4;',
+        'sql_warn' => 'color:#009bb4;font-size:14px;',
+        'error_handler' => 'color:#f4006b;font-size:14px;',
+        'page' => 'color:#40e2ff;background:#171717;'
     );
 
-    public static function __callStatic($method,$args)
+    public static function __callStatic($method, $args)
     {
-        if(in_array($method,self::$log_types))
-        {
-            array_unshift($args,$method);
-            return call_user_func_array(array(self::getInstance(),'record'),$args);
+        if (in_array($method, self::$log_types)) {
+            array_unshift($args, $method);
+            return call_user_func_array(array(self::getInstance(), 'record'), $args);
         }
     }
 
-   public static function sql($sql,$link)
+    public static function sql($sql, $link)
     {
-        if(is_object($link) && 'mysqli'==get_class($link))
-        {
-               return self::mysqlilog($sql,$link);
+        if (is_object($link) && 'mysqli' == get_class($link)) {
+            return self::mysqlilog($sql, $link);
         }
 
-        if(is_resource($link) && ('mysql link'==get_resource_type($link) || 'mysql link persistent'==get_resource_type($link)))
-        {
-               return self::mysqllog($sql,$link);
+        if (is_resource($link) && ('mysql link' == get_resource_type($link) || 'mysql link persistent' == get_resource_type($link))) {
+            return self::mysqllog($sql, $link);
         }
 
 
-        if(is_object($link) && 'PDO'==get_class($link))
-        {
-               return self::pdolog($sql,$link);
+        if (is_object($link) && 'PDO' == get_class($link)) {
+            return self::pdolog($sql, $link);
         }
 
         throw new Exception('SocketLog can not support this database link');
@@ -71,125 +70,113 @@ class Slog
 
     public static function big($log)
     {
-            self::log($log,'font-size:20px;color:red;');
+        self::log($log, 'font-size:20px;color:red;');
     }
 
-    public static function trace($msg,$trace_level=1,$css='')
+    public static function trace($msg, $trace_level = 1, $css = '')
     {
-        if(!self::check())
-        {
-            return ;
+        if (!self::check()) {
+            return;
         }
-        self::groupCollapsed($msg,$css);
-        $traces=debug_backtrace(false);
-        $traces=array_reverse($traces);
+        self::groupCollapsed($msg, $css);
+        $traces = debug_backtrace(false);
+        $traces = array_reverse($traces);
         $trace_level = $trace_level == '' ? 0 : intval($trace_level);
-        $max=count($traces)-$trace_level;
-        for($i=0;$i<$max;$i++){
-            $trace=$traces[$i];
-            $fun=isset($trace['class'])?$trace['class'].'::'.$trace['function']:$trace['function'];
-            $file=isset($trace['file'])?$trace['file']:'unknown file';
-            $line=isset($trace['line'])?$trace['line']:'unknown line';
-            $trace_msg='#'.$i.'  '.$fun.' called at ['.$file.':'.$line.']';
+        $max = count($traces) - $trace_level;
+        for ($i = 0; $i < $max; $i++) {
+            $trace = $traces[$i];
+            $fun = isset($trace['class']) ? $trace['class'] . '::' . $trace['function'] : $trace['function'];
+            $file = isset($trace['file']) ? $trace['file'] : 'unknown file';
+            $line = isset($trace['line']) ? $trace['line'] : 'unknown line';
+            $trace_msg = '#' . $i . '  ' . $fun . ' called at [' . $file . ':' . $line . ']';
             //不输出参数速度会有明显的改善
             //if(!empty($trace['args'])){
             //    self::groupCollapsed($trace_msg);
             //    self::log($trace['args']);
             //    self::groupEnd();
             //}else{
-                self::log($trace_msg);
+            self::log($trace_msg);
             //}
         }
         self::groupEnd();
     }
 
 
-    public static function mysqlilog($sql,$db)
+    public static function mysqlilog($sql, $db)
     {
-        if(!self::check())
-        {
-            return ;
+        if (!self::check()) {
+            return;
         }
 
-        $css=self::$css['sql'];
-        if(preg_match('/^SELECT /i', $sql))
-        {
+        $css = self::$css['sql'];
+        if (preg_match('/^SELECT /i', $sql)) {
             //explain
-            $query = @mysqli_query($db,"EXPLAIN ".$sql);
-            $arr=mysqli_fetch_array($query);
-            self::sqlexplain($arr,$sql,$css);
+            $query = @mysqli_query($db, "EXPLAIN " . $sql);
+            $arr = mysqli_fetch_array($query);
+            self::sqlexplain($arr, $sql, $css);
         }
-        self::sqlwhere($sql,$css);
-        self::trace($sql,2,$css);
+        self::sqlwhere($sql, $css);
+        self::trace($sql, 2, $css);
     }
 
 
-    public static function mysqllog($sql,$db)
+    public static function mysqllog($sql, $db)
     {
-        if(!self::check())
-        {
-            return ;
+        if (!self::check()) {
+            return;
         }
-        $css=self::$css['sql'];
-        if(preg_match('/^SELECT /i', $sql))
-        {
+        $css = self::$css['sql'];
+        if (preg_match('/^SELECT /i', $sql)) {
             //explain
-            $query = @mysql_query("EXPLAIN ".$sql,$db);
-            $arr=mysql_fetch_array($query);
-            self::sqlexplain($arr,$sql,$css);
+            $query = @mysql_query("EXPLAIN " . $sql, $db);
+            $arr = mysql_fetch_array($query);
+            self::sqlexplain($arr, $sql, $css);
         }
         //判断sql语句是否有where
-        self::sqlwhere($sql,$css);
-        self::trace($sql,2,$css);
+        self::sqlwhere($sql, $css);
+        self::trace($sql, 2, $css);
     }
 
 
-    public static function pdolog($sql,$pdo)
+    public static function pdolog($sql, $pdo)
     {
-        if(!self::check())
-        {
-            return ;
+        if (!self::check()) {
+            return;
         }
-        $css=self::$css['sql'];
-        if(preg_match('/^SELECT /i', $sql))
-        {
+        $css = self::$css['sql'];
+        if (preg_match('/^SELECT /i', $sql)) {
             //explain
             try {
-                $obj=$pdo->query( "EXPLAIN ".$sql);
-                if(is_object($obj) && method_exists($obj,'fetch'))
-                {
-                    $arr=$obj->fetch(\PDO::FETCH_ASSOC);
-                    self::sqlexplain($arr,$sql,$css);
+                $obj = $pdo->query("EXPLAIN " . $sql);
+                if (is_object($obj) && method_exists($obj, 'fetch')) {
+                    $arr = $obj->fetch(\PDO::FETCH_ASSOC);
+                    self::sqlexplain($arr, $sql, $css);
                 }
             } catch (Exception $e) {
-
             }
         }
-        self::sqlwhere($sql,$css);
-        self::trace($sql,2,$css);
+        self::sqlwhere($sql, $css);
+        self::trace($sql, 2, $css);
     }
 
-    private static function sqlexplain($arr,&$sql,&$css)
+    private static function sqlexplain($arr, &$sql, &$css)
     {
         $arr = array_change_key_case($arr, CASE_LOWER);
-        if(false!==strpos($arr['extra'],'Using filesort'))
-        {
-              $sql.=' <---################[Using filesort]';
-              $css=self::$css['sql_warn'];
+        if (false !== strpos($arr['extra'], 'Using filesort')) {
+            $sql .= ' <---################[Using filesort]';
+            $css = self::$css['sql_warn'];
         }
-        if(false!==strpos($arr['extra'],'Using temporary'))
-        {
-              $sql.=' <---################[Using temporary]';
-              $css=self::$css['sql_warn'];
+        if (false !== strpos($arr['extra'], 'Using temporary')) {
+            $sql .= ' <---################[Using temporary]';
+            $css = self::$css['sql_warn'];
         }
     }
-    private static function sqlwhere(&$sql,&$css)
+    private static function sqlwhere(&$sql, &$css)
     {
         //判断sql语句是否有where
-        if(preg_match('/^UPDATE |DELETE /i',$sql) && !preg_match('/WHERE.*(=|>|<|LIKE|IN)/i',$sql))
-        {
-           $sql.='<---###########[NO WHERE]';
-           $css=self::$css['sql_warn'];
+        if (preg_match('/^UPDATE |DELETE /i', $sql) && !preg_match('/WHERE.*(=|>|<|LIKE|IN)/i', $sql)) {
+            $sql .= '<---###########[NO WHERE]';
+            $css = self::$css['sql_warn'];
         }
     }
 
@@ -199,45 +186,73 @@ class Slog
      */
     public static function registerErrorHandler()
     {
-        if(!self::check())
-        {
-            return ;
+        if (!self::check()) {
+            return;
         }
 
-        set_error_handler(array(__CLASS__,'error_handler'));
-        register_shutdown_function(array(__CLASS__,'fatalError'));
+        set_error_handler(array(__CLASS__, 'error_handler'));
+        register_shutdown_function(array(__CLASS__, 'fatalError'));
     }
 
     public static function error_handler($errno, $errstr, $errfile, $errline)
     {
-        switch($errno){
-            case E_WARNING: $severity = 'E_WARNING'; break;
-            case E_NOTICE: $severity = 'E_NOTICE'; break;
-            case E_USER_ERROR: $severity = 'E_USER_ERROR'; break;
-            case E_USER_WARNING: $severity = 'E_USER_WARNING'; break;
-            case E_USER_NOTICE: $severity = 'E_USER_NOTICE'; break;
-            case E_STRICT: $severity = 'E_STRICT'; break;
-            case E_RECOVERABLE_ERROR: $severity = 'E_RECOVERABLE_ERROR'; break;
-            case E_DEPRECATED: $severity = 'E_DEPRECATED'; break;
-            case E_USER_DEPRECATED: $severity = 'E_USER_DEPRECATED'; break;
-            case E_ERROR: $severity = 'E_ERR'; break;
-            case E_PARSE: $severity = 'E_PARSE'; break;
-            case E_CORE_ERROR: $severity = 'E_CORE_ERROR'; break;
-            case E_COMPILE_ERROR: $severity = 'E_COMPILE_ERROR'; break;
-            case E_USER_ERROR: $severity = 'E_USER_ERROR'; break;
-            default: $severity= 'E_UNKNOWN_ERROR_'.$errno; break;
-        }
-        $msg="{$severity}: {$errstr} in {$errfile} on line {$errline} -- SocketLog error handler";
-        self::trace($msg,2,self::$css['error_handler']);
+        switch ($errno) {
+            case E_WARNING:
+                $severity = 'E_WARNING';
+                break;
+            case E_NOTICE:
+                $severity = 'E_NOTICE';
+                break;
+            case E_USER_ERROR:
+                $severity = 'E_USER_ERROR';
+                break;
+            case E_USER_WARNING:
+                $severity = 'E_USER_WARNING';
+                break;
+            case E_USER_NOTICE:
+                $severity = 'E_USER_NOTICE';
+                break;
+            case E_STRICT:
+                $severity = 'E_STRICT';
+                break;
+            case E_RECOVERABLE_ERROR:
+                $severity = 'E_RECOVERABLE_ERROR';
+                break;
+            case E_DEPRECATED:
+                $severity = 'E_DEPRECATED';
+                break;
+            case E_USER_DEPRECATED:
+                $severity = 'E_USER_DEPRECATED';
+                break;
+            case E_ERROR:
+                $severity = 'E_ERR';
+                break;
+            case E_PARSE:
+                $severity = 'E_PARSE';
+                break;
+            case E_CORE_ERROR:
+                $severity = 'E_CORE_ERROR';
+                break;
+            case E_COMPILE_ERROR:
+                $severity = 'E_COMPILE_ERROR';
+                break;
+            case E_USER_ERROR:
+                $severity = 'E_USER_ERROR';
+                break;
+            default:
+                $severity = 'E_UNKNOWN_ERROR_' . $errno;
+                break;
+        }
+        $msg = "{$severity}: {$errstr} in {$errfile} on line {$errline} -- SocketLog error handler";
+        self::trace($msg, 2, self::$css['error_handler']);
     }
 
     public static function fatalError()
     {
         // 保存日志记录
-        if ($e = error_get_last())
-        {
-                self::error_handler($e['type'],$e['message'],$e['file'],$e['line']);
-                self::sendLog();//此类终止不会调用类的 __destruct 方法,所以此处手动sendLog
+        if ($e = error_get_last()) {
+            self::error_handler($e['type'], $e['message'], $e['file'], $e['line']);
+            self::sendLog(); //此类终止不会调用类的 __destruct 方法,所以此处手动sendLog
         }
     }
 
@@ -254,34 +269,28 @@ class Slog
 
     protected static function check()
     {
-        if(!self::getConfig('enable'))
-        {
+        if (!self::getConfig('enable')) {
             return false;
         }
-        $tabid=self::getClientArg('tabid');
-         //是否记录日志的检查
-        if(!$tabid && !self::getConfig('force_client_ids'))
-        {
+        $tabid = self::getClientArg('tabid');
+        //是否记录日志的检查
+        if (!$tabid && !self::getConfig('force_client_ids')) {
             return false;
         }
         //用户认证
-        $allow_client_ids=self::getConfig('allow_client_ids');
-        if(!empty($allow_client_ids))
-        {
+        $allow_client_ids = self::getConfig('allow_client_ids');
+        if (!empty($allow_client_ids)) {
             //通过数组交集得出授权强制推送的client_id
             self::$_allowForceClientIds = array_intersect($allow_client_ids, self::getConfig('force_client_ids'));
             if (!$tabid && count(self::$_allowForceClientIds)) {
                 return true;
             }
 
-            $client_id=self::getClientArg('client_id');
-            if(!in_array($client_id,$allow_client_ids))
-            {
+            $client_id = self::getClientArg('client_id');
+            if (!in_array($client_id, $allow_client_ids)) {
                 return false;
             }
-        }
-        else
-        {
+        } else {
             self::$_allowForceClientIds = self::getConfig('force_client_ids');
         }
         return true;
@@ -289,7 +298,7 @@ class Slog
 
     protected static function getClientArg($name)
     {
-        static $args=array();
+        static $args = array();
 
         $key = 'HTTP_USER_AGENT';
 
@@ -297,21 +306,17 @@ class Slog
             $key = 'HTTP_SOCKETLOG';
         }
 
-        if(!isset($_SERVER[$key]))
-        {
+        if (!isset($_SERVER[$key])) {
             return null;
         }
-        if(empty($args))
-        {
-            if(!preg_match('/SocketLog\((.*?)\)/',$_SERVER[$key],$match))
-            {
-                $args=array('tabid'=>null);
+        if (empty($args)) {
+            if (!preg_match('/SocketLog\((.*?)\)/', $_SERVER[$key], $match)) {
+                $args = array('tabid' => null);
                 return null;
             }
-            parse_str($match[1],$args);
+            parse_str($match[1], $args);
         }
-        if(isset($args[$name]))
-        {
+        if (isset($args[$name])) {
             return $args[$name];
         }
         return null;
@@ -319,25 +324,22 @@ class Slog
 
 
     //设置配置
-    public static function  config($config)
+    public static function config($config)
     {
-        $config=array_merge(self::$config,$config);
-        if(isset($config['force_client_id'])){
+        $config = array_merge(self::$config, $config);
+        if (isset($config['force_client_id'])) {
             //兼容老配置
-            $config['force_client_ids']=array_merge($config['force_client_ids'],array($config['force_client_id']));
+            $config['force_client_ids'] = array_merge($config['force_client_ids'], array($config['force_client_id']));
         }
-        self::$config=$config;
-        if(self::check())
-        {
+        self::$config = $config;
+        if (self::check()) {
             self::getInstance(); //强制初始化SocketLog实例
-            if($config['optimize'])
-            {
-                self::$start_time=microtime(true);
-                self::$start_memory=memory_get_usage();
+            if ($config['optimize']) {
+                self::$start_time = microtime(true);
+                self::$start_memory = memory_get_usage();
             }
 
-            if($config['error_handler'])
-            {
+            if ($config['error_handler']) {
                 self::registerErrorHandler();
             }
         }
@@ -345,25 +347,25 @@ class Slog
 
 
     //获得配置
-    public static function  getConfig($name)
+    public static function getConfig($name)
     {
-        if(isset(self::$config[$name]))
+        if (isset(self::$config[$name])) {
             return self::$config[$name];
+        }
         return null;
     }
 
     //记录日志
-    public function record($type,$msg='',$css='')
+    public function record($type, $msg = '', $css = '')
     {
-        if(!self::check())
-        {
-            return ;
+        if (!self::check()) {
+            return;
         }
 
-        self::$logs[]=array(
-            'type'=>$type,
-            'msg'=>$msg,
-            'css'=>$css
+        self::$logs[] = array(
+            'type' => $type,
+            'msg' => $msg,
+            'css' => $css
         );
     }
 
@@ -373,9 +375,9 @@ class Slog
      * @param string $address - 地址
      * @return bool
      */
-    public static function send($host,$message='',$address='/')
+    public static function send($host, $message = '', $address = '/')
     {
-        $url='http://'.$host.':'.self::$port.$address;
+        $url = 'http://' . $host . ':' . self::$port . $address;
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_POST, true);
@@ -383,85 +385,76 @@ class Slog
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
-        $headers=array(
-                 "Content-Type: application/json;charset=UTF-8"
+        $headers = array(
+            "Content-Type: application/json;charset=UTF-8"
         );
-        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);//设置header
+        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); //设置header
         $txt = curl_exec($ch);
         return true;
     }
 
     public static function sendLog()
     {
-        if(!self::check())
-        {
-            return ;
+        if (!self::check()) {
+            return;
         }
 
 
-        $time_str='';
-        $memory_str='';
-        if(self::$start_time)
-        {
-            $runtime=microtime(true)-self::$start_time;
-            $reqs=number_format(1/$runtime,2);
-            $time_str="[运行时间:{$runtime}s][吞吐率:{$reqs}req/s]";
+        $time_str = '';
+        $memory_str = '';
+        if (self::$start_time) {
+            $runtime = microtime(true) - self::$start_time;
+            $reqs = number_format(1 / $runtime, 2);
+            $time_str = "[运行时间:{$runtime}s][吞吐率:{$reqs}req/s]";
         }
-        if(self::$start_memory)
-        {
-            $memory_use=number_format((memory_get_usage()-self::$start_memory)/1024,2);
-            $memory_str="[内存消耗:{$memory_use}kb]";
+        if (self::$start_memory) {
+            $memory_use = number_format((memory_get_usage() - self::$start_memory) / 1024, 2);
+            $memory_str = "[内存消耗:{$memory_use}kb]";
         }
 
-        if(isset($_SERVER['HTTP_HOST']))
-        {
-            $current_uri=$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
-        }
-        else
-        {
-            $current_uri="cmd:".implode(' ',$_SERVER['argv']);
+        if (isset($_SERVER['HTTP_HOST'])) {
+            $current_uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
+        } else {
+            $current_uri = "cmd:" . implode(' ', $_SERVER['argv']);
         }
-        array_unshift(self::$logs,array(
-                'type'=>'group',
-                'msg'=>$current_uri.$time_str.$memory_str,
-                'css'=>self::$css['page']
+        array_unshift(self::$logs, array(
+            'type' => 'group',
+            'msg' => $current_uri . $time_str . $memory_str,
+            'css' => self::$css['page']
         ));
 
-        if(self::getConfig('show_included_files'))
-        {
-            self::$logs[]=array(
-                    'type'=>'groupCollapsed',
-                    'msg'=>'included_files',
-                    'css'=>''
+        if (self::getConfig('show_included_files')) {
+            self::$logs[] = array(
+                'type' => 'groupCollapsed',
+                'msg' => 'included_files',
+                'css' => ''
             );
-            self::$logs[]=array(
-                    'type'=>'log',
-                    'msg'=>implode("\n",get_included_files()),
-                    'css'=>''
+            self::$logs[] = array(
+                'type' => 'log',
+                'msg' => implode("\n", get_included_files()),
+                'css' => ''
             );
-            self::$logs[]=array(
-                    'type'=>'groupEnd',
-                    'msg'=>'',
-                    'css'=>'',
+            self::$logs[] = array(
+                'type' => 'groupEnd',
+                'msg' => '',
+                'css' => '',
             );
         }
 
-        self::$logs[]=array(
-                'type'=>'groupEnd',
-                'msg'=>'',
-                'css'=>'',
+        self::$logs[] = array(
+            'type' => 'groupEnd',
+            'msg' => '',
+            'css' => '',
         );
 
-        $tabid=self::getClientArg('tabid');
-        if(!$client_id=self::getClientArg('client_id'))
-        {
-            $client_id='';
+        $tabid = self::getClientArg('tabid');
+        if (!$client_id = self::getClientArg('client_id')) {
+            $client_id = '';
         }
-        if(!empty(self::$_allowForceClientIds))
-        {
+        if (!empty(self::$_allowForceClientIds)) {
             //强制推送到多个client_id
-            foreach(self::$_allowForceClientIds as $force_client_id) {
-                $client_id=$force_client_id;
+            foreach (self::$_allowForceClientIds as $force_client_id) {
+                $client_id = $force_client_id;
                 self::sendToClient($tabid, $client_id, self::$logs, $force_client_id);
             }
         } else {
@@ -477,22 +470,21 @@ class Slog
      * @param $logs
      * @param $force_client_id
      */
-    protected static function sendToClient($tabid, $client_id, $logs, $force_client_id) {
-         $logs=array(
-            'tabid'=>$tabid,
-            'client_id'=>$client_id,
-            'logs'=>$logs,
-            'force_client_id'=>$force_client_id,
+    protected static function sendToClient($tabid, $client_id, $logs, $force_client_id)
+    {
+        $logs = array(
+            'tabid' => $tabid,
+            'client_id' => $client_id,
+            'logs' => $logs,
+            'force_client_id' => $force_client_id,
         );
-        $msg=@json_encode($logs);
-        $address='/'.$client_id; //将client_id作为地址, server端通过地址判断将日志发布给谁
-        self::send(self::getConfig('host'),$msg,$address);
+        $msg = @json_encode($logs);
+        $address = '/' . $client_id; //将client_id作为地址, server端通过地址判断将日志发布给谁
+        self::send(self::getConfig('host'), $msg, $address);
     }
 
     public function __destruct()
     {
         self::sendLog();
     }
-
 }
-

+ 5 - 5
server/config.json

@@ -1,6 +1,6 @@
 {
-  //是否开启对client_id的验证
-  "client_verify":false, 
-  //能连接服务器的client_id
-  "client_ids":["luofei_zfH5NbLn"]    
-}
+    // 是否开启对 client_id 的验证
+    "client_verify": false,
+    // 能连接服务器的 client_id
+    "client_ids": ["luofei_zfH5NbLn"]
+}

+ 83 - 74
server/index.html

@@ -1,80 +1,89 @@
 <!DOCTYPE html>
 <html>
-    <head>
-        <meta charset="utf-8" />
-        <meta name="viewport" content="width=device-width" />
-        <title>ThinkPHP SocketLog服务</title>
-        <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
-<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
-<script>
-function makeid()
-{
-  var text = "";
-  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
- 
-  for( var i=0; i < 5; i++ )
-    text += possible.charAt(Math.floor(Math.random() * possible.length));
- 
-  return text;
-}
-    function gen_client_id(){
-        var c_id='tp'+makeid()+'_'+makeid();
-        $('#client_id').html(c_id);
-        $('#gen').show();
-    }
-</script>
-        <style>
-.bg{
-    background:#1E88E5;
-        padding:100px;
-            color:#fff;
-}
-.bg a{
-    color:#fff;
-}
-.bg .info{
-    font-size:25px;
-}
-.btn-yellow{
-    color:#fff;
-    background:#ffab40;
-        margin-top:20px;
-}
 
-.box{
-        width:500px;
-            margin:0 auto;
-}
-.ps{
-    margin:20px auto;
-        width:500px;
+<head>
+    <meta charset="utf-8" />
+    <meta name="viewport" content="width=device-width" />
+    <title>ThinkPHP SocketLog服务</title>
+    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
+    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
+    <script>
+        function makeid() {
+            var text = "";
+            var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
+
+            for (var i = 0; i < 5; i++)
+                text += possible.charAt(Math.floor(Math.random() * possible.length));
+
+            return text;
+        }
+
+        function gen_client_id() {
+            var c_id = 'tp' + makeid() + '_' + makeid();
+            $('#client_id').html(c_id);
+            $('#gen').show();
+        }
+    </script>
+    <style>
+        .bg {
+            background: #1E88E5;
+            padding: 100px;
+            color: #fff;
+        }
+        
+        .bg a {
+            color: #fff;
+        }
+        
+        .bg .info {
+            font-size: 25px;
+        }
+        
+        .btn-yellow {
+            color: #fff;
+            background: #ffab40;
+            margin-top: 20px;
+        }
         
-}
-        </style>
-    </head>
-    <body>
+        .box {
+            width: 500px;
+            margin: 0 auto;
+        }
+        
+        .ps {
+            margin: 20px auto;
+            width: 500px;
+        }
+    </style>
+</head>
 
-<a href="https://github.com/luofei614/SocketLog" target="_blank"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a>
-        <div class="bg">
-            <div class="container text-center">
-                <h1>ThinkPHP SocketLog服务</h1>
-                <p class="info">调试程序、分析源码的好工具</p>
-                <p>具体使用方法,请阅读GitHUb项目上的文档:<a href="http://github.com/luofei614" target="_blank">http://github.com/luofei614</a></p>
-                <p>点击下方按钮,生成Client_id进行使用</p>
-                <button class="btn btn-yellow" onclick="gen_client_id();">生成Client_ID</button>
-            </div>
-        </div><!--/bg-->
-        <br />
-        <div id="gen" style="display:none;">
-            <div class="alert alert-dark box" role="alert">
-                        <code>
-                            服务器地址:ws://slog.thinkphp.cn<br />
-                            client_id:<span id="client_id"></span>
-                        </code>
-            </div>
-            <p class="ps">
-            免费服务,不保证服务稳定性,如对稳定性要求高,请查看GitHub项目页的服务端安装方法。
-            </p>
+<body>
+
+    <a href="https://github.com/luofei614/SocketLog" target="_blank">
+        <img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub">
+    </a>
+    <div class="bg">
+        <div class="container text-center">
+            <h1>ThinkPHP SocketLog服务</h1>
+            <p class="info">调试程序、分析源码的好工具</p>
+            <p>具体使用方法,请阅读GitHUb项目上的文档:<a href="http://github.com/luofei614" target="_blank">http://github.com/luofei614</a></p>
+            <p>点击下方按钮,生成Client_id进行使用</p>
+            <button class="btn btn-yellow" onclick="gen_client_id();">生成Client_ID</button>
         </div>
-    </body>
-</html>
+    </div>
+    <!--/bg-->
+    <br />
+    <div id="gen" style="display:none;">
+        <div class="alert alert-dark box" role="alert">
+            <code>
+                服务器地址:ws://slog.thinkphp.cn<br />
+                client_id:<span id="client_id"></span>
+            </code>
+        </div>
+        <p class="ps">
+            免费服务,不保证服务稳定性,如对稳定性要求高,请查看GitHub项目页的服务端安装方法。
+        </p>
+    </div>
+</body>
+
+</html>

+ 27 - 34
server/index.js

@@ -2,72 +2,65 @@ var ws = require("nodejs-websocket");
 var http = require('http');
 var fs = require('fs');
 var stripJsonComments = require('strip-json-comments');
-function loadJSONFile (file) {
-      var json = fs.readFileSync(file).toString();
-        return JSON.parse(stripJsonComments(json));
+
+function loadJSONFile(file) {
+    var json = fs.readFileSync(file).toString();
+    return JSON.parse(stripJsonComments(json));
 }
-var server = ws.createServer(function (conn) {
-    var config=loadJSONFile(__dirname+'/config.json');
-    if(config.client_verify){
+var server = ws.createServer(function(conn) {
+    var config = loadJSONFile(__dirname + '/config.json');
+    if (config.client_verify) {
         //验证client_id
-        var client_id=conn.path.substring(1);
-        if(-1 === config.client_ids.indexOf(client_id)){
-            conn.sendText('close:client_id不允许连接');
+        var client_id = conn.path.substring(1);
+        if (-1 === config.client_ids.indexOf(client_id)) {
+            conn.sendText('close:client_id 不允许连接');
             conn.close();
         }
     }
     console.log("New connection");
-    conn.on("close", function (code, reason) {
+    conn.on("close", function(code, reason) {
         console.log("Connection closed");
     });
-    conn.on("error", function (err) {
+    conn.on("error", function(err) {
         console.log(err);
     });
 }).listen(1229);
 
 //广播消息
-function broadcast(msg,path) {
-    server.connections.forEach(function (conn) {
+function broadcast(msg, path) {
+    server.connections.forEach(function(conn) {
         //通过path判断,将日志发给指定的client_id
-        if(conn.path==path)
-        {
+        if (conn.path == path) {
             console.log('##send message##');
             conn.sendText(msg);
         }
     });
 }
 
-var httpServer = http.createServer(function(request, response){
-     if('POST'==request.method)
-     {
+var httpServer = http.createServer(function(request, response) {
+    if ('POST' == request.method) {
         var requestBody = '';
         request.on('data', function(data) {
-            requestBody+=data;
+            requestBody += data;
         });
-        request.on('end',function(){
+        request.on('end', function() {
             console.log(requestBody);
             //发送日志
-            broadcast(requestBody,request.url);
+            broadcast(requestBody, request.url);
             response.end('sucess');
         });
-     }
-     else
-     {
-         response.end('please request with POST method');
-     }
+    } else {
+        response.end('please request with POST method');
+    }
 });
 httpServer.listen(1116);
 
 
-
 //测试服务的申请页面
-var httpServer = http.createServer(function(request, response){
-      var html = fs.readFileSync(__dirname+'/index.html').toString();
-      response.end(html);
+var httpServer = http.createServer(function(request, response) {
+    var html = fs.readFileSync(__dirname + '/index.html').toString();
+    response.end(html);
 });
 httpServer.listen(8712);
 
-
-
-
-console.log('SocketLog started success');
+console.log('SocketLog started success');