-
Notifications
You must be signed in to change notification settings - Fork 0
로그 기능 추가 #21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
로그 기능 추가 #21
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
96 changes: 96 additions & 0 deletions
96
src/main/java/com/recyclestudy/common/log/ApiLogFilter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| package com.recyclestudy.common.log; | ||
|
|
||
| import jakarta.servlet.Filter; | ||
| import jakarta.servlet.FilterChain; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.ServletRequest; | ||
| import jakarta.servlet.ServletResponse; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import java.io.IOException; | ||
| import java.util.Optional; | ||
| import java.util.UUID; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.slf4j.MDC; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import static com.recyclestudy.common.log.MDCKey.CLIENT_IP; | ||
| import static com.recyclestudy.common.log.MDCKey.HOST; | ||
| import static com.recyclestudy.common.log.MDCKey.HTTP_METHOD; | ||
| import static com.recyclestudy.common.log.MDCKey.QUERY_STRING; | ||
| import static com.recyclestudy.common.log.MDCKey.REQUEST_URI; | ||
| import static com.recyclestudy.common.log.MDCKey.TRACE_ID; | ||
| import static com.recyclestudy.common.log.MDCKey.USER_AGENT; | ||
|
|
||
| @Slf4j | ||
| @Component | ||
| public class ApiLogFilter implements Filter { | ||
|
|
||
| private static final String REQUEST_ID_HEADER = "X-Request-Id"; | ||
|
|
||
| @Override | ||
| public void doFilter( | ||
| final ServletRequest servletRequest, | ||
| final ServletResponse servletResponse, | ||
| final FilterChain filterChain | ||
| ) throws IOException, ServletException { | ||
| final HttpServletRequest request = (HttpServletRequest) servletRequest; | ||
| final HttpServletResponse response = (HttpServletResponse) servletResponse; | ||
|
|
||
| final String traceId = Optional.ofNullable(request.getHeader(REQUEST_ID_HEADER)) | ||
| .filter(header -> !header.isBlank()) | ||
| .orElseGet(this::generateTraceId); | ||
|
|
||
| populateMDC(traceId, request); | ||
| response.setHeader(REQUEST_ID_HEADER, traceId); | ||
|
|
||
| final long startTime = System.currentTimeMillis(); | ||
| logRequest(request); | ||
|
|
||
| int statusForLog = 200; | ||
| try { | ||
| filterChain.doFilter(servletRequest, servletResponse); | ||
| statusForLog = response.getStatus(); | ||
| } catch (final Exception ex) { | ||
| statusForLog = 500; | ||
| throw ex; | ||
| } finally { | ||
| logResponse(response, startTime, statusForLog); | ||
| MDC.clear(); | ||
| } | ||
| } | ||
|
|
||
| private void logRequest(final HttpServletRequest request) { | ||
| final String uri = request.getRequestURI(); | ||
| final String method = request.getMethod(); | ||
| final String ip = request.getRemoteAddr(); | ||
|
|
||
| final String queryString = request.getQueryString(); | ||
| final String userAgentHeader = request.getHeader("User-Agent"); | ||
| final String query = (queryString != null ? "?" + queryString : ""); | ||
| final String userAgent = (userAgentHeader != null ? userAgentHeader : "-"); | ||
|
|
||
| log.info("[REQ] layer=filter | ip={} | method={} | uri={}{} | userAgent={}", ip, method, uri, query, userAgent); | ||
jhan0121 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| private void logResponse(final HttpServletResponse response, final long startTime, final int status) { | ||
| final long duration = System.currentTimeMillis() - startTime; | ||
| final String contentType = Optional.ofNullable(response.getContentType()).orElse("-"); | ||
|
|
||
| log.info("[RES] layer=filter | status={} | duration={}ms | contentType={}", status, duration, contentType); | ||
| } | ||
|
|
||
| private String generateTraceId() { | ||
| return UUID.randomUUID().toString().substring(0, 8); | ||
| } | ||
|
|
||
| private void populateMDC(final String traceId, final HttpServletRequest request) { | ||
| MDC.put(TRACE_ID.getKey(), traceId); | ||
| MDC.put(HOST.getKey(), request.getHeader("host")); | ||
| MDC.put(HTTP_METHOD.getKey(), request.getMethod()); | ||
| MDC.put(REQUEST_URI.getKey(), request.getRequestURI()); | ||
| MDC.put(QUERY_STRING.getKey(), request.getQueryString()); | ||
| MDC.put(CLIENT_IP.getKey(), request.getRemoteAddr()); | ||
| MDC.put(USER_AGENT.getKey(), request.getHeader("User-Agent")); | ||
| } | ||
| } | ||
88 changes: 88 additions & 0 deletions
88
src/main/java/com/recyclestudy/common/log/ControllerLoggingAspect.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| package com.recyclestudy.common.log; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import java.util.Arrays; | ||
| import java.util.Optional; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.aspectj.lang.ProceedingJoinPoint; | ||
| import org.aspectj.lang.annotation.Around; | ||
| import org.aspectj.lang.annotation.Aspect; | ||
| import org.aspectj.lang.annotation.Pointcut; | ||
| import org.aspectj.lang.reflect.MethodSignature; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.context.request.RequestContextHolder; | ||
| import org.springframework.web.context.request.ServletRequestAttributes; | ||
|
|
||
| @Aspect | ||
| @Component | ||
| @Slf4j | ||
| public class ControllerLoggingAspect { | ||
|
|
||
| private static final int MAX_LOG_LENGTH = 500; | ||
|
|
||
| @Pointcut("execution(* com.recyclestudy..controller..*(..))") | ||
| public void controllerMethods() { | ||
| } | ||
|
|
||
| @Around("controllerMethods()") | ||
| public Object logController(final ProceedingJoinPoint joinPoint) throws Throwable { | ||
| final MethodSignature signature = (MethodSignature) joinPoint.getSignature(); | ||
| final String className = signature.getDeclaringType().getSimpleName(); | ||
| final String methodName = signature.getName(); | ||
| final Object[] args = joinPoint.getArgs(); | ||
|
|
||
| final HttpServletRequest request = getCurrentHttpRequest(); | ||
| final String httpMethod = request != null ? request.getMethod() : "N/A"; | ||
| final String uri = request != null ? request.getRequestURI() : "N/A"; | ||
|
|
||
| final long startTime = System.currentTimeMillis(); | ||
| logRequest(className, methodName, httpMethod, uri, args); | ||
|
|
||
| final Object result = joinPoint.proceed(); | ||
| logResponse(className, methodName, httpMethod, uri, result, startTime); | ||
|
|
||
| return result; | ||
| } | ||
|
|
||
| private void logRequest( | ||
| final String className, | ||
| final String methodName, | ||
| final String httpMethod, | ||
| final String uri, | ||
| final Object[] args | ||
| ) { | ||
| log.info("[REQ] layer=controller | method={}.{} | httpMethod={} | uri={} | args={}", | ||
| className, methodName, httpMethod, uri, Arrays.toString(args)); | ||
jhan0121 marked this conversation as resolved.
Show resolved
Hide resolved
jhan0121 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| private void logResponse( | ||
| final String className, | ||
| final String methodName, | ||
| final String httpMethod, | ||
| final String uri, | ||
| final Object result, | ||
| final long startTime | ||
| ) { | ||
| final long duration = System.currentTimeMillis() - startTime; | ||
| final String resultStr = formatResult(result); | ||
|
|
||
| log.info("[RES] layer=controller | method={}.{} | httpMethod={} | uri={} | duration={}ms | result={}", | ||
| className, methodName, httpMethod, uri, duration, resultStr); | ||
jhan0121 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| private HttpServletRequest getCurrentHttpRequest() { | ||
| return Optional.ofNullable(RequestContextHolder.getRequestAttributes()) | ||
| .filter(ServletRequestAttributes.class::isInstance) | ||
| .map(ServletRequestAttributes.class::cast) | ||
| .map(ServletRequestAttributes::getRequest) | ||
| .orElse(null); | ||
| } | ||
|
|
||
| private String formatResult(final Object result) { | ||
| if (result == null) { | ||
| return "null"; | ||
| } | ||
| final String resultStr = result.toString(); | ||
| return resultStr.length() <= MAX_LOG_LENGTH ? resultStr : resultStr.substring(0, MAX_LOG_LENGTH) + "..."; | ||
jhan0121 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| package com.recyclestudy.common.log; | ||
|
|
||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public enum MDCKey { | ||
|
|
||
| TRACE_ID("traceId"), | ||
| HOST("host"), | ||
| HTTP_METHOD("httpMethod"), | ||
| REQUEST_URI("requestUri"), | ||
| QUERY_STRING("queryString"), | ||
| CLIENT_IP("clientIp"), | ||
| USER_AGENT("userAgent"); | ||
|
|
||
| private final String key; | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
9 changes: 9 additions & 0 deletions
9
src/main/java/com/recyclestudy/exception/GlobalControllerAdvice.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.