前端重写console.log方法

2020-12-29 16:28:45

nuxtjs项目,我本来像用插件来解决,但发现我没找到如何零活控制。

babel-plugin-transform-remove-console这个插件能解决,但是不灵活。


自己重写console却很好的能控制,并且在网页控制台输入变量,还能展示出来线上屏蔽的console。好用。

我们在开发前端的时候,有时候希望在开发和测试过程中,可以输出console.log日志,方便查看,但是在生产环境不需要再console.log的,于是想到重写console.log方法,以下有两种效果:

1. 和原生console.log一样效果

console.log = (function (oriLogFunc) {return function () {//判断配置文件是否开启日志调试if (!Config.isProduct) {try{oriLogFunc.call(console, ...arguments);}catch(e){console.error('console.log error', e);}}}})(console.log);

可以通过配置文件,决定是否要开启console.log输出。用法和原来一样,输出的效果和原生console.log一样,以下是输出结果图片:

 

2. 以数组方式输出效果

console.log = (function (oriLogFunc) {return function () {//判断配置文件是否开启日志调试if (!Config.isProduct) {try{if(arguments && arguments.length > 1){let first = arguments[0];let arr = Array.prototype.slice.call(arguments);let more = arr.slice(1);oriLogFunc.call(console, first, more);}else if (arguments && arguments.length == 1){oriLogFunc.call(console, arguments[0]);}}catch(e){console.error('console.log error', e);}}}})(console.log);

可以通过配置文件,决定是否要开启console.log输出。用法和原来一样,以下是输出结果图片:

 

 

两种方式都可以达到可配置console是否输出的效果,直接把代码放在程序最开始运行之前的位置就可以了。比如项目是RN,把这段代码放在src目录下的app.js文件运行;如果项目是小程序,把代码放在app.js的App()运行前面运行即可;如果项目是Vue,把代码放在main.js目录下运行即可。其它项目都可以类似的。

 

按照上面方法,还可以重写console.error、console.debug方法。


  • 2017-11-06 01:00:17

    撤销git add

    如何撤销git add,不小心执行了git add . 操作,但是又不能提交所有的文件,因为对应不同的分支,现在怎么样可以将git add 撤销回来

  • 2017-11-10 00:06:15

    CORS: credentials mode is 'include'

    XMLHttpRequest cannot load http://localhost/Foo.API/token. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:5000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.