1

so am doing a cli program and i needed to log the timestamp next to the logged string , i used this peace of code :

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 

this worked well and it would log something like this

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

what i want is to configure it more and add more argurments for example if i want to add Task ID :

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

and it would log out this

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

and so on , hope you got the point

DUMBUSER
  • 491
  • 7
  • 22
  • Why not use something like log4js? – Mureinik Jul 02 '21 at 14:56
  • so log4js log the timestamp but i dont know if u can add the custome arguments ,i think there is only fatal and error and debug and couple more – DUMBUSER Jul 02 '21 at 15:08
  • 1
    [Overwriting default functions / prototype is a bad idea.](https://stackoverflow.com/questions/12260375/javascript-overwriting-functions-prototype-bad-practice) – 0xLogN Jul 02 '21 at 15:31

1 Answers1

2

Do not change the default console behavior. What you want to do is something like this:

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);
}
0xLogN
  • 3,289
  • 1
  • 14
  • 35