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

View File

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