program tip

프로덕션 JavaScript 코드에 "console.log ()"호출을 남겨 두는 것이 좋지 않습니까?

radiobox 2020. 10. 23. 07:45
반응형

프로덕션 JavaScript 코드에 "console.log ()"호출을 남겨 두는 것이 좋지 않습니까?


console.log()내 JavaScript에 많은 호출이 있습니다.

프로덕션에 배포하기 전에 주석 처리해야합니까?

나는 그것들을 거기에 남겨두고 싶기 때문에 더 이상 디버깅을해야 할 경우 나중에 주석을 다시 추가하는 문제로 갈 필요가 없습니다. 이것은 나쁜 생각입니까?


Javascript 오류가 발생하여 오류가 포함 된 Javascript 블록의 실행이 종료됩니다.

그러나 Firebug가 활성화되지 않은 경우 작동하지 않는 더미 함수를 정의 할 수 있습니다.

if(typeof console === "undefined") {
    console = { log: function() { } };
}

이외의 방법을 사용하는 경우 해당 방법도 log스텁해야합니다.


다른 사람들이 이미 지적했듯이 그대로두면 일부 브라우저에서 오류가 발생하지만 일부 스텁을 넣어 이러한 오류를 해결할 수 있습니다.

그러나 나는 그것들을 주석 처리 할뿐만 아니라 그 라인들을 완전히 제거 할 것입니다. 그렇지 않으면 엉성해 보입니다. 내가 현학적 인 사람 일 수도 있지만, "프로덕션"코드는 주석이 달린 형태로도 "디버그"코드를 전혀 포함해서는 안된다고 생각합니다. 주석을 전혀 남기지 않으면 해당 주석은 비활성화 된 코드 블록이 아니라 코드가 수행하는 작업 또는 그 뒤에있는 이유를 설명해야합니다. (단, 대부분의 댓글은 최소화 과정에서 자동으로 제거되어야합니다. 최소화하는 중이 지요?)

또한 몇 년 동안 JavaScript로 작업하면서 함수로 돌아가서 "이런 console.logs를 여기에 두 었으면 좋겠어요!"라고 말한 적이 없습니다. 일반적으로 함수 작업을 "완료"하고 나중에 다시 돌아와야 할 때 다른 문제를 해결하기 위해 돌아옵니다. 새로운 문제가 무엇이든, 이전 작업의 console.logs가 도움이된다면 처음으로 문제를 발견했을 것입니다. 즉, 내가 무언가로 돌아 오면 이전에 필요했던 것과 정확히 동일한 디버그 정보가 필요하지 않을 것입니다.

내 2 센트 만 ... 행운을 빕니다!


배포 스크립트가있는 경우이를 사용하여 console.log에 대한 호출을 제거하고 파일을 축소 할 수 있습니다.

거기에있는 동안 JSLint를 통해 JS를 던지고 검사를 위해 위반 사항을 기록하거나 배포를 방지 할 수 있습니다.

이것은 배포를 자동화하려는 이유를 보여주는 좋은 예입니다. 프로세스에서 console.logs가 포함 된 js 파일을 게시 할 수 있다면 언젠가 그렇게 할 것입니다.


내가 아는 console.log한 다음 45 자보다 짧은 스터 빙 방법은 없습니다 .

window.console||(console={log:function(){}});

그것은 당신이 스터브하려는 콘솔 방법에 따라 세 가지 버전 중 첫 번째 버전이며 모두 작고 IE6 + 및 최신 브라우저에서 테스트되었습니다.

다른 두 버전은 다양한 다른 콘솔 방법을 다룹니다. 하나는 네 가지 기본 사항을 다루고 다른 하나는 방화범 및 웹킷에 대해 알려진 모든 콘솔 방법을 다룹니다. 다시 말하지만 가능한 가장 작은 파일 크기입니다.

해당 프로젝트는 github에 있습니다 : https://github.com/andyet/ConsoleDummy.js

코드를 최소화 할 수있는 방법을 생각할 수 있다면 기고를 환영합니다.

-편집-2012 년 5 월 16 일

이후이 코드를 개선했습니다. 여전히 작지만 콘솔 출력을 켜고 끄는 기능이 추가되었습니다 : https://github.com/HenrikJoreteg/andlog

The Changelog Show소개되었습니다.


console.log객체가 존재하지 않는 경우 최소한 더미를 생성해야 합니다. 그래야 Firebug가 설치되지 않은 사용자의 컴퓨터에서 코드가 오류를 발생시키지 않습니다.

또 다른 가능성은 '디버그 모드'에서만 로깅을 트리거하는 것입니다. 즉, 특정 플래그가 설정된 경우 :

if(_debug) console.log('foo');
_debug && console.log('foo');

누군가에게 도움이되기를 바랍니다. 나는 잠시 전에 래퍼를 썼습니다. 허용 된 솔루션보다 약간 더 유연합니다.

분명히 console.info 등과 같은 다른 방법을 사용하면 효과를 복제 할 수 있습니다. 스테이징 환경이 끝나면 기본 C.debug를 프로덕션 용으로 false로 변경하기 만하면 다른 코드를 변경하거나 줄을 제거 할 필요가 없습니다. 나중에 돌아와서 디버그하기가 매우 쉽습니다.

var C = {
    // console wrapper
    debug: true, // global debug on|off
    quietDismiss: false, // may want to just drop, or alert instead
    log: function() {
        if (!C.debug) return false;

        if (typeof console == 'object' && typeof console.log != "undefined") {
            console.log.apply(this, arguments); 
        }
        else {
            if (!C.quietDismiss) {
                var result = "";
                for (var i = 0, l = arguments.length; i < l; i++)
                    result += arguments[i] + " ("+typeof arguments[i]+") ";

                alert(result);
            }
        }
    }
}; // end console wrapper.

// example data and object
var foo = "foo", bar = document.getElementById("divImage");
C.log(foo, bar);

// to surpress alerts on IE w/o a console:
C.quietDismiss = true;
C.log("this won't show if no console");

// to disable console completely everywhere:
C.debug = false;
C.log("this won't show ever");

이것은 나를 위해 일하는 것 같습니다 ...

if (!window.console) {
    window.console = {
        log: function () {},
        group: function () {},
        error: function () {},
        warn: function () {},
        groupEnd: function () {}
    };
}

나는 다른 관점을 공유 할 것이라고 생각했다. PCI 응용 프로그램에서 이러한 유형의 출력을 외부에 표시하면 비준수 상태가됩니다.


I agree that the console stub is a good approach. I've tried various console plugins, code snippets, including some fairly complex ones. They all had some problem in at least one browser, so I ended up going with something simple like below, which is an amalgamation of other snippets I've seen and some suggestions from the YUI team. It appears to function in IE8+, Firefox, Chrome and Safari (for Windows).

// To disable logging when posting a production release, just change this to false.
var debugMode = false;

// Support logging to console in all browsers even if the console is disabled. 
var log = function (msg) {
    debugMode && window.console && console.log ? console.log(msg) : null;
};

Note: It supports disabling logging to the console via a flag. Perhaps you could automate this via build scripts too. Alternatively, you could expose UI or some other mechanism to flip this flag at run time. You can get much more sophisticated of course, with logging levels, ajax submission of logs based on log threshold (e.g. all Error level statements are transmitted to the server for storage there etc.).

Many of these threads/questions around logging seem to think of log statements as debug code and not code instrumentation. Hence the desire to remove the log statements. Instrumentation is extremely useful when an application is in the wild and it's no longer as easy to attach a debugger or information is fed to you from a user or via support. You should never log anything sensitive, regardless of where it's been logged to so privacy/security should not be compromised. Once you think of the logging as instrumentation it now becomes production code and should be written to the same standard.

With applications using ever more complex javascript I think instrumentation is critical.


As other have mentions it will thrown an error in most browsers. In Firefox 4 it won't throw an error, the message is logged in the web developer console (new in Firefox 4).

One workaround to such mistakes that I really liked was de&&bug:

var de = true;
var bug = function() { console.log.apply(this, arguments); }

// within code
de&&bug(someObject);

A nice one-liner:

(!console) ? console.log=function(){} : console.log('Logging is supported.');

참고URL : https://stackoverflow.com/questions/1114187/bad-idea-to-leave-console-log-calls-in-your-production-javascript-code

반응형