Method and significance of JS shielding console.log in production environment

console.log: Print a message to the web development console, which is often used for debugging and analysis during development. Sometimes during development, you need to print some object information, but forget to remove the console.log statement when publishing, which may cause memory leaks.

The object passed to console.log cannot be garbage collected♻️ , because the object information needs to be viewed in the development tool after the code is run. So it's best not to console.log any objects in production.

Just execute the following global function directly:

//Determine whether the configuration file enables log debugging or not to output the log True output False not output
var logDebug = false;
console.log = (function (oriLogFunc) {
  return function () {
    if (logDebug) {
      oriLogFunc.apply(this, arguments);
    }
  }
})(console.log);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Of course, you can also rewrite the console.log function to block its console printing operations.
Objects printed by console.log will not be collected by the garbage collector. Therefore it is best not to console.log any large objects in the page, which may affect the overall performance of the page, especially in a production environment. In addition to console.log, there are similar problems in console.dir, console.error, console.warn, etc., and these details need special attention.

Related: Method and significance of JS shielding console.log in production environment