如何在节点js中进行自定义登录

how to make custom logging in node js

我正在做一个 cli 程序,我需要在记录的字符串旁边记录时间戳, 我使用了这个和平代码:

var DEBUG = (function(){
  var timestamp = function(){};
  timestamp.toString = function(){
    return`[${new Date().getFullYear()+"-"+new Date().getMonth()+"-"+new Date().getDay()+" "+new Date().getHours()+":"+new Date().getMinutes()+":"+new Date().getSeconds() +":"+new Date().getMilliseconds()} ]`.red.bold;    
  };
  return {
      log : console.log.bind(console, '%s', timestamp    )
  }
})();

console = DEBUG 

这很好用,它会记录类似这样的内容

[2021-6-5 17:37:18:13 ] Hello World

我想要的是对其进行更多配置并添加更多参数,例如,如果我想添加任务 ID:

let TaskID = 1 ; 
console.log(TaskID,"Hello World")

它会注销这个

[2021-6-5 17:37:18:13 ][Task ID : 1] Hello World

等等,希望你明白了

不要更改默认的控制台行为。你想要做的是这样的:

function log(tid, m) {
    console.log(`[${new Date().getFullYear()+"-"+new Date().getMonth()+"-"+new Date().getDay()+" "+new Date().getHours()+":"+new Date().getMinutes()+":"+new Date().getSeconds() +":"+new Date().getMilliseconds()} ]`.red.bold + ' [Task ID: ' + tid + '] ' + m);
}