(function(window, document) { var logLevels = ["debug", "trace", "log", "info", "warn", "error"]; // 每次log记录成功后需要重置的属性 var publicProps = ["message", "level", "params"]; function createHttpRequest() { if (window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { return new XMLHttpRequest(); } } function AliLogTracker(host, project, logstore) { this.uri_ = "https://" + project + "." + host + "/logstores/" + logstore + "/track?APIVersion=0.6.0"; this.params_ = { params: {}, level: "", message: '', }; this.httpRequest_ = createHttpRequest(); } AliLogTracker.prototype = { /** * 新增键值对到 params 中 * @param {object} params */ setContext: function(params) { if (!!params && params instanceof Object) { this.params_.params = this.params_.params || {}; Object.assign(this.params_.params, params); } }, /** * 新增全局键值对 * @param {string} key * @param {any} value */ setGlobalContext: function(key, value) { this.params_[key] = value; }, logger: function() { this.params_ = this.params_ || {}; var params = {...this.params_}; if (params.params && params.params instanceof Object && Object.values(params.params).length) { params.params = JSON.stringify(params.params); } else { delete params.params; } var url = this.uri_; var queryString = new URLSearchParams(params).toString(); if (queryString) { url += "&" + queryString; try { this.httpRequest_.open("GET", url, true); this.httpRequest_.send(null); publicProps.map(prop => { delete this.params_[prop]; }); } catch (ex) { if (window && window.console && typeof window.console.log === "function") { console.log("Failed to log to ali log service because of this exception:\n" + ex); console.log("Failed log data:", url); } } } } }; logLevels.map(level => { AliLogTracker.prototype[level] = function(message, params) { this.params_.message = message; this.params_.level = level; this.params_.url = window.location.href; this.setContext(params); this.logger(); }; }); window.Tracker = AliLogTracker; })(window, document);