laya 日志统计 过滤

随着开发中代码量的增加,日志查询就很头痛啊。所以还是整个自己的管理来过滤下。

目前针对自己项目使用,记录下下后期可改。

//日志
let Log = console.log;
let Warn = console.warn;
let Error = console.error;

const LOG_LENGTH: number = 300;
const LOG_FILTERS: boolean = false;
let FILTERS_LIST = {
    "MainUI": false,
};
export default class Trace extends Laya.Script {
    private _logList: Array < string > = new Array < string > ();
    private static _instance: Trace = null;
    public static getInstance(): Trace {
        if (Trace._instance === null)
            Trace._instance = new Trace();
        return Trace._instance;
    };

    public log(msg: string | any, ...subst: any[]): void {
        let _msg: string = this.format(msg, subst);
        if (_msg.length < 0)
            return;
        if (LOG_FILTERS) {
            if (this.isValid(FILTERS_LIST[msg]) && !FILTERS_LIST[msg]) return;
        }
        _msg = this._getTimeString() + _msg;
        // GameMainController.Instance.DebugLv && console.log(_msg);
        Log.call(console, _msg);
        this._recordLog(_msg);
    };

    public warn(msg: string | any, ...subst: any[]): void {
        let _msg: string = this.format(msg, subst);
        if (_msg.length < 0)
            return;
        if (LOG_FILTERS) {
            if (this.isValid(FILTERS_LIST[msg]) && !FILTERS_LIST[msg]) return;
        }
        _msg = this._getTimeString() + _msg;
        // GameMainController.Instance.DebugLv && console.warn(_msg);
        Warn.call(console, _msg);
        this._recordLog(_msg);
    };

    public error(msg: string | any, ...subst: any[]): void {
        let _msg: string = this.format(msg, subst);
        if (_msg.length < 0)
            return;
        if (LOG_FILTERS) {
            if (this.isValid(FILTERS_LIST[msg]) && !FILTERS_LIST[msg]) return;
        }
        _msg = this._getTimeString() + _msg;
        // GameMainController.Instance.DebugLv && console.error(_msg);
        Error.call(console, _msg);
        this._recordLog(_msg);
    };

    public getAll(): string {
        let _msg = "";
        for (let i in this._logList)
            _msg = _msg + this._logList[i] + "\n";

        return _msg;
    };
    /**记录日志 */
    private _recordLog(msg: string): void {
        this._logList.length > LOG_LENGTH && this._logList.shift();
        !this.isEmptyStr(msg) && this._logList.push(msg);
    };
    /**获取时间字符串 */
    private _getTimeString(): string {
        let date = new Date();
        return "[" + this.prefix(date.getHours(), '0', 2) +
            ":" + this.prefix(date.getMinutes(), '0', 2) +
            ":" + this.prefix(date.getSeconds(), '0', 2) +
            ":" + this.prefix(date.getMilliseconds(), '0', 3) + "]";
    };
    /**字符串合并 */
    public format(...args: any[]): string {
        let as = [].slice.call(arguments),
            fmt = as.shift(),
            i = 0;
        if (this.isInvalid(fmt))
            return;

        if (typeof fmt !== 'string') fmt = fmt.toString();
        return fmt.replace(/%(\w)?(\d)?([dfsx])/ig, (_, a, b, c) => {
            let s = b ? new Array(b - 0 + 1).join(a || "") : "";
            if (c == "d") s += parseInt(as[i++]);
            if (c == "f") s += parseFloat(as[i++]);
            else if (c == "s") s += as[i++];
            return b ? s.slice(b * -1) : s;
        });
    };
    /**对象是否有效 */
    public isValid < T > (obj: T): boolean {
        return obj !== null && obj !== undefined;
    }
    /**对象是否无效 */
    public isInvalid < T > (obj: T): boolean {
        return !this.isValid(obj);
    };
    /**是否空串 */
    public isEmptyStr(str: string): boolean {
        if (this.isInvalid(str))
            return true;
        return str.length < 1;
    };
    /**在source前面填充N个element使之长度为len */
    public prefix(source: string | number, element: string, len: number): string {
        return (Array(len).join(element) + source).slice(-len);
    }
    /**过滤console输出日志 */
    public filterConsole(excludePatterns, options) {
        options = {
            console,
            methods: [
                'log',
                'debug',
                'info',
                'warn',
                'error',
            ],
            ...options,
        };

        const {
            console: consoleObject,
            methods
        } = options;
        const originalMethods = methods.map(method => consoleObject[method]);

        const check = string => {
            for (const pattern of excludePatterns) {
                if (typeof pattern === 'string') {
                    if (string.includes(pattern)) {
                        return true;
                    }
                } else if (typeof pattern === 'function') {
                    if (pattern(string)) {
                        return true;
                    }
                } else if (pattern.test(string)) {
                    return true;
                }
            }

            return false;
        };

        for (const method of methods) {
            const originalMethod = consoleObject[method];
            consoleObject[method] = (...args) => {
                if (check(this.format(...args))) {
                    return;
                }
                originalMethod(...args);
            };
            consoleObject[method].original = originalMethod;
        }
        return () => {
            for (const [index, method] of methods.entries()) {
                consoleObject[method] = originalMethods[index];
            }
        };

    };
}
export function getAllTrace(): string {
    return Trace.getInstance().getAll();
}

/** 
 * 
import Trace from "../utils/Trace";
(function(){
    console.log = (msg: string | any, ...subst: any[]) => {
        Trace.getInstance().log(msg, subst);
    };
    console.warn = (msg: string | any, ...subst: any[]) => {
        Trace.getInstance().warn(msg, subst);
    };
    console.error = (msg: string | any, ...subst: any[]) => {
        Trace.getInstance().error(msg, subst);
    };
}());

console.log(this.GetName,"xxx");
*/

为了开发书写方便,定义好自定义代码片段,使用起来就方便多了。过滤就方便多了。

{
	// Place your snippets for typescript here. Each snippet is defined under a snippet name and has a prefix, body and 
	// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
	// same ids are connected.
	// Example:
	// "Print to console": {
	// 	"prefix": "log",
	// 	"body": [
	// 		"console.log('$1');",
	// 		"$2"
	// 	],
	// 	"description": "Log output to console"
	// }

	"Print to console": {
		"prefix": "log",
		"body": [
			"console.log(this.GetName,'$1');",
			"$2"
		],
		"description": "Log output to console"
	}
}

当然可以用日志颜色区分下,可以参考How to change node.js's console font color? - Stack Overflow

console.log("%c ddd","color:red");

或者

console.log('\x1b[36m%s\x1b[0m', 'I am cyan');
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值