cocos Creator[框架封装之二] 日志系统 设计 与 实现

在游戏开发中,调试代码不仅仅要靠断点调试,也需要日志输出帮助调试!此时,我们希望日志能够打赢出各种各样的颜色,来区分不同的错误信息,也需要知道该日子打印的时间和文件的代码行数,以及函数的调用者,等等。
cocos Creator调试,详细大多数人跟我一样也是借助浏览器来调试完成开发。

1.获取日志打印时间
AppLog.getDateString = function () {
    var d = new Date();
    var str = d.getHours();
    var timeStr = "";
    timeStr += (str.length==1? "0"+str : str) + ":";
    str = d.getMinutes();
    timeStr += (str.length==1? "0"+str : str) + ":";
    str = d.getSeconds();
    timeStr += (str.length==1? "0"+str : str) + ":";
    str = d.getMilliseconds();
    if( str.length==1 ) str = "00"+str;
    if( str.length==2 ) str = "0"+str;
    timeStr += str;

    timeStr = "[" + timeStr + "]";
    return timeStr;
};
2.获取调用堆栈
AppLog.stack = function (index) {
    var e = new Error();
    var lines = e.stack.split("\n");
    lines.shift();
    var result = [];
    lines.forEach(function (line) {
        line = line.substring(7);
        var lineBreak = line.split(" ");
        if (lineBreak.length<2) {
            result.push(lineBreak[0]);
        } else {
            result.push({[lineBreak[0]] : lineBreak[1]});
        }
    });

    var list = [];
    if(index < result.length-1){
        for(var a in result[index]){
            list.push(a);
        }
    }

    var splitList = list[0].split(".");
    return (splitList[0] + ".js->" + splitList[1] + ": ");
}
3.日志封装
AppLog.log = function(){
    var backLog = console.log || cc.log || log;

    if(OPENLOGFLAG){
        backLog.call(this,"%s%s"+cc.js.formatStr.apply(cc,arguments),this.stack(2),AppLog.getDateString());
    }
};

AppLog.info = function () {
    var backLog = console.log || cc.log || log;
    if(OPENLOGFLAG){
        backLog.call(this,"%c%s:"+cc.js.formatStr.apply(cc,arguments),"color:#00CD00;",AppLog.getDateString());
    }
};

AppLog.warn = function(){
    var backLog = console.log || cc.log || log;
    if(OPENLOGFLAG){
        backLog.call(this,"%c%s:"+cc.js.formatStr.apply(cc,arguments),"color:#ee7700;",AppLog.getDateString());
        //cc.warn
    }
};

AppLog.err = function(){
    var backLog = console.log || cc.log || log;
    if(OPENLOGFLAG){
        backLog.call(this,"%c%s:"+cc.js.formatStr.apply(cc,arguments),"color:red",AppLog.getDateString());
    }
};

转载请说明出处:http://blog.csdn.net/u013158916/article/details/53537922

你可能感兴趣的:(CocosCreator)