8 日志系统 - HelloHxz/react-bricks GitHub Wiki

{
  "name": "snk-log",
  "version": "0.0.1",
  "description": "> 支持全局禁止输出日志,增强日志输出格式,支持日志埋点统一处理",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "",
  "license": "ISC",
  "repository": {
    "type": "git",
    "url": "http://git.sinosafe.com.cn/snk/snk-log.git"
  },
  "devDependencies": {
    "express": "^4.16.2",
    "body-parser": "^1.18.2",
    "connect-multiparty": "^2.0.0",
    "fs-extra": "^4.0.2"
  }
}

var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser')
var fs =require('fs-extra');


app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, './')));


app.post('/errorupload',function (req, res) {
    //追加写入
    fs.appendFileSync(path.join(__dirname, './errorlog.txt'), "\r\n"+JSON.stringify(req.body.data));

    setTimeout(()=>{
        res.end(JSON.stringify({code:0}));
   },3000);
});

app.post('/eventsupload',function (req, res) {
    fs.appendFileSync(path.join(__dirname, './eventtrack.txt'), "\r\n"+JSON.stringify(req.body.data));
    setTimeout(()=>{
         res.end(JSON.stringify({code:0}));
    },3000);
});


var server = app.listen(4000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});
;(function(){
    var window_or_global = typeof window !== 'undefined' ? window : global;
    var midconsole = window_or_global.console;

    function SnkLog(config){
        var _this = this;
        this.originConsole = midconsole;
        window_or_global.console = {
            log:function(){
                _this.log.apply(_this,arguments);
            },
            dateString:function(){
                _this.dateString.apply(_this,arguments);
            },
            _errorOriginal:function(){
              _this._errorOriginal.apply(_this,arguments);
            },
            error:function(){
                _this.error.apply(_this,arguments);
            },
            time:function(){
                _this.time.apply(_this,arguments);
            },
            timeEnd:function(){
                _this.timeEnd.apply(_this,arguments);
            },
            warn:function(){
                _this.warn.apply(_this,arguments);
            },
            info:function(){
                _this.info.apply(_this,arguments);
            },
            debug:function(){
                _this.debug.apply(_this,arguments);
            },
            trace:function(){
                _this.trace.apply(_this,arguments);
            },
            group:function(c){
                _this.group(c);
            },
            disableConsole:function(){
                midconsole.disableYellowBox = true;
                _this.disableConsole.apply(_this,arguments);
            },
            enableConsole:function(){
               midconsole.disableYellowBox = false;
                _this.enableConsole.apply(_this,arguments);
           
            },  
            profile:function(){
                _this.profile.apply(_this,arguments);
            },
            profileEnd:function(){
                _this.profileEnd.apply(_this,arguments);
            },
            groupEnd:function(){
                _this.groupEnd();
            },
            getNowString:function(){
                return  _this.getNowString();
            },
            uploadError:function(c){
                _this.uploadError(c);
            },
            clearErrorLogStack:function(){
                _this.clearErrorLogStack();
            },
            clearEventTrackStack:function(){
                _this.clearEventTrackStack();
            },
            uploadEvent:function(c){
                _this.uploadEvent(c);
            },
            clear:function(){
                _this.clear();
            },
        }

        this.freeTouploadEvent = true;
        this.freeTouploadError = true;
        this._disableConsole = false;
        this.config = config||{};
        this._consoleNoDate = !!this.config.consoleNoDate;
        this.errorLogStack = [];
        this.eventTrackStack = [];
        this.errorLogStack_bk = [];
        this.eventTrackStack_bk = [];
        this.uploadIntervalId = null;

        this.eventUploadCount = config.eventUploadCount;
        if(isNaN(this.eventUploadCount)){
            this.eventUploadCount = 5;
        }else{
            this.eventUploadCount = parseInt(this.eventUploadCount);
        }

        this.errorUploadCount = config.errorUploadCount;
        if(isNaN(this.errorUploadCount)){
            this.errorUploadCount = 5;
        }else{
            this.errorUploadCount = parseInt(this.errorUploadCount);
        }

        this.startInterval();

    }

    SnkLog.prototype = {
        disableConsole:function(){
            this._disableConsole = true;
            console.disableYellowBox = true;
        },
        enableConsole:function(){
            this._disableConsole = false;
            console.disableYellowBox = false;
        },
        dateString:function(fomart){
            if( this._disableConsole ){
                return;
            }
            midconsole.log("["+this.getNowString(fomart)+"]");
        },
        getNowString:function(fomart){
            return this.ConvertDateToStr(new Date().valueOf(),fomart||'yyyy-MM-dd hh:mm:ss');
        },
        _outputDate:function(){
            if(this._consoleNoDate){
                return;
            }
            this.dateString();
        },
        log:function(){
            if( this._disableConsole ){
                return;
            }
            this._outputDate();
            midconsole.log.apply(this,arguments);
        },
        clear:function(){
            midconsole.clear();
        },
        error:function(){
            if( this._disableConsole ){
                return;
            }
            this._outputDate();
            midconsole.error.apply(this,arguments);
        },
        _errorOriginal:function(){
          if( this._disableConsole ){
              return;
          }
          if(midconsole._errorOriginal){
            this._outputDate();
            midconsole._errorOriginal.apply(this,arguments);
          }
        },
        info:function(){
            if( this._disableConsole ){
                return;
            }
            this._outputDate();
            midconsole.info.apply(this,arguments);
        },
        profile:function(){
            if( this._disableConsole ){
                return;
            }
            midconsole.profile&&midconsole.profile.apply(this,arguments);
        },
        profileEnd:function(){
            if( this._disableConsole ){
                return;
            }
            midconsole.profileEnd&& midconsole.profileEnd.apply(this,arguments);
        },
        warn:function(){
            if( this._disableConsole ){
                return;
            }
            if(midconsole.warn){
                this._outputDate();
                midconsole.warn.apply(this,arguments);
            }
        },
        group:function(){
            if( this._disableConsole ){
                return;
            }
            midconsole.group&&midconsole.group.apply(this,arguments);
        },
        trace:function(){
            if( this._disableConsole ){
                return;
            }
            if(midconsole.trace){
                this._outputDate();
                midconsole.trace.apply(this,arguments);
            }
        },
        time:function(){
            if( this._disableConsole ){
                return;
            }
            midconsole.time&&midconsole.time.apply(this,arguments);
        },
        timeEnd:function(){
            if( this._disableConsole ){
                return;
            }
            if(midconsole.timeEnd){
               midconsole.timeEnd.apply(this,arguments);
            }
        },
        debug:function(){
            if( this._disableConsole ){
                return;
            }
            if(midconsole.debug){
                this._outputDate();
                midconsole.debug.apply(this,arguments);
            }
        },
        groupEnd:function(){
            if( this._disableConsole ){
                return;
            }
            midconsole.groupEnd&&midconsole.groupEnd.apply(this,arguments);
        },
        _pushErrorLogDone:function(){
            this.freeTouploadError = true;
            if(this.errorLogStack_bk.length>0){
                this.errorLogStack = this.errorLogStack.concat(this.errorLogStack_bk);
                this.errorLogStack_bk = [];
            }
        },
        uploadError:function(jsondata) {
            var _this = this;
            if(this.freeTouploadError){
                this.errorLogStack.push(jsondata);
                this.freeTouploadError = false;
                this._onErrorLogPush();
            }else{
                this.errorLogStack_bk.push(jsondata);
                if(this.config.onErrorLogAdd){
                    this.config.onErrorLogAdd({instance:this});
                }
            }
        },
        _pullEventTrackDone:function(){
            this.freeTouploadEvent = true;
            if(this.eventTrackStack_bk.length>0){
                this.eventTrackStack = this.eventTrackStack.concat(this.eventTrackStack_bk);
                this.eventTrackStack_bk = [];
            }
 
        },
        uploadEvent:function(jsondata) {
            var _this = this;
            if(this.freeTouploadEvent){
                this.eventTrackStack.push(jsondata);
                this.freeTouploadEvent = false;
                this._onEventTrackPush();
            }else{
                this.eventTrackStack_bk.push(jsondata);
                if(this.config.onEventTrackAdd){
                    this.config.onEventTrackAdd({instance:this});
                }
            }
                
        },
        _onEventTrackPush:function(){
            if(this.config.onEventTrackAdd){
                this.config.onEventTrackAdd({instance:this});
            }
            if(this.eventTrackStack.length>=this.eventUploadCount){
                this._uploadEventToServer();
            }else{
                this._pullEventTrackDone();
            }
        },
        cancelInterval:function(){
            if(this.uploadIntervalId){
                clearInterval(this.uploadIntervalId);
                this.uploadIntervalId = null;
            }
        },
        startInterval:function(){
            if(!this.config.uploadFreq){
                return;
            }
            if(isNaN(this.config.uploadFreq)){
                return;
            }
            var _this = this;
            if(!this.uploadIntervalId){
                this.uploadIntervalId = setInterval(function(){
                    _this._uploadEventToServer();
                    _this._uploadErrorToServer();
                },parseInt(this.config.uploadFreq));
            }
        },
        _uploadEventToServer:function(params){
            if(this.eventTrackStack.length===0){
                return;
            }
            if(!this.config.eventTrackServerPath){
                return;
            }
            var _this = this;
            var data = {
                data:this.eventTrackStack
            };

            this.post({
                url: this.config.eventTrackServerPath,
                data:JSON.stringify(data),
                success:function(){
                    console.clearEventTrackStack();
                    _this._pullEventTrackDone();
                },
                error:function(){
                    _this._pullEventTrackDone();
                }
            });
           
        },
        post:function(config){
            var _this = this;
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                if (xhr.readyState==4 && xhr.status==200){
                   var RJSON = JSON.parse(xhr.responseText);
                   if(RJSON.code===0){
                     config.success();
                   }else{
                    config.error();
                   }
                }else if(xhr.status!==0&& xhr.status!==200){
                    config.error();
                }
            }
            xhr.open('POST', config.url, true);
            xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
            xhr.send(config.data);
        },
        _onErrorLogPush:function(){
            if(this.config.onErrorLogAdd){
                this.config.onErrorLogAdd({instance:this});
            }
            if(this.errorLogStack.length>=this.errorUploadCount){
                this._uploadErrorToServer();
            }else{
                this._pushErrorLogDone();
            }
        },
        _uploadErrorToServer:function(){
            if(!this.config.errorLogServerPath){
                return;
            }
            if(this.errorLogStack.length===0){
                return;
            }
            var _this = this;
            var data = {
                data:this.errorLogStack
            };

            this.post({
                url: this.config.errorLogServerPath,
                data:JSON.stringify(data),
                success:function(){
                    console.clearErrorLogStack();
                    _this._pushErrorLogDone();
                },
                error:function(){
                    _this._pushErrorLogDone();
                }
            });
        },
        clearErrorLogStack:function() {
            this.errorLogStack = [];
        },
        clearEventTrackStack:function(){
            this.eventTrackStack = [];
        },
        convertToDate:function(date) {
            try {
                if (date instanceof Date) {
                    return date;
                } else if (!isNaN(date)) {
                    return this.timestampToDate(date);
                } else if (typeof(date) == "string") {
                    return this.convertStrToDate(date);
                }
            } catch (e) {
                return new Date();
            }

            return new Date();
        },
        timestampToDate:function(timestamp) {
            if (!timestamp) return new Date();
            if (timestamp.toString().length === 10) {
                timestamp = timestamp * 1000;
            }
            return new Date(parseInt(timestamp));
        },
        convertStrToDate:function(str) {
            if (!str) {
                return new Date();
            }
            var str_arr = str.split(" ");
            var yearmonthday = str_arr[0];
            var hourminsecond = str_arr[1] || "";
            var hourminsecond_arr = hourminsecond.split(":");
            var yearmonthday_arr = yearmonthday.split("-");
            if (yearmonthday_arr.length != 3) {
                yearmonthday_arr = yearmonthday.split("/");
            }
            if (yearmonthday_arr.length != 3) {
                return new Date();
            }
            if (!hourminsecond) {
                return new Date(yearmonthday_arr[0], parseInt(yearmonthday_arr[1]) - 1, yearmonthday_arr[2]);
            }
            return new Date(yearmonthday_arr[0], parseInt(yearmonthday_arr[1]) - 1, yearmonthday_arr[2], hourminsecond_arr[0] || 0, hourminsecond_arr[1] || 0, hourminsecond_arr[2] || 0);

        },
        ConvertDateToStr:function(date, formart) {
            date = this.convertToDate(date);
            var info = this.getDateInfo(date);
            info.month = info.month < 10 ? "0" + info.month : info.month;
            info.day = info.day < 10 ? "0" + info.day : info.day;
            info.min = info.min < 10 ? "0" + info.min : info.min;
            info.second = info.second < 10 ? "0" + info.second : info.second;
            info.hour = info.hour < 10 ? "0" + info.hour : info.hour;
            if (formart == "yyyy-MM-dd") {
                return info.year + "-" + info.month + "-" + info.day;
            } else if (formart == "yyyy-MM") {
                return info.year + "-" + info.month;
            } else if (formart == "yyyy-MM-dd hh:mm:ss") {
                return info.year + "-" + info.month + "-" + info.day + " " + info.hour + ":" + info.min + ":" + info.second;
            } else if (formart == "MM-dd hh:mm") {
                return info.month + "-" + info.day + " " + info.hour + ":" + info.min;
            } else if (formart == "hh:mm") {
                return info.hour + ":" + info.min;
            } else if (formart == "MM-dd week") {
                return info.month + "-" + info.day + " " + info.week;
            } else if (formart == "yyyy-MM-dd week") {
                return info.year + "-" + info.month + "-" + info.day + " " + info.week;
            } else if (formart == "yyyy-MM-dd hh:mm") {
                return info.year + "-" + info.month + "-" + info.day + " " + info.hour + ":" + info.min;
            }else if(formart == "yyyyMMdd week hh:mm"){
                return info.year + "年" + info.month + "月" + info.day + "日" + info.week + " " + info.hour + ":" + info.min;
            }
            return info.year + "-" + info.month + "-" + info.day;
        },
        weekArr: ["日", "一", "二", "三", "四", "五", "六"],
        getDateInfo:function(date) {
            date = this.convertToDate(date);
            var month = date.getMonth() + 1;
            var day = date.getDate();
            var hour = date.getHours();
            var min = date.getMinutes();
            var second = date.getSeconds();
            var week = date.getDay();
            return {
                year: date.getFullYear(),
                month: month,
                weekStr: this.weekArr[week],
                weekFullStr: "星期" + this.weekArr[week],
                week: "周" + this.weekArr[week],
                monthStr: this._processtime(month),
                day: day,
                dayStr: this._processtime(day),
                hour: hour,
                hourStr: this._processtime(hour),
                min: min,
                minStr: this._processtime(min),
                second: second,
                secondStr: this._processtime(second)
            };
        },
        _processtime:function(num) {
            return (num < 10 ? ("0" + num) : num);
        },


    }

    var moduleName = SnkLog;
    if (typeof module !== 'undefined' && typeof exports === 'object') {
        module.exports = moduleName;
    } else if (typeof define === 'function' && (define.amd || define.cmd)) {
        define(function() { return moduleName; });
    } else {
        window_or_global.SnkLog = moduleName;
    }
}).call(function() {
return this;
});