실습 코드
https://github.com/Livenow14/slf4j-logback-lab
@Slf4j
로 예외 발생시 로그 추가@Slf4j
@RequiredArgsConstructor
public class BusinessExceptionHandlerFilter extends OncePerRequestFilter {
private static final String LOG_FORMAT = "Error Class : {}, Error Code : {}, Message : {}";
private final ObjectMapper objectMapper;
private final MessageSourceAccessor messageSourceAccessor;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch (BusinessException exception) {
log.info(LOG_FORMAT, exception.getClass(), exception.getErrorCode(), exception.getMessage());
ErrorCode errorCode = exception.getErrorCode();
response.setStatus(errorCode.getStatusCode());
response.setCharacterEncoding("UTF-8");
response.getWriter().println(objectMapper.writeValueAsString(new ErrorResponse(errorCode.getCode(), messageSourceAccessor.getMessage(errorCode.getMessageCode()))));
}
}
}
RollingFileAppender
- 파일에 저장하기 위해 명시<included>
<appender name="FILE-INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>./log/info/info-${BY_DATE}.log</file>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>./backup/info/info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>100MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>3GB</totalSizeCap>
</rollingPolicy>
</appender>
</included>