Skip to content
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

[feat] log filter 추가 및 aop 수정 #39

Merged
merged 2 commits into from
Jan 10, 2024

Conversation

linglong67
Copy link
Collaborator

@linglong67 linglong67 commented Jan 9, 2024

💡 Motivation and Context

공통 Log 처리방식 변경


🔨 Modified

비즈니스 로직 처리 전, 후 Log를 남기는 공통 로직을 aop에서 filter로 이동

  • LogFilter에서 비즈니스 로직 처리 전, 후 로그를 남김
  • AOP에서는 커스텀 어노테이션으로 로그 남기는 형태로 하나 만들어둠
  • 커스텀 어노테이션 1개 작성 (실행시간 측정)
  • 아래 예시처럼 적용 가능
    image

🌟 More

  • [참고] AOP에서 커스텀 어노테이션 등을 통해 로그를 작성할 케이스가 있다면 위 방식 참고
  • [참고] annotation, filter 패키지 추가되면서 상위 패키지로 global 생성함


📋 커밋 전 체크리스트

  • 추가/변경에 대한 단위 테스트를 완료하였습니다.
  • 컨벤션에 맞게 작성하였습니다.

🤟🏻 PR로 완료된 이슈

closes #38

- 기존에 aop 있던 비즈니스 로직 전, 후 로깅 로직은 filter로 옮김 (실행 시점 및 세부 로그는 일부 달라짐)
- aop에는 커스텀 어노테이션으로 로그 남기는 형태로 하나 만들어둠
- 실행시간 측정하는 용도의 커스텀 어노테이션 생성
@linglong67 linglong67 added 🖥️ BackEnd 서버 관련 💡 Feature 새로운 기능 추가, 혹은 구현 🔨 Refactor 이 코드는 아주 약간 더 클린코드에 가까워졌습니다... labels Jan 9, 2024
@linglong67 linglong67 self-assigned this Jan 9, 2024
Copy link

cr-gpt bot commented Jan 9, 2024

Seems you are using me but didn't get OPENAI_API_KEY seted in Variables/Secrets for this repo. you could follow readme for more information

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
ContentCachingRequestWrapper req = new ContentCachingRequestWrapper((HttpServletRequest) request);
ContentCachingResponseWrapper res = new ContentCachingResponseWrapper((HttpServletResponse) response);
Copy link
Collaborator

@gunsight1 gunsight1 Jan 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ServletRequest, ServletResponce가 받아오기만 하고 ContentCachingRequestWrapper, ResponseWrapper가 실제 수행하는 변수라면 변수명 request <-> req 바꿔 쓰는 것이 이어지는 하위 코드들의 가독성에는 더 좋을 것이라 생각듭니다!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

말씀해주신 부분 확인하고, 수정해서 커밋했습니다~!

Copy link

cr-gpt bot commented Jan 9, 2024

Seems you are using me but didn't get OPENAI_API_KEY seted in Variables/Secrets for this repo. you could follow readme for more information

Copy link
Collaborator

@chan99k chan99k left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 고생하셨습니다!!

Comment on lines +14 to +23
@Around("@annotation(com.kernel360.global.annotation.LogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object proceed = joinPoint.proceed();

long executionTime = System.currentTimeMillis() - start;
log.info("##### @LogExecutionTime ##### " + joinPoint.getSignature() + " executed in " + executionTime + "ms");

return proceed;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

특정 로그를 남기도록 커스텀 어노테이션으로 추가하고 싶다면 여기 LogAspect.java 에 메서드를 추가하고 어노테이션을 선언하면 되나요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네! 맞습니다~!
커스텀 어노테이션 생성 후에 위 코드처럼 메소드 추가해주시면 되요~

@HyunJunSon HyunJunSon self-requested a review January 10, 2024 01:51
Copy link
Collaborator

@HyunJunSon HyunJunSon left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Comment on lines +18 to +60
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
ContentCachingRequestWrapper request = new ContentCachingRequestWrapper((HttpServletRequest) req);
ContentCachingResponseWrapper response = new ContentCachingResponseWrapper((HttpServletResponse) res);
log.info("##### INIT URI: {}", request.getRequestURI());

chain.doFilter(request, response);

// Request
StringBuilder requestHeaderValues = new StringBuilder();
request.getHeaderNames().asIterator().forEachRemaining(headerKey -> {
String headerValue = request.getHeader(headerKey);

requestHeaderValues
.append("[")
.append(headerKey)
.append(" : ")
.append(headerValue)
.append("] ");
});

String requestBody = new String(request.getContentAsByteArray());
String uri = request.getRequestURI();
String method = request.getMethod();
log.info("##### REQUEST ##### uri: {}, method: {}, header: {}, body: {}", uri, method, requestHeaderValues, requestBody);

// Response
StringBuilder responseHeaderValues = new StringBuilder();
response.getHeaderNames().forEach(headerKey -> {
String headerValue = response.getHeader(headerKey);

responseHeaderValues
.append("[")
.append(headerKey)
.append(" : ")
.append(headerValue)
.append("] ");
});

String responseBody = new String(response.getContentAsByteArray());
log.info("##### RESPONSE ##### uri: {}, method: {}, header: {}, body: {}", uri, method, responseHeaderValues, responseBody);

response.copyBodyToResponse();
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

메소드가 라인수가 조금 무거운거 같은데,
리스폰스, 리퀘스트 로직 따로 메소드로 빼는게 어떨까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

제가 이건 리팩토링 고려해보고 수정하게 되면 다음에 다시 올릴게요~!

@linglong67 linglong67 merged commit 9275fc0 into Kernel360:develop Jan 10, 2024
1 check passed
@linglong67 linglong67 deleted the feature/log-filter-and-aop branch January 10, 2024 03:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🖥️ BackEnd 서버 관련 💡 Feature 새로운 기능 추가, 혹은 구현 🔨 Refactor 이 코드는 아주 약간 더 클린코드에 가까워졌습니다...
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Filter 로깅 추가 및 AOP 로깅 변경
4 participants