增加切面

This commit is contained in:
2025-07-13 00:53:10 +08:00
parent 1a381b0c8a
commit 867a669836
2 changed files with 104 additions and 0 deletions

View File

@ -215,6 +215,13 @@
<version>1.5.5.Final</version>
<scope>provided</scope>
</dependency>
<!-- FastJSON -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
</dependencies>
<!-- Build Configuration -->

View File

@ -0,0 +1,97 @@
package com.sczx.car.aspect;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @Author Huang Kai
* @Date 2023/1/18 17:01
* @Version 1.0
*/
@Aspect
@Component
@Slf4j
public class WebLogAspect {
/** 以 controller 包下定义的所有请求为切入点 */
@Pointcut("execution(public * com.sczx.*.controller.*.*(..))")
public void webLog() {}
/**
* 在切点之前织入
* @param joinPoint
*/
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
String uid = UUID.randomUUID().toString();
MDC.put("requestId",uid.substring(24,36));
// 开始打印请求日志
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = null;
if (attributes != null) {
request = attributes.getRequest();
}
// 打印请求相关参数
log.info("========================= Start =========================");
// 打印请求入参
try{
Object[] args = joinPoint.getArgs();
List<Object> filteredArgs = new ArrayList<>();
for (Object arg : args) {
//如果是文件类,则只打印文件名称和大小
if (arg instanceof MultipartFile) {
MultipartFile file = (MultipartFile) arg;
JSONObject fileJson = new JSONObject();
fileJson.put("filename", file.getOriginalFilename());
fileJson.put("size", file.getSize());
filteredArgs.add(fileJson);
} else {
filteredArgs.add(arg);
}
}
if (request != null) {
log.info("URL:{} , {}", request.getRequestURL().toString(), JSON.toJSONString(filteredArgs));
}
} catch (Exception e){
log.error("打印WebLogAspect_Request失败args无法被序列化", e);
}
}
/**
* 处理完请求后执行
* @param joinPoint
* @param result
*/
@AfterReturning(pointcut = "webLog()", returning = "result")
public void doAfterReturning(JoinPoint joinPoint, Object result) {
// 打印出参
try {
log.info("WebLogAspect_Response:{}", JSON.toJSON(result));
}catch (Exception e){
log.error("打印WebLogAspect_Response失败result无法被序列化", e);
}
log.info("========================= End =========================");
MDC.clear();
}
@AfterThrowing(throwing="ex",pointcut="webLog()")
public void doRecoveryActions(Throwable ex){
MDC.clear();
}
}