program story

console.log ()를 재정의하십시오.

inputbox 2020. 8. 6. 08:20
반응형

console.log ()를 재정의하십시오. 생산 용 [중복]


Javascript 개발에 익숙하지 않아서 이것이 초보자 초보자 일 수 있습니다.

디버깅 목적으로 응용 프로그램을 가지고 console.log();있습니다.

나는 모든 빌드 타임을 결합하는 가지고있다 . app.debug.js디버깅 및 app.min.js프로덕션 용 으로 출력합니다.

이제 console.log();프로덕션으로 갈 준비가되었을 때 모든 코드 파일을 찾아 수동으로 삭제할 수는 있지만 메소드를 재정의하는 방법이 있는지 궁금합니다.

기본적으로 console.log();메소드가 호출 될 때마다 NOT NOTHING.

그렇게하면 디버그 구성이 아닌 프로덕션 구성에 재정의 코드 파일을 넣을 수 있습니다.

이게 가능해?


이것을 파일 맨 위에 놓으십시오.

var console = {};
console.log = function(){};

일부 브라우저 및 축소 기의 경우이를 윈도우 객체에 적용해야 할 수도 있습니다.

window.console = console;

또는 콘솔의 동작을 다시 정의하려는 경우 (예를 들어 로그를 추가하기 위해) 다음과 같이 할 수 있습니다.

// define a new console
var console=(function(oldCons){
    return {
        log: function(text){
            oldCons.log(text);
            // Your code
        },
        info: function (text) {
            oldCons.info(text);
            // Your code
        },
        warn: function (text) {
            oldCons.warn(text);
            // Your code
        },
        error: function (text) {
            oldCons.error(text);
            // Your code
        }
    };
}(window.console));

//Then redefine the old console
window.console = console;

프로덕션 빌드에서 로깅을 토글 할 수 있으면 매우 유용합니다. 아래 코드는 기본적으로 로거를 끕니다.

로그를 볼 필요가있을 때 debug(true)콘솔에 입력 하면됩니다.

var consoleHolder = console;
function debug(bool){
    if(!bool){
        consoleHolder = console;
        console = {};
        Object.keys(consoleHolder).forEach(function(key){
            console[key] = function(){};
        })
    }else{
        console = consoleHolder;
    }
}
debug(false);

철저히 말하면 이것은뿐만 아니라 모든 콘솔 메소드를 대체 console.log합니다.


console.log = function(){};

다른 것과 마찬가지로 재정의하십시오.


I use something similar to what posit labs does. Save the console in a closure and you have it all in one portable function.

var GlobalDebug = (function () {
    var savedConsole = console;
    return function(debugOn,suppressAll){
        var suppress = suppressAll || false;
        if (debugOn === false) {
            console = {};
            console.log = function () { };
            if(suppress) {
                console.info = function () { };
                console.warn = function () { };
                console.error = function () { };
            } else {
                console.info = savedConsole.info;
                console.warn = savedConsole.warn;
                console.error = savedConsole.error;              
            }
        } else {
            console = savedConsole;
        }
    }
})();

Just do globalDebug(false) to toggle log messages off or globalDebug(false,true) to remove all console messages.


I would recommend using: https://github.com/sunnykgupta/jsLogger

Features:

  1. It safely overrides the console.log.
  2. Takes care if the console is not available (oh yes, you need to factor that too.)
  3. Stores all logs (even if they are suppressed) for later retrieval.
  4. Handles major console functions like log, warn, error, info.

Is open for modifications and will be updated whenever new suggestions come up.

Disclaimer: I am the author of the plugin.


You could also use regex to delete all the console.log() calls in your code if they're no longer required. Any decent IDE will allow you to search and replace these across an entire project, and allow you to preview the matches before committing the change.

\s*console\.log\([^)]+\);

Just remember that with this method each console.log call will still do a call to a (empty) function causing overhead, if there are 100 console.log commands, you are still doing 100 calls to a blank function.

Not sure how much overhead this would cause, but there will be some, it would be preferable to have a flag to turn debug on then use something along the lines of:

var debug=true; if (debug) console.log('blah')

Theres no a reason to let all that console.log all over your project in prod enviroment... If you want to do it on the proper way, add UglifyJS2 to your deployment process using "drop_console" option.


After read a lot of posts, I made my own solution as follow:

SCRIPT:

function extendConsole() {
    "use strict";
    try {
        var disabledConsoles = {};

        console.enable = function (level, enabled) {
            // Prevent errors in browsers without console[level]
            if (window.console === 'undefined' || !window.console || window.console === null) {
                window.console = {};
            }
            if (window.console[level] === 'undefined' || !window.console[level] || window.console[level] == null) {
                window.console[level] = function() {};
            }

            if (enabled) {
                if (disabledConsoles[level]) {
                    window.console[level] = disabledConsoles[level];
                }
                console.info("console." + level + "() was enabled.");
            } else {
                disabledConsoles[level] = window.console[level];
                window.console[level] = function () { };
                console.info("console." + level + "() was disabled.");
            }
        };
    } catch (exception) {
        console.error("extendConsole() threw an exception.");
        console.debug(exception);
    }
}

USAGE:

extendConsole();
console.enable("debug", window.debugMode);

EXAMPLE:

http://jsfiddle.net/rodolphobrock/2rzxb5bo/10/


This will override console.log function when the url does not contain localhost. You can replace the localhost with your own development settings.

// overriding console.log in production
if(window.location.host.indexOf('localhost:9000') < 0) {
    console.log = function(){};
}

You can look into UglifyJS: http://jstarrdewar.com/blog/2013/02/28/use-uglify-to-automatically-strip-debug-messages-from-your-javascript/, https://github.com/mishoo/UglifyJS I haven't tried it yet.

Quoting,

 if (typeof DEBUG === 'undefined') DEBUG = true; // will be removed

 function doSomethingCool() {
     DEBUG && console.log("something cool just happened"); // will be removed }

... 로그 메시지 행은 Uglify의 데드 코드 리무버에 의해 제거됩니다 (항상 거짓으로 평가되는 모든 조건을 지우므로). 첫 번째 조건부도 마찬가지입니다. 그러나 압축되지 않은 코드로 테스트 할 때는 DEBUG가 정의되지 않은 상태로 시작되고 첫 번째 조건부에서이를 true로 설정하고 모든 console.log () 메시지가 작동합니다.


여기 내가 한 일이 있습니다

    var domainNames =["fiddle.jshell.net"]; // we replace this by our production domain.

var logger = {
    force:false,
    original:null,
    log:function(obj)
    {
        var hostName = window.location.hostname;
        if(domainNames.indexOf(hostName) > -1)
        {
            if(window.myLogger.force === true)
            {
                window.myLogger.original.apply(this,arguments);
            }
        }else {
            window.myLogger.original.apply(this,arguments);
        }
    },
    forceLogging:function(force){
        window.myLogger.force = force;
    },
    original:function(){
        return window.myLogger.original;
    },
    init:function(){
        window.myLogger.original = console.log;
        console.log = window.myLogger.log;
    }
}

window.myLogger = logger;
console.log("this should print like normal");
window.myLogger.init();
console.log("this should not print");
window.myLogger.forceLogging(true);
console.log("this should print now");

또한 여기에 게시했습니다. http://bhavinsurela.com/naive-way-of-overriding-console-log/

참고 URL : https://stackoverflow.com/questions/7042611/override-console-log-for-production

반응형