[Spring] println이 아닌 Logger을 통해 logging을 출력하는 이유

민지·2024년 1월 20일

Spring

목록 보기
4/6

Understanding logging

  • 스프링부트에서는 application.properties에서 로깅을 설정할 수 있다.

  • 로깅 레벨
    - debug레벨에서 로깅하면, 많은 정보를 출력하는 과정에서 성능에 영향을 끼칠 수 있다.

    • 그래서 프로덕션 중 어플리케이션을 실행할 때는 info레벨 추천
    • 정보가 적은 -> 많은 순서대로의 로깅 레벨
      1. ERROR
      2. WARN
      3. INFO
      4. DEBUG
      5. TRACE
  • 로깅 방법
    - logging.level.[패키지경로] = [로깅레벨]

    logging.level.org.springframework = info
     logging.level.com.firstWebApplication.springboot.myfirstWebapp = info
    

    - 순서대로 info레벨로 org.springframework에 대한 로깅과 루트 패키지에 대한 로깅이다.

참고로, 보통 개발 서버는 debug, 운영 서버는 info를 사용한다.

로깅을 프린트하는 방법 - Logger (import slf4j)

Logger 예제코드

package com.firstWebApplication.springboot.myfirstWebapp.login;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController {
	private Logger logger = LoggerFactory.getLogger(getClass()); // Logger 초기화

	@RequestMapping("/login")
	public String login(@RequestParam String name, @RequestParam Character gender, @RequestParam int age,
			ModelMap model) {

		model.put("name", name);
		logger.debug("debug : Request param is {}", name); // debug 레벨에서 로깅
		model.put("gender", gender);
		model.put("age", age);

		return "login";
	}
}
  • logger.debug(String msg) 정의

  • logger.debug(String format, Object arg) 정의
    Log a message at the DEBUG level according to the specified format and argument.

    This form avoids superfluous object creation when the logger is disabled for the DEBUG level.
    
    Parameters:
    format : the format string
    arg : the argument

해당 메서드는 로깅 레벨에 따라 메서드명이 달라질 뿐, 파라미터는 비슷하다.

실행결과 -> 맨 마지막 로그메세지를 보면 잘 출력된 것을 확인할 수 있었다.

추가 코드 - 다양한 레벨에서의 로깅

@Controller
public class LoginController {
	private Logger logger = LoggerFactory.getLogger(getClass()); // Logger 초기화

	@RequestMapping("/login")
	public String login(@RequestParam String name, @RequestParam Character gender, @RequestParam int age,
			ModelMap model) {

		model.put("name", name);
		logger.debug("debug : Request param is {}", name);
		logger.info("I want this printed at info level");
		logger.warn("I want this printed at warn level");
		model.put("gender", gender);
		model.put("age", age);

		return "login";
	}
}

실행결과는 다음과 같다.
c.f.s.m.login.LoginController : debug : Request param is John
c.f.s.m.login.LoginController : I want this printed at info level
c.f.s.m.login.LoginController : I want this printed at warn level

System.out.println()을 사용하지 않고, logging을 사용하는 이유

그렇다면 왜 굳이 println문으로 찍으면 편할 것을 굳이 logger을 초기화해 해당 logger클래스의 메서드를 사용할까? 그 이유는 logging을 사용할 때의 다양한 장점들이 존재하기 때문이다.

  1. 스레드 정보, 클래스 이름 같은 부가 정보를 함께 볼 수 있고, 출력 모양을 조정할 수 있다.
  2. 로그 레벨에 따라 개발서버에서는 모든 로그를 출력하고, 운영서버에서는 출력하지 않는 등 로그를 상황별로 맞게 조절할 수 있다.
  3. System out console에만 출력하는 것이 아니라, 파일이나 네트워크 등, 로그를 별도의 위치에 남길 수 있다.
  4. 특히 파일로 남길 때에는, 일별, 특정 용량에 따라 로그를 분할하는 것 또한 가능하다.
  5. println을 썼을 때보다 내부 버퍼링, 멀티 스레드 등의 환경에서 훨씬 좋다.
profile
배운 내용을 바로바로 기록하자!

0개의 댓글