Console

Console 객체는 브라우저의 디버깅 콘솔(Firefox 웹 콘솔 등)에 접근할 수 있는 메서드를 제공합니다. 동작 방식은 브라우저마다 다르지만, 사실상 표준으로 여겨지는 기능도 여럿 있습니다.

Console 객체는 아무 전역 객체에서나 접근할 수 있습니다. 브라우징 문맥에선 Window, 워커에서는 WorkerGlobalScope이 속성으로 포함하고 있습니다. Window.console의 형태로 노출되어 있으므로 간단하게 console로 참조할 수 있습니다.

console.log("링크를 열 수 없습니다")

이 문서는 콘솔 객체에서 사용할 수 있는 메서드와 몇 가지 예제를 다룹니다.

주의: This feature is available in Web Workers.

메서드

Console.assert()
첫 번째 매개변수가 false인 경우 메시지와 스택 추적을 출력합니다.
Console.clear()
콘솔의 내용을 지웁니다.
Console.count()
주어진 라벨로 메서드를 호출한 횟수를 출력합니다.
Console.countReset()
주어진 라벨의 횟수를 초기화합니다.
Console.debug()
"debug" 중요도로 메시지를 출력합니다.
참고: Chromium 브라우저는 58 버전 이후 브라우저 콘솔의 "Verbose" 레벨을 선택하지 않으면 이 메서드의 출력 결과가 보이지 않습니다.
Console.dir()
주어진 JavaScript 객체의 속성 목록을 상호작용 가능한 형태로 표시합니다. 속성 값이 다른 객체라면 펼쳐서 살펴볼 수 있습니다.
Console.dirxml()

객체를 XML/HTML 요소 형태로 나타낼 수 있으면 그렇게 표시하고, 아닐 경우 JavaScript 객체 형태로 표시합니다.

Console.error()
오류 메시지를 출력합니다. 추가 매개변수와 함께 문자열 치환을 사용할 수 있습니다.
Console.exception()
error()의 별칭입니다.
Console.group()
새로운 인라인 그룹을 생성해, 이후 모든 출력을 한 단계 들여씁니다. 그룹을 나오려면 groupEnd()를 호출하세요.
Console.groupCollapsed()
새로운 인라인 그룹을 생성해, 이후 모든 출력을 한 단계 들여씁니다. 그러나 group()과 달리, groupCollapsed()로 생성한 그룹은 처음에 접혀 있습니다. 그룹을 나오려면 groupEnd()를 호출하세요.
Console.groupEnd()
현재 인라인 그룹을 나옵니다.
Console.info()
정보 메시지를 출력합니다. 추가 매개변수와 함께 문자열 치환을 사용할 수 있습니다.
Console.log()
일반 메시지를 출력합니다. 추가 매개변수와 함께 문자열 치환을 사용할 수 있습니다.
Console.profile()
브라우저의 내장 프로파일러(Firefox 성능 측정 도구 등)를 실행합니다. 선택 사항으로 프로파일에 이름을 붙일 수 있습니다.
Console.profileEnd()
프로파일러를 멈춥니다. 프로파일 결과는 브라우저의 성능 측정 도구(Firefox 성능 측정 도구 등)에서 확인할 수 있습니다.
Console.table()
표 형태의 데이터를 표에 그립니다.
Console.time()
주어진 이름의 타이머를 실행합니다. 하나의 페이지에서는 최대 10,000개의 타이머를 동시에 실행할 수 있습니다.
Console.timeEnd()
지정한 타이머를 멈추고, 소요시간을 출력합니다.
Console.timeStamp()
브라우저의 타임라인이나 워터폴에 마커를 추가합니다.
Console.trace()
스택 추적을 출력합니다.
Console.warn()
경고 메시지를 출력합니다. 추가 매개변수와 함께 문자열 치환을 사용할 수 있습니다.

예제

콘솔에 텍스트 출력하기

콘솔에서 가장 많이 사용하는 기능은 데이터와 텍스트를 출력하는 것입니다. 콘솔 메시지의 중요도는 네 가지로, 각각 console.log(), console.info(), console.warn(), console.error() 메서드를 사용해 출력할 수 있습니다. 중요도 별로 출력 스타일이 조금씩 다르며, 중요도 필터를 사용해 원하는 메시지만 골라 볼 수도 있습니다.

There are two ways to use each of the output methods; you can simply pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of the objects with which to replace them.

단일 객체를 출력하기

단일 객체는 다음과 같은 방법으로 출력한다:

var someObject = { str: "Some text", id: 5 };
console.log(someObject);

다음과 같이 출력된다:

[09:27:13.475] ({str:"Some text", id:5})

여러 객체를 출력하기

여러 객체를 출력하는 방법은 메소드를 호출할 때 나열하면 된다:

var car = "Dodge Charger";
var someObject = {str:"Some text", id:5}; 
console.info("My first car was a", car, ". The object is: ", someObject);

다음과 같이 출력된다:

[09:28:22.711] My first car was a Dodge Charger . The object is:  ({str:"Some text", id:5})

문자열 치환

When passing a string to one of the console object's methods that accepts a string (such as log()), you may use these substitution strings:

치환 문자열 설명
%o 또는 %O Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
%d 또는 %i Outputs an integer. Number formatting is supported, for example console.log("Foo %.2d", 1.1) will output the number as two significant figures with a leading 0: Foo 01
%s Outputs a string.
%f Outputs a floating-point value. Formatting is supported, for example console.log("Foo %.2f", 1.1) will output the number to 2 decimal places: Foo 1.10

참고: Chrome에서는 정밀 서식이 동작하지 않습니다.

Each of these pulls the next argument after the format string off the parameter list. For example:

for (var i=0; i<5; i++) {
  console.log("Hello, %s. You've called me %d times.", "Bob", i+1);
}

다음과 같이 출력된다:

[13:14:13.481] Hello, Bob. You've called me 1 times.
[13:14:13.483] Hello, Bob. You've called me 2 times.
[13:14:13.485] Hello, Bob. You've called me 3 times.
[13:14:13.487] Hello, Bob. You've called me 4 times.
[13:14:13.488] Hello, Bob. You've called me 5 times.

console 출력 꾸미기

You can use the "%c" directive to apply a CSS style to console output:

console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
The test before the directive will not affected, but the text after the directive will be styled using the CSS declarations in the parameter.
 

Note: Quite a few CSS properties are supported by this styling; you should experiment and see which ones provide useful.

콘솔 그룹 사용하기

You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar, but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.

Note: Collapsed groups are not supported yet in Gecko; the groupCollapsed() method is the same as group() at this time.

To exit the current group, simply call console.groupEnd(). For example, given this code:

console.log("This is the outer level");
console.group();
console.log("Level 2");
console.group();
console.log("Level 3");
console.warn("More of level 3");
console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.debug("Back to the outer level");

The output looks like this:

nesting.png

타이머

In order to calculate the duration of a specific operation, Gecko 10 introduced the support of timers in the console object. To start a timer, call the console.time() method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the console.timeEnd() method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.

For example, given this code:

console.time("answer time");
alert("Click to continue");
console.timeEnd("answer time");

will log the time needed by the user to discard the alert box:

timerresult.png

Notice that the timer's name is displayed both when the timer is started and when it's stopped.

Note: It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.

스택 추적

The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call console.trace(). Given code like this:

function foo() {
  function bar() {
    console.trace();
  }
  bar();
}

foo();

The output in the console looks something like this:

명세

Specification Status Comment
Console API Living Standard Initial definition.

브라우저 호환성

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
ConsoleChrome Full support 4Edge Full support YesFirefox Full support 2IE Partial support 8
Notes
Partial support 8
Notes
Notes Only functions when developer tools are opened. Otherwise, the 'console' object is undefined.
Opera Full support 10.1Safari Full support 3.1WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android ? Safari iOS Full support 3.2Samsung Internet Android Full support Yes
assertChrome Full support YesEdge Full support 12Firefox Full support 28IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 28Opera Android ? Safari iOS ? Samsung Internet Android ?
clearChrome Full support YesEdge Full support 12Firefox Full support 48IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 48Opera Android ? Safari iOS ? Samsung Internet Android ?
countChrome Full support YesEdge Full support 12Firefox Full support 30IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 30Opera Android ? Safari iOS ? Samsung Internet Android ?
countResetChrome Full support YesEdge ? Firefox Full support 62IE No support NoOpera Full support YesSafari ? WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 62Opera Android ? Safari iOS ? Samsung Internet Android Full support Yes
debugChrome Full support YesEdge Full support 12Firefox Full support 4IE Full support YesOpera ? Safari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
dir
ExperimentalNon-standard
Chrome Full support YesEdge Full support 12Firefox Full support 8IE Full support 9Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 8Opera Android ? Safari iOS ? Samsung Internet Android ?
dirxml
ExperimentalNon-standard
Chrome Full support YesEdge Full support 12Firefox Full support YesIE Full support YesOpera Full support YesSafari ? WebView Android Full support YesChrome Android Full support YesFirefox Android No support NoOpera Android ? Safari iOS ? Samsung Internet Android ?
errorChrome Full support YesEdge Full support 12Firefox Full support 4IE Full support 8Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
exception (an alias for error)
DeprecatedNon-standard
Chrome No support NoEdge Full support 13Firefox Full support 28IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoFirefox Android Full support 28Opera Android ? Safari iOS No support NoSamsung Internet Android No support No
groupChrome Full support 4Edge Full support 12Firefox Full support 4IE Full support 11Opera Full support YesSafari Full support 4WebView Android Full support 37Chrome Android Full support 18Firefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
groupCollapsedChrome Full support 6Edge Full support 12Firefox Full support 52IE Full support 11Opera ? Safari Full support 5.1WebView Android Full support 37Chrome Android Full support 18Firefox Android Full support 52Opera Android ? Safari iOS ? Samsung Internet Android ?
groupEndChrome Full support 4Edge Full support 12Firefox Full support 9IE Full support 11Opera Full support YesSafari Full support 4WebView Android Full support 37Chrome Android Full support 18Firefox Android Full support 9Opera Android ? Safari iOS ? Samsung Internet Android ?
infoChrome Full support YesEdge Full support 12Firefox Full support 4IE Full support 8Opera Full support YesSafari Full support Yes
Notes
Full support Yes
Notes
Notes No information icon
WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
logChrome Full support YesEdge Full support 12Firefox Full support 4IE Full support 8Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
profile
ExperimentalNon-standard
Chrome Full support 53Edge Full support 12Firefox Full support YesIE Full support YesOpera ? Safari ? WebView Android Full support 53Chrome Android Full support 53Firefox Android Full support 10Opera Android ? Safari iOS ? Samsung Internet Android ?
profileEnd
ExperimentalNon-standard
Chrome Full support YesEdge Full support 12Firefox Full support YesIE Full support YesOpera ? Safari ? WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 10Opera Android ? Safari iOS ? Samsung Internet Android ?
tableChrome Full support YesEdge Full support 13Firefox Full support 34IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 34Opera Android ? Safari iOS ? Samsung Internet Android ?
timeChrome Full support 4Edge Full support 12Firefox Full support 10IE Full support 11Opera Full support YesSafari Full support 4WebView Android Full support 37Chrome Android Full support 18Firefox Android Full support 10Opera Android ? Safari iOS ? Samsung Internet Android ?
timeEndChrome Full support 4Edge Full support 12Firefox Full support 10IE Full support 11Opera Full support YesSafari Full support 4WebView Android Full support 37Chrome Android Full support 18Firefox Android Full support 10Opera Android ? Safari iOS ? Samsung Internet Android ?
timeLogChrome Full support 72Edge No support NoFirefox Full support 62IE No support NoOpera Full support 60Safari No support No
Notes
No support No
Notes
Notes See bug 186833.
WebView Android Full support 72Chrome Android Full support 72Firefox Android Full support 62Opera Android ? Safari iOS No support NoSamsung Internet Android No support No
timestamp
ExperimentalNon-standard
Chrome Full support YesEdge Full support 12Firefox Full support YesIE Full support 11Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 10Opera Android ? Safari iOS ? Samsung Internet Android ?
traceChrome Full support YesEdge Full support 12Firefox Full support 10IE Full support 11Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 10Opera Android ? Safari iOS ? Samsung Internet Android ?
warnChrome Full support YesEdge Full support 12Firefox Full support 4IE Full support 8Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
Available in workersChrome Full support YesEdge Full support YesFirefox Full support 38IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 38Opera Android ? Safari iOS ? Samsung Internet Android ?

Legend

Full support  
Full support
Partial support  
Partial support
No support  
No support
Compatibility unknown  
Compatibility unknown
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.
See implementation notes.
See implementation notes.

참고

  • At least in Firefox, if a page defines a console object, that object overrides the one built into Firefox.
  • Prior to Gecko 12.0, the console object's methods only work when the Web Console is open. Starting with Gecko 12.0, output is cached until the Web Console is opened, then displayed at that time.
  • It's worth noting that the Firefox's built-in console object is compatible with the one provided by Firebug.

같이 보기

다른 구현체