package com.yuvision.pircvbs.config;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
@Aspect
@Component
@Slf4j
public class WebLogAspect {
ThreadLocal<Long> startTime = new ThreadLocal<>();
@Pointcut("execution(public * com.yuvision.pircvbs.*.controller.*.*(..))")
private void logPointCut() {
}
@Before("logPointCut()")
public void doBefore(JoinPoint joinPoint) {
try {
startTime.set(System.currentTimeMillis());
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Object params[] = joinPoint.getArgs();
log.info("-------------------------------------- 請求開始 -----------------------------------------------------");
log.info(">>> 方法地址: {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
log.info(">>> 請求入參: {}", Arrays.toString(params));
log.info(">>> 請求地址: " + request.getRequestURL().toString());
log.info(">>> 請求ip: " + request.getRemoteAddr());
} catch (Exception e) {
log.info("日志打印異常 -> {}",e.getMessage());
}
}
@After("logPointCut()")
public void daAfter() {
log.info("-------------------------------------- 請求結束 -----------------------------------------------------");
}
@AfterReturning(returning = "result", pointcut = "logPointCut()")
public void daAfterReturn(JoinPoint joinPoint, Object result) {
try {
log.info(">>> 響應時間: {}", (System.currentTimeMillis() - startTime.get()) + " ms");
log.info(">>> 返回內容: {}", new JSONObject(result));
} catch (Exception e) {
log.info(">>> 返回內容: {}", result);
}
}
}