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

3
  • Why not use something like log4js? Commented Jul 2, 2021 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 Commented Jul 2, 2021 at 15:08
  • 1
    Overwriting default functions / prototype is a bad idea. Commented Jul 2, 2021 at 15:31

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you , don't know why i didn't though of that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.