1

I have a load of console.logs in my code, but I only need to see them/ turn them on if I need to see them on a site, so I want a way to be able to enable/ disbale them from in browser console by setting up a couple of snippets, such as: adysis.debug('enable') , adysis.debug('disable') but how can i get these to them trigger the console.logs in the code, I got no clue at all at the moment on how to do it?

  • 1
    Does this answer your question? [How to quickly and conveniently disable all console.log statements in my code?](https://stackoverflow.com/questions/1215392/how-to-quickly-and-conveniently-disable-all-console-log-statements-in-my-code) – GrafiCode Aug 29 '23 at 10:37

1 Answers1

2

To disable ALL the console's methods use Proxy.

Use console.enabled = true/false in the browser console to disable/enable console. The disabled state is persisted in the local storage. So it's the same after a page reload.

(Remove try/catch since it's not allowed here).

{
  const key = 'console-enabled';
  
  let enabled;
  try{
  enabled = localStorage.getItem(key);
  }catch(_){}
  
  window.console = new Proxy(window.console, {
    get(console, prop){
      if(prop === 'enabled'){
        return disabled;
      }
      if(!enabled && typeof console[prop] === 'function' && Object.hasOwn(console, prop)){
        return function(){}
      }
      return Reflect.get(...arguments);
    },
    set(console, prop, val){
      if(prop === 'enabled'){
        enabled = val;
        try{
          enabled ? localStorage.setItem(key, val) : localStorage.removeItem(key);
        }catch(_){}
        return true;
      }
      return Reflect.set(...arguments);
    }
  });
}


console.log('disabled');
console.dir(document.body);

$pre.textContent = 'console.log is enumerable: ' + console.propertyIsEnumerable('log');

console.enabled = true;

console.log('enabled');
console.dir(document.body);
<pre id="$pre"></pre>
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17