DUMBUSER
DUMBUSER

Reputation: 531

how to make custom logging in node js

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

Upvotes: 1

Views: 1037

Answers (1)

0xLogN
0xLogN

Reputation: 3823

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

Upvotes: 2

Related Questions