One-liner JS debug-logger for recursive function coding exercise

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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容