아직도 console.log만 씀?

김범식·2024년 5월 15일
0
post-thumbnail

javascript를 사용해 개발을 할 때 console.log를 항상 달고 살았습니다. console은 javascript에서 제공하는 내장 객체 중 하나인데 주로 디버깅과 로깅에 사용됩니다. 저는 console.log를 사용해 변수를 출력해보거나 if문이 잘 실행되었는지 메시지를 출력해보는 과정에서 특히 더 많이 사용했습니다.

// 변수명 출력 

let name ="jhon"
console.log(name)
// if문 실행되는지 확인

if(flag){
	console.log("if문으로 들어옴!!")
	// 나머지 코드.. 
}

물론 console 안에는 log보다 훨씬 더 많은 기능이 들어있습니다. 한번쯤 들어봤을 법한 warn, info, error등을 통해 console에 출력되는 메시지의 형태를 변경할 수도 있지만 전혀 사용하지 않았습니다.




javascript를 사용하면서 어떻게 보면 가장 많이 사용한 문법중 하나가 console.log인데 그동안 전혀 활용하지 못하고 있었다는 생각이 들었습니다. 그래서 이번 기회에 console 함수들을 어떻게 사용하는지, 어떤식으로 활용하면 좋을지 알아보고자 합니다. 활용법은 공식문서를 참고했습니다.

📌group()

콘솔에 출력되는 로그를 그룹화 하여 보기 쉽게 만들어 줍니다. group으로 그룹의 시작 지점을 정하고 groupEnd로 로그의 끝을 나타냅니다.

console.group("사용자 정보");

console.log("이름: John");
console.log("나이: 30");
console.log("직업: Developer");

console.groupEnd();

필요한 정보가 그룹화 되어 표시되는 것을 볼 수 있습니다.

물론 겹겹이 사용할 수도 있습니다.

    //바깥쪽
    console.group("outer");
    console.log("outer")

    //안쪽
    console.group("inner");
    console.log("inner")
    console.groupEnd();

    console.groupEnd();




📌groupCollapsed()

group과 동일합니다. 다만 차이점은 console에 축소된 상태로 표시됩니다.

	//groupCollapsed 사용
 		console.groupCollapsed("groupCollapsed : 사용자 정보");

    console.log("이름: John");
    console.log("나이: 30");
    console.log("직업: Developer");

    console.groupEnd();

	//group 사용
    console.group("group : 사용자 정보2");

    console.log("이름: John");
    console.log("나이: 30");
    console.log("직업: Developer");

    console.groupEnd();


console로 출력할 일이 많을 때 groupCollapsed가 더 가시성이 더 좋을것 같습니다.




📌assert()

주어진 조건이 false인 경우에만 메시지를 출력합니다. 이를 사용하여 간단한 조건 확인을 통해 디버깅을 수행할 수 있습니다.

     //assert 사용
    console.group("assert");

    console.assert(false, "false일 때 출력 됩니다.");
    console.assert(true, "true일 때는 출력되지 않습니다.");

    console.groupEnd();

공식문서에 보면 다음과 같이 표시되어있는데 메시지 혹은 객체를 연속으로 넣을 수 있습니다.

assert(assertion)

assert(assertion, obj1)
assert(assertion, obj1, obj2)
assert(assertion, obj1, obj2, /* …, */ objN)

assert(assertion, msg)
assert(assertion, msg, subst1)
assert(assertion, msg, subst1, /* …, */ substN)

이를 활용해서 메시지 말고도 다음과 같이 객체를 출력할 수도 있습니다.

    console.group("assert");
    const userInfo = { name: "홍길동", age: 30 };
    console.assert(userInfo.age > 40, "나이가 40대 이상이 아닙니다.", userInfo);
    console.groupEnd();




📌count()

주로 메서드가 호출된 횟수를 콘솔에 출력할 때 사용됩니다. 주어진 라벨과 함께 호출될 때마다 호출 횟수가 증가합니다. 이벤트나 함수 호출을 추적하고 디버깅할 때 유용합니다.

    console.group("count");
    
    function func() {
      console.count("functions count"); //함수를 실행할 때마다 카운트증가
    }
    func();
    func();
    func();

		//라벨을 지정해 다른 카운트 실행
    console.count("other count");
    console.count("other count");

		//기본 카운트
    console.count()
    console.count()
    console.count()

    console.groupEnd();


라벨을 통해 호출 카운트를 특정지어 사용할 수 있다는 게 특히 유용할 것 같습니다.




📌coutReset()

카운터의 개수를 0으로 초기화 시켜주는 역할을 합니다.

    console.group("countReset");

    function func() {
      console.count("functions count");
    }
    func();
    func();
    func();
    console.countReset("functions count") //카운트 리셋
    func();
    func();

    console.groupEnd();




📌log(), info(), error(), warn()

모두 콘솔에 메시지를 출력하는 데 사용된다는 점에서 log와 크게 다르지 않지만 시각적으로 명확하게 어떤 유형의 메시지 인지를 나타내기 위해 사용됩니다.

    console.group("log, error, info, warn");

    // console.info()를 사용하여 정보성 메시지 출력
    console.info("사용자가 로그인하였습니다.");

    // console.error()를 사용하여 에러 메시지 출력
    const divisor = 0;
    if (divisor === 0) {
      console.error("0으로 나눌 수 없습니다.");
    } else {
      const result = 10 / divisor;
      console.log("결과:", result);
    }

    // console.warn()을 사용하여 경고 메시지 출력
    const age = 15;
    if (age < 18) {
      console.warn("미성년자입니다. 본 사이트 이용이 제한될 수 있습니다.");
    }

    console.groupEnd();




📌table()

배열이나 객체를 테이블 형태로 콘솔에 출력하는데 사용됩니다. 이를 통해 데이터를 시각적으로 표시할 수 있습니다. 저는 복잡한 형태의 object가 아니라면 table로 출력하는게 가시성이 훨씬 좋았습니다.

// 배열사용
   console.group("table");

    const fruits = [
      { name: "Apple", color: "Red", price: 1 },
      { name: "Banana", color: "Yellow", price: 0.5 },
      { name: "Grapes", color: "Purple", price: 2 },
    ];

    console.table(fruits);

    console.groupEnd();


//객체 사용
    console.group("table")

    const fruits = { name: "Apple", color: "Red", price: 1 };
    console.table(fruits);

    console.groupEnd();

객체의 경우 객체 안의 객체 형태로 깊이가 깊어질 경우 약식으로 표시될 수도 있어 복잡한 객체에 사용하는건 별로 좋지 않아보입니다.

  console.group("table");

    const someObbject = {
        data1:{
            data2:{
                data3:"data3"
            }
        }
    }
    console.table(someObbject);




📌time() timeLog() timeEnd()

코드의 시간을 측정하는데 사용됩니다. 일부 코드 블록을 실행되는 데 걸리는 시간을 측정하고 성능 분석 및 최적화에 도움이 됩니다.

    console.group("time");

    // 시간 측정 시작
    console.time("myTimer");

    // 시간이 오래 걸리는 작업 수행
    for (let i = 0; i < 1000000; i++) {
      // 작업
    }

    // 시간 측정 종료 및 결과 출력
    console.timeEnd("myTimer");

    console.groupEnd();

  // 중간에 경과 시간 로깅
    console.time("anotherTimer");
    // 시간이 오래 걸리는 다른 작업 수행
    for (let i = 0; i < 1000000; i++) {
      // 작업
    }
    console.timeLog("anotherTimer", "50만 번째 반복 완료"); // 중간에 경과 시간 로깅
    console.timeEnd("anotherTimer");

    console.groupEnd();

fetch를 사용해 api통신을 할 때도 얼마나 걸리는지 측정할 수 있습니다.

    console.time("fetching");
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((data) => console.timeLog("fetching", "성공!", data))
      .catch((error) => console.timeLog("fetching", "실패!", error))
      .finally(() => timeEnd("fetching"));
    console.groupEnd();




📌dir

자바스크립트에서 객체를 출력할 때 사용하는 콘솔 메서드 중 하나입니다. 이 메서드는 객체의 속성과 속성 값을 나열하여 출력합니다. 주로 객체의 구조를 파악할 때 사용합니다.

예시로 console.log와 console.dir의 차이점을 살펴봅시다.

// html 태그 
<div>박스</div>

// dir과 log 사용
console.group("dir");
const div = document.querySelector("div")
console.log(div)
console.dir(div)
console.groupEnd();

log는 단순히 태그만 출력되는 반면, dir은 div안의 속상까지 출력해 주고 있습니다. 이현상은 객체를 출력할 때도 똑같이 발생합니다.

// 객체 출력
    console.group("dir");
    const person = {
      name: "John",
      age: 30,
      address: {
        city: "New York",
        zip: "10001",
      },
    };
    console.log(person);
    console.dir(person);
    console.groupEnd();


객체를 속성들을 트리구조로 표시하다보니 log보다 객체를 명확하게 살펴볼 수 있다는 장점이 있습니다. 또한 객체가 복잡한 경우에도 객체의 중첩된 속성을 쉽게 확인할 수 있습니다.




📌trace()

trace를 호출하면 호출 스택의 각 단계에서 함수의 이름과 위치가 표시됩니다. 이를 통해 코의 흐름을 추적하고, 함수가 어디서 호출되었는지를 파악할 수 있습니다.

console.group("trace")
    function innerFunction() {
  console.trace("Trace from innerFunction:");
}

function middleFunction() {
  innerFunction();
}

function outerFunction() {
  middleFunction();
}

outerFunction();
console.groupEnd()


함수의 실행순서를 스택 순서로 보여주는것을 알 수 있습니다.




느낀점

그동안 console.log를 사용하면서 알게 모르게 느꼈던 불편점들이 있었는데 이부분을 시원하게 긁어주는 기능이 진작에 구현되어 있었다는걸 깨달았습니다. 특히 성능적인 면을 측정할 때 time을 유용하게 사용할 수 있을거 같아서 벌써부터 기대되네요!

profile
frontend developer

0개의 댓글