0

I have this :

  //define in utils.js
   function l (message) {
    if (message.includes('success')) {
        return console.log.bind.call(console.log, console, `%c%s`, `color:green;`)
    } else {
        return console.log.bind.call(console.log, console, `%c%s`)
    }
}
   

    l("success to import")("success to import") // execute in index.js

It work because I have the good color and the good row (from index.js and NOT utils.js). But I want to be able to only write l("success this check work", some var,...)

And Not with two pair of parenthesis ...

I want to have a wrapper function which could change color based on log content : If I have succes I want green log If I have error I want red log And display the correct log row, not from utils.js but from other file js where it's called

enter image description here

LexaGC
  • 110
  • 3
  • 13
  • Instead of `var l = (function(message){. . .})`, why not just have: `function l(message){. . .}`? Also, wrapping the function in parenthesis here does nothing. – Scott Marcus Mar 30 '20 at 20:37
  • it's the same result – LexaGC Mar 30 '20 at 20:38
  • Why are you binding to the console? You would only be doing that if you were overriding the original. – epascarello Mar 30 '20 at 20:41
  • I know. That's what I was trying to point out. Your code is more complicated than it need be. It's always best to start with the simplest code possible. – Scott Marcus Mar 30 '20 at 20:42
  • If you doesn't bind it you will lose the row number, some it will tell me it's executed from my utils.js – LexaGC Mar 30 '20 at 20:43

1 Answers1

1

I will recommend create a object to separate out method, like success, fail. However, still needed follow the below syntax. This sample is for node js.

const logger = {
  log: (...messages) => console.log("\x1b[36m%s\x1b[0m", ...messages),
  info: (...messages) => console.log("\x1b[36m%s\x1b[0m", ...messages),
  warn: (...messages) => console.log("\x1b[33m%s\x1b[0m", ...messages),
  error: (...messages) => console.log("\x1b[31m%s\x1b[0m", ...messages),
  success: (...messages) => console.log("\x1b[32m%s\x1b[0m", ...messages),
  _raw: console.log
};
const l = (...messages) => {
  if (messages.length === 1) {
    if (messages[0].indexOf("success") !== -1)
      console.log(`%c${messages[0]}`, "color: green; font-size: 16px;");
    else if (messages[0].indexOf("error") !== -1)
      console.log(`%c${messages[0]}`, "color: red; font-size: 16px;");
    else console.log(`%c${messages[0]}`, "color: blue; font-size: 16px;");
  } else console.log(...messages);
};
l("success to import"); // execute in index.js
l("error to import");
xdeepakv
  • 7,835
  • 2
  • 22
  • 32