Change the native console function.log

Asked

Viewed 51 times

3

There is some way to change the console’s native function.log, but keep the old one?

Ex:

console.log = (e) => {
     antigoConsoleLog(e);
     alert(e); //exemplo
     minhaFuncao(e); //exemplo
}
  • 1

    You didn’t explain the purpose, but there’s a recommendation: Reactotron

1 answer

6


You can... but I advise against it. Other people using your code will have serious problems finding where that method was over-written.

Having said that, you can for example add >>> to all logs like this:

globalThis.console = {
  log: console.log.bind(null, '>>>>')
}
console.log('Teste!');

You can keep a reference to the old one too:

globalThis.consolaAntiga = console;
globalThis.console = {
  log(...args) {
    globalThis.consolaAntiga.log(':::', ...args);
  }
}
console.log('Teste!');
globalThis.consolaAntiga.log('Teste 2');

This code works in Browser and Node.js

  • Thank you very much worked perfectly here

  • only had a problem, in Node I had to use a function I found in Github. GITHUB LINK PAGE

  • Using an old version of Node? @Luíshnrique what gives node -v in the terminal?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.