카테고리 없음

스프링 logging

KayEsQuo 2025. 8. 24. 16:55

스프링 MVC 로깅(Log) 정리

1) System.out.println() 대신 로그 쓰는 이유

운영환경에서 System.out.println() 쓰면 관리 어려움 생김.
로그 라이브러리 쓰면 이점 많음: 레벨별 제어(TRACE/DEBUG/INFO/WARN/ERROR), 포맷(시간/클래스/쓰레드) 지정, 파일/네트워크 출력 가능, 성능도 더 좋음(버퍼링/멀티스레드 고려):contentReference[oaicite:0]{index=0}.

2) 스프링 부트 기본 로깅

스프링 부트 스타터 사용 시 spring-boot-starter-logging 자동 포함됨.
인터페이스는 SLF4J, 기본 구현체는 Logback 사용함. 별도 설정 없이 바로 사용 가능함:contentReference[oaicite:1]{index=1}.

3) 로그 선언 방법


// 일반 선언
private static final Logger log = LoggerFactory.getLogger(MyClass.class);

// 롬복 사용 (@Slf4j)
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyClass {
    // log.info(), log.error() 등 바로 사용 가능
}

4) 로그 출력 예시


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class LogTestController {

    @RequestMapping("/log-test")
    public String logTest() {
        String name = "Spring";

        log.trace("trace log={}", name);
        log.debug("debug log={}", name);
        log.info("info log={}", name);
        log.warn("warn log={}", name);
        log.error("error log={}", name);

        return "ok";
    }
}

/log-test 호출하면 설정한 레벨에 따라 출력됨.
개발환경은 보통 DEBUG 이상, 운영환경은 보통 INFO 이상 사용함:contentReference[oaicite:2]{index=2}.

5) 로그 레벨 설정 (application.properties)


# 전체 로그 레벨 (기본 info)
logging.level.root=info

# 특정 패키지 로그 레벨
logging.level.hello.springmvc=debug

6) 올바른 로그 사용법

잘못된 예시 (불필요한 문자열 연산 항상 발생함):


log.debug("data=" + data);

올바른 예시 (필요할 때만 평가됨):


log.debug("data={}", data);

레벨이 INFO 이상이면 DEBUG 로그 미출력 + 불필요 연산도 안 돌림:contentReference[oaicite:3]{index=3}.

7) 로그 장점 요약

  • 시간/클래스/쓰레드 등 부가정보 포함 가능
  • 레벨별 제어로 환경에 맞게 출력 조절 가능
  • 파일/네트워크 등 다양한 출력 대상 지원 (용량/일자 기반 로테이션 가능)
  • 성능 유리함 (버퍼링/멀티스레드 처리):contentReference[oaicite:4]{index=4}

결론 = System.out.println() 대신 로그 무조건 쓰는 게 정답임