Skip to content

Commit

Permalink
Merge pull request Kernel360#83 from Hju95/AOP리팩터링
Browse files Browse the repository at this point in the history
[refactor] AOP 리팩터링 1차
  • Loading branch information
mooncw authored Jan 9, 2024
2 parents f08efb0 + d372d88 commit 541a3b7
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 55 deletions.
84 changes: 31 additions & 53 deletions src/main/java/com/kernel360/kernelsquare/global/aop/Logging.java
Original file line number Diff line number Diff line change
@@ -1,75 +1,53 @@
package com.kernel360.kernelsquare.global.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class Logging {
//ToDo 로그 정책이 정해지면 리팩토링
@Pointcut("execution(* com.kernel360.kernelsquare.domain.member.service.MemberService.*(..)) || " +
"execution(* com.kernel360.kernelsquare.domain.question.service.QuestionService.*(..))")
public void allController() {}

@Around("allController()")
public Object aroundServiceMethod(ProceedingJoinPoint joinPoint) throws Throwable {
Signature signature = joinPoint.getSignature();
String fileFullName = signature.getDeclaringTypeName(); // 파일 전체 이름을 가져옵니다.
String packageName = fileFullName.substring(0, fileFullName.lastIndexOf('.')); // 패키지 이름을 가져옵니다.
String className = fileFullName.substring(fileFullName.lastIndexOf('.')+1); // 클래스 이름을 가져옵니다.
String methodName = signature.getName(); // 메서드 이름을 가져옵니다.
private static final String TRACE_ID_NAME = "request_id";

try {
long startTime = System.currentTimeMillis();

log.info("Start - Package: " + packageName + ", Class: " + className + ", Method: " + methodName);

// 메서드 실행
Object result = joinPoint.proceed();

long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;

log.info("Method " + signature.toShortString() + " execution finished with duration " + executionTime + " ms");

return result;
} catch (Throwable e){
log.error("Method " + signature.toShortString() + " execution finished with error: " + e);

throw e;
}
@Pointcut("bean(*Service)")
private void service() {
}

/*일단은 레포지토리 메서드가 정상적으로 동작하면 DB에 반영됨을 전제로 함.*/
@Pointcut("execution(* com.kernel360.kernelsquare.domain.member.repository.MemberRepository.*(..)) || " +
"execution(* com.kernel360.kernelsquare.domain.question.repository.QuestionRepository.*(..))")
public void allRepository() {}

@Around("allRepository()")
public Object aroundRepositoryMethod(ProceedingJoinPoint joinPoint) throws Throwable {
Signature signature = joinPoint.getSignature();

try {
long startTime = System.currentTimeMillis();

Object result = joinPoint.proceed();

long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;

log.info("JPA " + signature.toShortString() + " execution time: " + executionTime + " ms");
@Pointcut("bean(*Controller)")
private void controller() {
}

return result;
} catch (Throwable e) {
log.error("JPA " + signature.toShortString() + " execution finished with error: " + e);
@AfterThrowing(pointcut = "service()", throwing = "exception")
private void logException(
JoinPoint joinPoint,
RuntimeException exception
) {
String exceptionName = exception.getClass().getSimpleName();
String exceptionMessage = exception.getMessage();
String methodName = joinPoint.getSignature().toShortString();
Object[] args = joinPoint.getArgs();
log.error("[{}] [Exception] {} , exceptionName = {}, exceptionMessage = {}, args = {}",
MDC.get(TRACE_ID_NAME), methodName, exceptionName, exceptionMessage, args);
}

throw e;
}
@Around("controller()")
private Object log(
ProceedingJoinPoint joinPoint
) throws Throwable {
var beforeTime = System.currentTimeMillis();
var methodName = joinPoint.getSignature().toShortString();
Object result = joinPoint.proceed();
var executeTime = System.currentTimeMillis() - beforeTime;
log.info("[{}] methodName : [{}] time = [{}ms]", MDC.get(TRACE_ID_NAME), methodName, executeTime);
return result;
}
}
23 changes: 23 additions & 0 deletions src/main/java/com/kernel360/kernelsquare/global/aop/MDCFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.kernel360.kernelsquare.global.aop;

import jakarta.servlet.*;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.UUID;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MDCFilter implements Filter {

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final UUID uuid = UUID.randomUUID();
MDC.put("request_id", uuid.toString());
chain.doFilter(request, response);
MDC.clear();
}
}
2 changes: 1 addition & 1 deletion src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ spring:
logging.level:
org.hibernate.SQL: debug
# org.hibernate.type: trace
org.springframework.security: debug
org.springframework.security: warn

cloud:
aws:
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/logback.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<property name="INFO_LOG_PATH" value="info/%d{yyyy-MM}/infoLog"/>
<property name="WARN_LOG_PATH" value="warn/%d{yyyy-MM}/warnLog"/>
<property name="ERROR_LOG_PATH" value="error/%d{yyyy-MM}/errorLog"/>
<property name="CONSOLE_LOG_PATTERN" value="%green(%d{yyyy-MM-dd HH:mm:ss}:) %magenta([%thread]) %highlight(%-5level) %cyan(%logger) %yellow([%C.%M:%line]) - %msg%n"/>
<property name="CONSOLE_LOG_PATTERN" value="%green(%d{yyyy-MM-dd HH:mm:ss}:) %magenta([%thread] [traceId=%X{traceId}]) %highlight(%-5level) %cyan(%logger) %yellow([%C.%M:%line]) - %msg%n"/>
<property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss}: [%thread] %-5level %logger [%C.%M:%line] - %msg%n"/>


Expand Down

0 comments on commit 541a3b7

Please sign in to comment.