美文网首页
One-liner JS debug-logger for re

One-liner JS debug-logger for re

作者: Star_C | 来源:发表于2018-07-02 17:05 被阅读0次

    Coding exercise like leetcode, lintcode, hacker rank are just gym rooms for programmers.

    But debug your code on your webpage can be horrible.

    This is even true when you write recursive functions, which I often do.

    So we need a one-liner logger to help our debug. It must be able to inidicate the nested levels of my recursive function. Here it is:

    Code for Copy&Paste

    var Logger=function(){function t(o,t){this.logKey=o,this.writeLog=t}return t.prototype.log=function(o){var t=null;t="function"==typeof o.toString&&"object"!=typeof o?o.toString():o,this.writeLog({logKey:this.logKey,content:t})},t.prototype.child=function(o){return new t(this.logKey+"."+o,this.writeLog)},t}(),consoleLogger=new Logger("MAIN",console.log);
    

    How to use it?

    const logger = consoleLogger; // just for shorter name
    logger.log('debug message 1'); // {logKey: "MAIN", content: "debug message 1"}
    let level2Logger = logger.child('lv2')
    level2Logger.log('debug message 1') // {logKey: "MAIN.lv2", content: "debug message 1"}
    

    As you can see, you will not be confused by the same message if you set a child logger correctly as you pass it into next recursive call.

    相关文章

      网友评论

          本文标题:One-liner JS debug-logger for re

          本文链接:https://www.haomeiwen.com/subject/ljmluftx.html