【问题标题】:how to make custom logging in node js如何在节点js中进行自定义日志记录
【发布时间】:2021-09-14 12:47:48
【问题描述】:

所以我正在做一个 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] 你好世界

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

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

它会注销这个

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

等等,希望你明白了

【问题讨论】:

标签: javascript node.js console.log


【解决方案1】:

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

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);
}

【讨论】:

  • 谢谢,不知道为什么我没有想到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
  • 2019-11-15
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多