Spring boot Logging system
Logback framework 사용
로깅 레벨
1.TRACE 2.DEBUG 3.INFO 4.WARN 5.ERROR
로그 레벨 설정
# spring framework logging
logging.level.org.springframework = ERROR
# local application logging
logging.level.com.acomp.hello = INFO
Logger 사용
package com.somebiz.restapp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// other imports
@RestController
public class HomeController{
private static final Logger logger =
LoggerFactory.getLogger(HomeController.class);
@GetMapping("/")
public Map<String, Object> test(){
Map<String, Object> map = new HashMap<>();
map.put("result","Aloha");
logger.trace("{test} trace");
logger.debug("{test} debug");
logger.info("{test} info");
logger.warn("{test} warn");
logger.error("{test} error");
return map;
}
}
REST 어플리케이션 예외처리
@ControllerAdvice - 전역처리
@RestController는 컨트롤러
@ExceptionHandler 어노테이션을 사용하여 예외를 처리할 클래스를 정의
@ControllerAdvice
@RestController
public class GlobalExceptionHandler{
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = BaseException.class)
public String handleBaseException(BaseException e){
return e.getMessage();
}
@ExceptionHandler(value = Exception.class)
public String handleBaseException(Exception e){
return e.getMessage();
}
}
GlobalExceptionHandler v2
@ControllerAdvice
@RestController
public class GlobalExceptionHandler{
@ExceptionHandler(value = ArithmeticException.class)
public Map<String, String> handleArithMaticException(ArithmeticException e){
Map<String, String> res = new HashMap<>();
res.put("errorMsg", e.getMessage());
res.put("status", "error");
return res;
}
@ExceptionHandler(value = Exception.class)
public Map<String, String> handleException(Exception e){
Map<String, String> res = new HashMap<>();
res.put("errorMsg", e.getMessage());
res.put("status", "error");
return res;
}
}
@ExceptionHandler 를 사용한 컨트롤러 단 예외처리
@ExceptionHandler(value = NumberFormatException.class)
public String nfeHandler(NumberFormatException e){
return e.getMessage();
}
비지니스 예외 예제
public class ClientException extends RuntimeException{
private final int errorCode;
private final String errorDescription;
public ClientException(ApiError error){
super(error.getErrorCode() + ": "+ error.getDescription());
this.errorCode = error.getErrorCode();
this.errorDescription = error.getDescription();
}
public int getErrorCode(){
return errorCode;
}
public String getErrorDescription(){
return errorDescription;
}
}