修改Aop

master
张小东 2023-11-21 22:01:24 +08:00
parent 009b25f4d8
commit 7450eb713e
3 changed files with 37 additions and 79 deletions

View File

@ -1,6 +1,6 @@
package com.february.common.domain.aspect; package com.february.common.domain.aspect;
import com.alibaba.nacos.shaded.com.google.gson.Gson; import com.google.gson.Gson;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*; import org.aspectj.lang.annotation.*;
@ -18,100 +18,70 @@ import java.lang.reflect.Method;
*/ */
@Aspect @Aspect
@Component @Component
//@Profile({"dev", "test"}) //只想在开发环境或者测试环境中使用
public class WebLogAspect { public class WebLogAspect {
private final static Logger logger = LoggerFactory.getLogger(WebLogAspect.class); private final static Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
/** 换行符 */ private static final Gson gson = new Gson(); // 用于重复使用Gson实例
private static final String LINE_SEPARATOR = System.lineSeparator(); private static final String LINE_SEPARATOR = System.lineSeparator();
/** 以自定义 @WebLog 注解为切点 */
@Pointcut("@annotation(com.february.common.domain.aspect.WebLog)") @Pointcut("@annotation(com.february.common.domain.aspect.WebLog)")
public void webLog() {} public void webLog() {}
/**
*
* @param joinPoint
* @throws Throwable
*/
@Before("webLog()") @Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable { public void doBefore(JoinPoint joinPoint) {
// 开始打印请求日志 // 开始打印请求日志
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest(); HttpServletRequest request = attributes.getRequest();
// 获取 @WebLog 注解的描述信息 // 获取 @WebLog 注解的描述信息
String methodDescription = getAspectLogDescription(joinPoint); String methodDescription;
try {
methodDescription = getAspectLogDescription(joinPoint);
} catch (Exception e) {
methodDescription = "无法获取方法描述信息";
logger.error("获取方法描述信息时发生异常: ", e);
}
// 打印请求相关参数 // 打印请求相关参数
logger.info("========================================== Start =========================================="); logger.info("========================================== Start ==========================================");
// 打印请求 url
logger.info("URL : {}", request.getRequestURL().toString()); logger.info("URL : {}", request.getRequestURL().toString());
// 打印描述信息
logger.info("Description : {}", methodDescription); logger.info("Description : {}", methodDescription);
// 打印 Http method
logger.info("HTTP Method : {}", request.getMethod()); logger.info("HTTP Method : {}", request.getMethod());
// 打印调用 controller 的全路径以及执行方法
logger.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); logger.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
// 打印请求的 IP
logger.info("IP : {}", request.getRemoteAddr()); logger.info("IP : {}", request.getRemoteAddr());
// 打印请求入参 logger.info("Request Args : {}", gson.toJson(joinPoint.getArgs()));
logger.info("Request Args : {}", new Gson().toJson(joinPoint.getArgs())); }
} }
/**
*
* @throws Throwable
*/
@After("webLog()") @After("webLog()")
public void doAfter() throws Throwable { public void doAfter() {
// 接口结束后换行,方便分割查看 logger.info("=========================================== End ==========================================={}", LINE_SEPARATOR);
logger.info("=========================================== End ===========================================" + LINE_SEPARATOR);
} }
/**
*
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around("webLog()") @Around("webLog()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
Object result = proceedingJoinPoint.proceed(); Object result = proceedingJoinPoint.proceed();
// 打印出参 logger.info("Response Args : {}", gson.toJson(result));
logger.info("Response Args : {}", new Gson().toJson(result));
// 执行耗时
logger.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime); logger.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
return result; return result;
} }
private String getAspectLogDescription(JoinPoint joinPoint) throws ClassNotFoundException {
/**
*
*
* @param joinPoint
* @return
* @throws Exception
*/
public String getAspectLogDescription(JoinPoint joinPoint)
throws Exception {
String targetName = joinPoint.getTarget().getClass().getName(); String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName(); String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs(); Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName); Class<?> targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods(); Method[] methods = targetClass.getMethods();
StringBuilder description = new StringBuilder("");
for (Method method : methods) { for (Method method : methods) {
if (method.getName().equals(methodName)) { if (method.getName().equals(methodName) && method.getParameterTypes().length == arguments.length) {
Class[] clazzs = method.getParameterTypes(); WebLog webLog = method.getAnnotation(WebLog.class);
if (clazzs.length == arguments.length) { if (webLog != null) {
description.append(method.getAnnotation(WebLog.class).description()); return webLog.description();
break;
} }
} }
} }
return description.toString(); return "";
} }
} }

View File

@ -2,9 +2,11 @@ package com.vehicle.trajectory;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@SpringBootApplication @SpringBootApplication
@EnableAspectJAutoProxy
public class TrajectoryApplication { public class TrajectoryApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(TrajectoryApplication.class); SpringApplication.run(TrajectoryApplication.class);

View File

@ -7,7 +7,6 @@ import com.february.common.domain.Vehicle;
import com.february.common.domain.VehicleType; import com.february.common.domain.VehicleType;
import com.february.common.domain.aspect.WebLog; import com.february.common.domain.aspect.WebLog;
import com.vehicle.trajectory.service.TrajectoryService; import com.vehicle.trajectory.service.TrajectoryService;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
@ -16,8 +15,6 @@ import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.List; import java.util.List;
//@Log4j2
@Aspect
@RestController @RestController
@RequestMapping("/vehicle") @RequestMapping("/vehicle")
public class TrajectoryController { public class TrajectoryController {
@ -32,10 +29,7 @@ public class TrajectoryController {
@GetMapping("/realDateList") @GetMapping("/realDateList")
@WebLog(description = "实时数据查看") @WebLog(description = "实时数据查看")
public Result<List<RealData>> realDateList() { public Result<List<RealData>> realDateList() {
//log.info("功能名称:【实时数据查看】,请求路径:【{}】,请求方式:【{}】", request.getRequestURI(), request.getMethod()); return trajectoryService.realDateList();
Result<List<RealData>> result = trajectoryService.realDateList();
//log.info("请求结果:【{}】", result);
return result;
} }
@ -46,10 +40,7 @@ public class TrajectoryController {
@GetMapping("/vehicleList") @GetMapping("/vehicleList")
@WebLog(description = "查看在线车辆") @WebLog(description = "查看在线车辆")
public Result<List<Vehicle>> carList() { public Result<List<Vehicle>> carList() {
//log.info("功能名称:【查看在线车辆】,请求路径:【{}】,请求方式:【{}】", request.getRequestURI(), request.getMethod()); return trajectoryService.vehicleList();
Result<List<Vehicle>> result = trajectoryService.vehicleList();
//log.info("请求结果:【{}】", result);
return result;
} }
/** /**
@ -58,11 +49,6 @@ public class TrajectoryController {
@GetMapping("/vehicleTypeList") @GetMapping("/vehicleTypeList")
@WebLog(description = "车辆类型") @WebLog(description = "车辆类型")
public Result<List<VehicleType>> vehicleTypeList(){ public Result<List<VehicleType>> vehicleTypeList(){
return trajectoryService.vehicleTypeList();
// log.info("功能名称:【车辆类型】,请求路径:【{}】,请求方式:【{}】",request.getRequestURI(),request.getMethod());
Result<List<VehicleType>> result = trajectoryService.vehicleTypeList();
// log.info("请求结果:【{}】",result);
return result;
} }
} }