How do I disable console.log when I am not debuggi

2019-01-31 11:21发布

I have many console.log (or any other console calls) in my code and I would like to use them only when my app is in some kind of "debug mode".

I can't seem to use some kind of logger function and internally use console.log because then I wouldn't know what line fired it. Maybe only with a try/catch, but my logs are very general and I don't want try/catch in my code.

What would you recommend?

11条回答
我命由我不由天
2楼-- · 2019-01-31 11:51

Clobbering global functions is generally a bad idea.

Instead, you could replace all instances of console.log in your code with LOG, and at the beginning of your code:

var LOG = debug ? console.log.bind(console) : function () {};

This will still show correct line numbers and also preserve the expected console.log function for third party stuff if needed.

查看更多
Melony?
3楼-- · 2019-01-31 11:54

Nowdays, in 2014, I simply use GULP (and recommend everyone to, it's an amazing tool), and I have a package installed which is called stripDebug which does that for you.

(I also use uglify and closureCompiler in production)

查看更多
地球回转人心会变
4楼-- · 2019-01-31 11:55

console can out put not just log but errors warnings etc. Here is a function to override all console outputs

(function () {
    var method;
    var noop = function noop() { };
    var methods = [
    'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
    'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
    'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
    'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];
        console[method] = noop;
    }
}());

Refer to detailed post here https://stapp.space/disable-javascript-console-on-production/

查看更多
爷的心禁止访问
5楼-- · 2019-01-31 12:02
// In Development:
var debugMode = true

// In Prod:
var debugMode = false

// This function logs console messages when debugMode is true .
function debugLog(logMessage) {
    if (debugMode) {
        console.log(logMessage);
    }
}

// Use the function instead of console.log
debugLog("This is a debug message");
查看更多
我想做一个坏孩纸
6楼-- · 2019-01-31 12:03

Simple.

Add a little bash script that finds all references to console.log and deletes them.

Make sure that this batch script runs as part of your deployment to production.

Don't shim out console.log as an empty function, that's a waste of computation and space.

查看更多
成全新的幸福
7楼-- · 2019-01-31 12:03

enter image description here

The newest versions of chrome show which line of code in which file fired console.log. If you are looking for a log management system, you can try out logeek it allows you to control which groups of logs you want to see.

查看更多
登录 后发表回答