From 3b2458d6cdd1505d01bd5c706dce47be7910d829 Mon Sep 17 00:00:00 2001 From: limju Date: Fri, 8 Sep 2023 18:51:44 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20log=20trace=20=EA=B8=B0=EB=8A=A5=20?= =?UTF-8?q?=EC=97=85=EB=8D=B0=EC=9D=B4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kr/xit/core/aop/TraceLoggerAspect.java | 89 ++++++++- .../spring/config/SpringDocsApiConfig.java | 7 +- .../xit/core/spring/config/WebMvcConfig.java | 187 ------------------ .../main/resources/config/application-app.yml | 31 +-- .../main/resources/config/application-dev.yml | 23 ++- .../resources/config/application-local.yml | 25 ++- .../resources/config/application-prod.yml | 21 +- .../kr/xit/core/aop/TraceLoggerAspect.java | 6 +- .../core/spring/config/SpringDocsConfig.java | 4 +- .../xit/core/spring/config/WebMvcConfig.java | 89 ++++----- .../spring/filter/ReadableRequestWrapper.java | 2 +- .../filter/ReadableRequestWrapperFilter.java | 2 +- 12 files changed, 200 insertions(+), 286 deletions(-) delete mode 100644 mens-api/src/main/java/kr/xit/core/spring/config/WebMvcConfig.java rename {mens-batch => mens-core}/src/main/java/kr/xit/core/spring/config/WebMvcConfig.java (91%) diff --git a/mens-api/src/main/java/kr/xit/core/aop/TraceLoggerAspect.java b/mens-api/src/main/java/kr/xit/core/aop/TraceLoggerAspect.java index 5809b25..4423ec6 100644 --- a/mens-api/src/main/java/kr/xit/core/aop/TraceLoggerAspect.java +++ b/mens-api/src/main/java/kr/xit/core/aop/TraceLoggerAspect.java @@ -1,6 +1,8 @@ package kr.xit.core.aop; import java.util.Arrays; +import java.util.Enumeration; +import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -9,13 +11,17 @@ import java.util.concurrent.Future; import javax.servlet.http.HttpServletRequest; +import kr.xit.core.support.utils.LogUtils; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; +import org.json.simple.JSONObject; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; @@ -69,8 +75,17 @@ public class TraceLoggerAspect { @Value("${app.slack-webhook.enabled:false}") private boolean isSlackEnabled; - @Value("#{'${app.mdc.log.trace.uris}'.split(',')}") - private String[] uris; + @Value("${app.log.request.custom-enabled:false}") + private boolean isReqLogEnabled; + + @Value("${app.log.response-enabled:false}") + private boolean isResLogEnabled; + + @Value("${app.log.mdc.enabled:false}") + private boolean isMdcLogEnabled; + + @Value("#{'${app.log.mdc.exclude-patterns}'.split(',')}") + private String[] excludes; private final ILoggingService loggingService; private final SlackWebhookPush slackWebhookPush; @@ -83,12 +98,31 @@ public class TraceLoggerAspect { this.slackWebhookPush = slackWebhookPush; } + @Pointcut("execution(public * egovframework..web.*.*(..)) || execution(public * kr.xit..web.*.*(..))") + public void requestPointCut() { + } + @Pointcut("execution(public * egovframework..*.*(..)) || execution(public * kr.xit..*.*(..))") public void errorPointCut() { } + @Pointcut("execution(public * egovframework..web.*.*(..)) || execution(public * kr.xit..web.*.*(..))") + public void resultPointCut() { + } + + @Before(value = "requestPointCut()") + public void logBefore(JoinPoint joinPoint) { + if(!isReqLogEnabled) return; + ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes != null? attributes.getRequest(): null; + requestLog(request, getParams(request)); + log.info("Before: " + joinPoint.getSignature().getName()); + } + @Around(value = "@annotation(kr.xit.core.spring.annotation.TraceLogging)") public Object serviceTraceLogging(final ProceedingJoinPoint pjp) throws Throwable { + if(!isMdcLogEnabled) return pjp.proceed(); + ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes != null? attributes.getRequest(): null; @@ -108,14 +142,22 @@ public class TraceLoggerAspect { return result; } + @AfterReturning(pointcut = "resultPointCut()", returning = "result") + public void logAfterReturning(final JoinPoint jp, final Object result) { + if(isResLogEnabled) { + log.info("{}{}{}", + "\n//============================= Http Response ==============================", + LogUtils.toString(result), + "\n=========================================================================//" + ); + } + } - //@AfterThrowing(value = "@annotation(kr.xit.core.spring.annotation.TraceLogging)", throwing = "error") @AfterThrowing(value = "errorPointCut()", throwing="error") public void afterThrowingProceed(final JoinPoint jp, final Throwable error) { traceLoggingError(jp, error); } - /** * 배치 실행시 여기에서 set한 MDC 값이 batch 모듈에서 reading이 불가하여, 배치 tasklet에서 set한 trace_id로 set * @param params @@ -124,7 +166,7 @@ public class TraceLoggerAspect { protected void traceLogging(final String params, final HttpServletRequest request) { if(request != null) { String uri = request.getRequestURI().toString(); - if(Arrays.asList(uris).stream().anyMatch(regx -> uri.matches(regx))) return; + if(Arrays.asList(excludes).stream().anyMatch(regx -> uri.matches(regx))) return; MDC.put(REQUEST_TRACE_ID, StringUtils.defaultString(MDC.get("request_trace_batch_id"), UUID.randomUUID().toString().replaceAll("/-/g", ""))); @@ -257,4 +299,41 @@ log.info("@@@@@@@@@@@@@@@@@로깅 start : [\n{}\n]",MDC.getCopyOfContextMap()); //if(RequestContextHolder.getRequestAttributes() != null) MDC.clear(); } + + + private void requestLog(HttpServletRequest request, JSONObject params) { + + if (log.isDebugEnabled()) { + Map map = new LinkedHashMap<>(); + //sb.append("Ajax Call : " + "XMLHttpRequest".equals(request.getHeader(Globals.AJAX_HEADER))).append("\n"); + map.put("URI", request.getRequestURI()); + map.put("URL", request.getRequestURL()); + map.put("IP", request.getRemoteAddr()); + map.put("Referer URI", request.getHeader("referer")); + map.put("Method", request.getMethod()); + map.put("User Agent", request.getHeader("User-Agent")); + map.put("Session", request.getSession().getId()); + map.put("Locale", request.getLocale().getCountry()); + map.put("ContentType", request.getContentType()); + map.put("Parameters", params); + + log.info("{}{}{}", + "\n//============================= Http Request ==============================", + LogUtils.toString(map), + "\n=========================================================================//" + ); + map.clear(); + } + } + + private JSONObject getParams(HttpServletRequest request) { + JSONObject jsonObject = new JSONObject(); + Enumeration params = request.getParameterNames(); + while (params.hasMoreElements()) { + String param = params.nextElement(); + String replaceParam = param.replaceAll("\\.", "-"); + jsonObject.put(replaceParam, request.getParameter(param)); + } + return jsonObject; + } } diff --git a/mens-api/src/main/java/kr/xit/core/spring/config/SpringDocsApiConfig.java b/mens-api/src/main/java/kr/xit/core/spring/config/SpringDocsApiConfig.java index adec7d6..30fefad 100644 --- a/mens-api/src/main/java/kr/xit/core/spring/config/SpringDocsApiConfig.java +++ b/mens-api/src/main/java/kr/xit/core/spring/config/SpringDocsApiConfig.java @@ -39,8 +39,7 @@ public class SpringDocsApiConfig { return GroupedOpenApi.builder() .group("2. 카카오페이 MyDoc API") .pathsToMatch( - "/api/kakaopay/v1/**", - "/api/kakaopay/v2/**" + "/api/kakaopay/**" ) .build(); } @@ -50,7 +49,7 @@ public class SpringDocsApiConfig { return GroupedOpenApi.builder() .group("3. Nice CI API") .pathsToMatch( - "/api/nice/v1/**" + "/api/nice/**" ) .build(); } @@ -60,7 +59,7 @@ public class SpringDocsApiConfig { return GroupedOpenApi.builder() .group("6. 전자고지 문서 확인 API") .pathsToMatch( - "/api/ens/v1/**" + "/api/ens/**" ) .build(); } diff --git a/mens-api/src/main/java/kr/xit/core/spring/config/WebMvcConfig.java b/mens-api/src/main/java/kr/xit/core/spring/config/WebMvcConfig.java deleted file mode 100644 index a143580..0000000 --- a/mens-api/src/main/java/kr/xit/core/spring/config/WebMvcConfig.java +++ /dev/null @@ -1,187 +0,0 @@ -package kr.xit.core.spring.config; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.DispatcherType; -import javax.servlet.Filter; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.Ordered; -import org.springframework.web.filter.CommonsRequestLoggingFilter; -import org.springframework.web.method.support.HandlerMethodArgumentResolver; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -import kr.xit.core.consts.Constants; -import kr.xit.core.spring.config.auth.AuthentificationInterceptor; -import kr.xit.core.spring.config.properties.CorsProperties; -import kr.xit.core.spring.filter.LoggingFilter; -import kr.xit.core.spring.filter.ReadableRequestWrapperFilter; -import kr.xit.core.spring.resolver.CustomArgumentResolver; -import kr.xit.core.spring.resolver.PageableArgumentResolver; -import lombok.RequiredArgsConstructor; - -/** - *
- * description : Spring MVC 설정
- *               - filter, interceptor
- *               - AuthentificationInterceptor : 인증처리
- *               - CommonsRequestLoggingFilter : request logging
- *               - ReadableRequestWrapperFilter : post logging 처리를 위한 필터
- *               - CORS
- * packageName : kr.xit.core.spring.config
- * fileName    : WebMvcConfig
- * author      : julim
- * date        : 2023-04-28
- * ======================================================================
- * 변경일         변경자        변경 내용
- * ----------------------------------------------------------------------
- * 2023-04-28    julim       최초 생성
- *
- * 
- * @see AuthentificationInterceptor - * @see CommonsRequestLoggingFilter - * @see ReadableRequestWrapperFilter - * @see LoggingFilter - */ -@RequiredArgsConstructor -@Configuration -@EnableWebMvc -public class WebMvcConfig implements WebMvcConfigurer { - /** - * logging exclude path - */ - @Value("${app.param.log.exclude-patterns}") - private List EXCLUDE_URL_REGEXS; - - private final CorsProperties corsProperties; - - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(new AuthentificationInterceptor()) - .addPathPatterns("/**/*") - .excludePathPatterns( - "/api/core/*" - ); - } - - // ------------------------------------------------------------- - // RequestMappingHandlerMapping 설정 View Controller 추가 - // ------------------------------------------------------------- - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/cmmn/validator.do") - .setViewName("cmmn/validator"); - registry.addViewController("/").setViewName("forward:/index.html"); - } - - //TODO :: ArgumentResolver add - @Override - public void addArgumentResolvers(List resolvers) { - resolvers.add(new CustomArgumentResolver()); - resolvers.add(new PageableArgumentResolver()); - } - - /** - * CommonsRequestLoggingFiler 등록 - * app.param.log.enabled: true시 로그 출력 - * @return - */ - @ConditionalOnProperty(value = "app.param.log.enabled", havingValue = "true", matchIfMissing = false) - @Bean - public FilterRegistrationBean requestLoggingFilter() { - CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter(){ - @Override - protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException { - String path = request.getServletPath(); - return EXCLUDE_URL_REGEXS.stream().anyMatch(regex -> path.matches(regex)); - } - }; - loggingFilter.setIncludeClientInfo(true); - loggingFilter.setIncludeHeaders(false); - loggingFilter.setBeforeMessagePrefix("\n//========================== Request(Before) ================================\n"); - loggingFilter.setBeforeMessageSuffix("\n//==========================================================================="); - - loggingFilter.setIncludeQueryString(true); - loggingFilter.setIncludePayload(true); - loggingFilter.setMaxPayloadLength(1024* 1024); - loggingFilter.setAfterMessagePrefix("\n//=========================== Request(After) ================================\n"); - loggingFilter.setAfterMessageSuffix("\n//==========================================================================="); - - FilterRegistrationBean bean = new FilterRegistrationBean<>(loggingFilter); - bean.setOrder(Ordered.HIGHEST_PRECEDENCE); - bean.addUrlPatterns(Constants.API_URL_PATTERNS); - return bean; - } - - /** - * exclude pattern 지정 - * @return FilterRegistrationBean - */ - @ConditionalOnProperty(value = "app.param.log.custom.enabled", havingValue = "true", matchIfMissing = false) - @Bean - public FilterRegistrationBean loggingFilter() { - Map initMap = new HashMap<>(); - initMap.put("excludedUrls", StringUtils.join(EXCLUDE_URL_REGEXS,",")); - - FilterRegistrationBean frb = new FilterRegistrationBean<>(new LoggingFilter()); - frb.setOrder(1); - frb.addUrlPatterns(Constants.API_URL_PATTERNS); - frb.setInitParameters(initMap); - frb.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC); - - return frb; - } - - /** - * Post 요청시 request(stream) logging 처리를 위한 필터 - * @return - */ - @ConditionalOnProperty(value = "app.param.log.custom.enabled", havingValue = "true", matchIfMissing = false) - @Bean - public FilterRegistrationBean readableRequestWrapperFilter() { - ReadableRequestWrapperFilter readableRequestWrapperFilter = new ReadableRequestWrapperFilter(); - - FilterRegistrationBean bean = new FilterRegistrationBean(readableRequestWrapperFilter); - bean.setOrder(Ordered.HIGHEST_PRECEDENCE); - bean.addUrlPatterns(Constants.API_URL_PATTERNS); - return bean; - } - - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/api/**") - .allowedOrigins(corsProperties.getAllowedOrigins().split(",")) - .allowedMethods(corsProperties.getAllowedMethods().split(",")) - .allowedHeaders(corsProperties.getAllowedHeaders().split(",")) - .allowCredentials(corsProperties.getAllowCredentials()) - .maxAge(corsProperties.getMaxAge()) - .exposedHeaders(corsProperties.getExposeHeader()); - } - - -// /** -// * HandlerExceptionResolver 를 상속받은 resolver 등록 -// * @param resolvers the list of configured resolvers to extend -// */ -// @Override -// public void extendHandlerExceptionResolvers(List resolvers) { -// HandlerExceptionResolver exceptionHandlerExceptionResolver = resolvers.stream().filter(x -> x instanceof ExceptionHandlerExceptionResolver).findAny().get(); -// int index = resolvers.indexOf(exceptionHandlerExceptionResolver); -// resolvers.add(index, new CustomRuntimeResolver()); -// WebMvcConfigurer.super.extendHandlerExceptionResolvers(resolvers); -// } - -} diff --git a/mens-api/src/main/resources/config/application-app.yml b/mens-api/src/main/resources/config/application-app.yml index a9d577f..498dad3 100644 --- a/mens-api/src/main/resources/config/application-app.yml +++ b/mens-api/src/main/resources/config/application-app.yml @@ -3,21 +3,28 @@ #----------------------------------------------------------------------- app: - # request log - param: - log: + #--------------------------------------------------------------- + # log 설정 + # request: + # custom-enabled | common-enabled | filter-enabled 중 1개만 활성화 + # --> 운영: common-enabled, 개발: custom-enabled 사용 권장 + # response-enabled : 호출 결과 출력 - 운영시 false + # mdc : api 호출(서비스) 로그 기록 + # uris : api 호출 로그 제외 패턴 + #--------------------------------------------------------------- + log: + request: # exclude pattern : CommonsRequestLoggingFilter && LoggingFilter 적용 exclude-patterns: '/swagger-ui/(.*), /api-docs/(.*)' + custom-enabled: false # CommonsRequestLoggingFilter 사용 parameter 로그 출력 - enabled: true - # parameter custom 로그 출력(LoggerAspect) - custom.enabled: false - # MDC logging trace 활성 - mdc: - log: - trace: - enabled: false - uris: '/api/kakao/(.*), /api/v1/ens/sendBulks(.*)' + common-enabled: false + # Filter를 사용한 로그 출력 + filter-enabled: false + response-enabled: false + mdc: + enabled: false + exclude-patterns: '/api/kakao/(.*), /api/v1/ens/sendBulks(.*)' # slack slack-webhook: diff --git a/mens-api/src/main/resources/config/application-dev.yml b/mens-api/src/main/resources/config/application-dev.yml index 4a85994..d472b07 100644 --- a/mens-api/src/main/resources/config/application-dev.yml +++ b/mens-api/src/main/resources/config/application-dev.yml @@ -51,14 +51,23 @@ app: data: root: path: /data - param: - log: - # CommonsRequestLoggingFilter 사용 parameter 로그 출력 + + #--------------------------------------------------------------- + # log 설정 + # request: + # custom-enabled | common-enabled | filter-enabled 중 1개만 활성화 + # --> 운영: common-enabled, 개발: custom-enabled 사용 권장 + # response-enabled : 호출 결과 출력 - 운영시 false + # mdc : api 호출(서비스) 로그 기록 + # uris : api 호출 로그 제외 패턴 + #--------------------------------------------------------------- + log: + request: + custom-enabled: true + response-enabled: true + # MDC logging trace 활성 + mdc: enabled: true - # parameter custom 로그 출력(LoggerAspect) - custom.enabled: true - # MDC logging trace 활성 - mdc.log.trace.enabled: true # slack slack-webhook: diff --git a/mens-api/src/main/resources/config/application-local.yml b/mens-api/src/main/resources/config/application-local.yml index 7fcc0d2..6204027 100644 --- a/mens-api/src/main/resources/config/application-local.yml +++ b/mens-api/src/main/resources/config/application-local.yml @@ -73,14 +73,23 @@ app: data: root: path: D:/data - param: - log: - # CommonsRequestLoggingFilter 사용 parameter 로그 출력 - enabled: true - # parameter custom 로그 출력(LoggerAspect) - custom.enabled: true - # MDC logging trace 활성 - mdc.log.trace.enabled: true + + #--------------------------------------------------------------- + # log 설정 + # request: + # custom-enabled | common-enabled | filter-enabled 중 1개만 활성화 + # --> 운영: common-enabled, 개발: custom-enabled 사용 권장 + # response-enabled : 호출 결과 출력 - 운영시 false + # mdc : api 호출(서비스) 로그 기록 + # uris : api 호출 로그 제외 패턴 + #--------------------------------------------------------------- + log: + request: + custom-enabled: true + response-enabled: true + # MDC logging trace 활성 + mdc: + enabled: false # slack slack-webhook: diff --git a/mens-api/src/main/resources/config/application-prod.yml b/mens-api/src/main/resources/config/application-prod.yml index 747877a..2579191 100644 --- a/mens-api/src/main/resources/config/application-prod.yml +++ b/mens-api/src/main/resources/config/application-prod.yml @@ -77,14 +77,21 @@ app: data: root: path: d:/data - param: - log: - # CommonsRequestLoggingFilter 사용 parameter 로그 출력 + #--------------------------------------------------------------- + # log 설정 + # request: + # custom-enabled | common-enabled | filter-enabled 중 1개만 활성화 + # --> 운영: common-enabled, 개발: custom-enabled 사용 권장 + # response-enabled : 호출 결과 출력 - 운영시 false + # mdc : api 호출(서비스) 로그 기록 + # uris : api 호출 로그 제외 패턴 + #--------------------------------------------------------------- + log: + request: + common-enabled: true + # MDC logging trace 활성 + mdc: enabled: true - # parameter custom 로그 출력(LoggerAspect) - custom.enabled: true - # MDC logging trace 활성 - mdc.log.trace.enabled: true # slack slack-webhook: diff --git a/mens-batch/src/main/java/kr/xit/core/aop/TraceLoggerAspect.java b/mens-batch/src/main/java/kr/xit/core/aop/TraceLoggerAspect.java index 5809b25..fcc9c33 100644 --- a/mens-batch/src/main/java/kr/xit/core/aop/TraceLoggerAspect.java +++ b/mens-batch/src/main/java/kr/xit/core/aop/TraceLoggerAspect.java @@ -69,8 +69,8 @@ public class TraceLoggerAspect { @Value("${app.slack-webhook.enabled:false}") private boolean isSlackEnabled; - @Value("#{'${app.mdc.log.trace.uris}'.split(',')}") - private String[] uris; + @Value("#{'${app.log.mdc.exclude-patterns}'.split(',')}") + private String[] excludes; private final ILoggingService loggingService; private final SlackWebhookPush slackWebhookPush; @@ -124,7 +124,7 @@ public class TraceLoggerAspect { protected void traceLogging(final String params, final HttpServletRequest request) { if(request != null) { String uri = request.getRequestURI().toString(); - if(Arrays.asList(uris).stream().anyMatch(regx -> uri.matches(regx))) return; + if(Arrays.asList(excludes).stream().anyMatch(regx -> uri.matches(regx))) return; MDC.put(REQUEST_TRACE_ID, StringUtils.defaultString(MDC.get("request_trace_batch_id"), UUID.randomUUID().toString().replaceAll("/-/g", ""))); diff --git a/mens-core/src/main/java/kr/xit/core/spring/config/SpringDocsConfig.java b/mens-core/src/main/java/kr/xit/core/spring/config/SpringDocsConfig.java index ab11ec5..3635fc3 100644 --- a/mens-core/src/main/java/kr/xit/core/spring/config/SpringDocsConfig.java +++ b/mens-core/src/main/java/kr/xit/core/spring/config/SpringDocsConfig.java @@ -50,8 +50,8 @@ public class SpringDocsConfig { .description("잘못된 부분이나 오류 발생 시 바로 말씀해주세요.") // 문서 설명 .contact(new Contact() // 연락처 .name("관리자") - .email("admin@xit.co.kr") - .url("http://www.xerotech.co.kr/")); + .email("admin@xit.co.kr")); + //.url("http://www.xerotech.co.kr/")); List servers = Collections.singletonList(new Server().url(url).description(name + "(" + active + ")")); diff --git a/mens-batch/src/main/java/kr/xit/core/spring/config/WebMvcConfig.java b/mens-core/src/main/java/kr/xit/core/spring/config/WebMvcConfig.java similarity index 91% rename from mens-batch/src/main/java/kr/xit/core/spring/config/WebMvcConfig.java rename to mens-core/src/main/java/kr/xit/core/spring/config/WebMvcConfig.java index 8fc851a..ab60ef3 100644 --- a/mens-batch/src/main/java/kr/xit/core/spring/config/WebMvcConfig.java +++ b/mens-core/src/main/java/kr/xit/core/spring/config/WebMvcConfig.java @@ -3,12 +3,18 @@ package kr.xit.core.spring.config; import java.util.HashMap; import java.util.List; import java.util.Map; - import javax.servlet.DispatcherType; import javax.servlet.Filter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; - +import kr.xit.core.consts.Constants; +import kr.xit.core.spring.config.auth.AuthentificationInterceptor; +import kr.xit.core.spring.config.properties.CorsProperties; +import kr.xit.core.spring.filter.LoggingFilter; +import kr.xit.core.spring.filter.ReadableRequestWrapperFilter; +import kr.xit.core.spring.resolver.CustomArgumentResolver; +import kr.xit.core.spring.resolver.PageableArgumentResolver; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -19,20 +25,11 @@ import org.springframework.core.Ordered; import org.springframework.web.filter.CommonsRequestLoggingFilter; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import kr.xit.core.consts.Constants; -import kr.xit.core.spring.config.auth.AuthentificationInterceptor; -import kr.xit.core.spring.config.properties.CorsProperties; -import kr.xit.core.spring.filter.LoggingFilter; -import kr.xit.core.spring.filter.ReadableRequestWrapperFilter; -import kr.xit.core.spring.filter.SimpleCORSFilter; -import kr.xit.core.spring.resolver.CustomArgumentResolver; -import kr.xit.core.spring.resolver.PageableArgumentResolver; -import lombok.RequiredArgsConstructor; - /** *
  * description : Spring MVC 설정
@@ -54,16 +51,16 @@ import lombok.RequiredArgsConstructor;
  * @see AuthentificationInterceptor
  * @see CommonsRequestLoggingFilter
  * @see ReadableRequestWrapperFilter
- * @see SimpleCORSFilter
  * @see LoggingFilter
  */
 @RequiredArgsConstructor
 @Configuration
+@EnableWebMvc
 public class WebMvcConfig implements WebMvcConfigurer {
     /**
      * logging exclude path
      */
-    @Value("${app.param.log.exclude-patterns}")
+    @Value("${app.log.request.exclude-patterns}")
     private List EXCLUDE_URL_REGEXS;
 
     private final CorsProperties corsProperties;
@@ -87,12 +84,29 @@ public class WebMvcConfig implements WebMvcConfigurer {
         registry.addViewController("/").setViewName("forward:/index.html");
     }
 
-    //TODO :: ArgumentResolver add
     @Override
-    public void addArgumentResolvers(List resolvers) {
-        resolvers.add(new CustomArgumentResolver());
-        resolvers.add(new PageableArgumentResolver());
-        //WebMvcConfigurer.super.addArgumentResolvers(resolvers);
+    public void addCorsMappings(CorsRegistry registry) {
+        registry.addMapping("/api/**")
+            .allowedOrigins(corsProperties.getAllowedOrigins().split(","))
+            .allowedMethods(corsProperties.getAllowedMethods().split(","))
+            .allowedHeaders(corsProperties.getAllowedHeaders().split(","))
+            .allowCredentials(corsProperties.getAllowCredentials())
+            .maxAge(corsProperties.getMaxAge())
+            .exposedHeaders(corsProperties.getExposeHeader());
+    }
+
+    /**
+     * Post 요청시 request(stream) logging 처리를 위한 필터
+     * @return
+     */
+    @Bean
+    public FilterRegistrationBean readableRequestWrapperFilter() {
+        ReadableRequestWrapperFilter readableRequestWrapperFilter = new ReadableRequestWrapperFilter();
+
+        FilterRegistrationBean bean = new FilterRegistrationBean(readableRequestWrapperFilter);
+        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
+        bean.addUrlPatterns(Constants.API_URL_PATTERNS);
+        return bean;
     }
 
     /**
@@ -100,7 +114,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
      * app.param.log.enabled: true시 로그 출력
      * @return
      */
-    @ConditionalOnProperty(value = "app.param.log.enabled", havingValue = "true", matchIfMissing = false)
+    @ConditionalOnProperty(value = "app.log.request.common-enabled", havingValue = "true", matchIfMissing = false)
     @Bean
     public FilterRegistrationBean requestLoggingFilter() {
         CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter(){
@@ -128,10 +142,10 @@ public class WebMvcConfig implements WebMvcConfigurer {
     }
 
     /**
-     * exclude pattern 지정
+     * Logging Filter 지정
      * @return FilterRegistrationBean
      */
-    @ConditionalOnProperty(value = "app.param.log.custom.enabled", havingValue = "true", matchIfMissing = false)
+    @ConditionalOnProperty(value = "app.log.request.filter-enabled", havingValue = "true", matchIfMissing = false)
     @Bean
     public FilterRegistrationBean loggingFilter() {
         Map initMap = new HashMap<>();
@@ -146,34 +160,11 @@ public class WebMvcConfig implements WebMvcConfigurer {
         return frb;
     }
 
-    /**
-     * Post 요청시 request(stream) logging 처리를 위한 필터
-     * @return
-     */
-    @ConditionalOnProperty(value = "app.param.log.custom.enabled", havingValue = "true", matchIfMissing = false)
-    @Bean
-    public FilterRegistrationBean readableRequestWrapperFilter() {
-        ReadableRequestWrapperFilter readableRequestWrapperFilter = new ReadableRequestWrapperFilter();
-
-        FilterRegistrationBean bean = new FilterRegistrationBean(readableRequestWrapperFilter);
-        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
-        bean.addUrlPatterns(Constants.API_URL_PATTERNS);
-        return bean;
-    }
-
-    /**
-     * CORS Filter 등록
-     * @return
-     */
+    //TODO :: ArgumentResolver add
     @Override
-    public void addCorsMappings(CorsRegistry registry) {
-        registry.addMapping("/batch/**")
-            .allowedOrigins(corsProperties.getAllowedOrigins().split(","))
-            .allowedMethods(corsProperties.getAllowedMethods().split(","))
-            .allowedHeaders(corsProperties.getAllowedHeaders().split(","))
-            .allowCredentials(corsProperties.getAllowCredentials())
-            .maxAge(corsProperties.getMaxAge())
-            .exposedHeaders(corsProperties.getExposeHeader());
+    public void addArgumentResolvers(List resolvers) {
+        resolvers.add(new CustomArgumentResolver());
+        resolvers.add(new PageableArgumentResolver());
     }
 
 
diff --git a/mens-core/src/main/java/kr/xit/core/spring/filter/ReadableRequestWrapper.java b/mens-core/src/main/java/kr/xit/core/spring/filter/ReadableRequestWrapper.java
index 5977421..bab5398 100644
--- a/mens-core/src/main/java/kr/xit/core/spring/filter/ReadableRequestWrapper.java
+++ b/mens-core/src/main/java/kr/xit/core/spring/filter/ReadableRequestWrapper.java
@@ -32,7 +32,7 @@ import lombok.extern.slf4j.Slf4j;
 
 /**
  * 
- * description : POST request parameter logging
+ * description : POST request parameter logging 처리
  * packageName : kr.xit.core.spring.filter
  * fileName    : ReadableRequestWrapper
  * author      : julim
diff --git a/mens-core/src/main/java/kr/xit/core/spring/filter/ReadableRequestWrapperFilter.java b/mens-core/src/main/java/kr/xit/core/spring/filter/ReadableRequestWrapperFilter.java
index 83ff1b3..75e998f 100644
--- a/mens-core/src/main/java/kr/xit/core/spring/filter/ReadableRequestWrapperFilter.java
+++ b/mens-core/src/main/java/kr/xit/core/spring/filter/ReadableRequestWrapperFilter.java
@@ -14,7 +14,7 @@ import lombok.extern.slf4j.Slf4j;
 
 /**
  * 
- * description : POST request parameter logging
+ * description : POST request parameter logging을 위한 Filter
  * packageName : kr.xit.core.spring.filter
  * fileName    : ReadableRequestWrapperFilter
  * author      : julim