maven
<!-- aop依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
//配置
aop:
proxy-target-class: true
1.自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
2.aop实现类
@Slf4j
@Aspect
@Component
public class LogAspect {
@Resource
private BaseProperties dsProperties;
@Resource
private LogService logService;
@Around("@annotation(com.gc.jgdq.cowork.common.annotation.Log)")
public Object around(ProceedingJoinPoint point) throws Throwable {
Object result = null;
HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
String uri = request.getRequestURI();
String method = request.getMethod();
log.info("********************【" + uri + "】 请求开始 **************************");
log.info("【请求路径】>>>> {}", uri);
log.info("【请求方式】>>>> {}", method);
log.info("【方法参数】>>>> {}", getFieldsName((JoinPoint) point));
long beginTime = System.currentTimeMillis();
try {
result = point.proceed();
} catch (Throwable e) {
log.error(e.getMessage());
throw e;
}
String ip = IpUtil.getIpAddr(request);
long time = System.currentTimeMillis() - beginTime;
if (dsProperties.isOpenAopLog()) {
String token = (String) SecurityUtils.getSubject().getPrincipal();
String username = JWTUtil.getUsername(token);
SysLog log = new SysLog();
log.setId(UIdUtil.getInstance().id());
log.setUsername(username);
log.setIp(ip);
log.setTime(time);
logService.saveLog(point, log);
}
log.info("【请求耗时】>>>> {} ms", time);
log.info("********************【" + uri + "】 请求结束 **************************");
return result;
}
private Map<String, Object> getFieldsName(JoinPoint joinPoint) throws ClassNotFoundException, NoSuchMethodException {
String classType = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
Class<?>[] classes = new Class[args.length];
for (int k = 0; k < args.length; k++) {
if (args[k] == null) {
return null;
}
if (args[k] instanceof MultipartFile || args[k] instanceof ServletRequest || args[k] instanceof ServletResponse) {
return null;
}
if (!args[k].getClass().isPrimitive()) {
Class s = args[k].getClass();
classes[k] = s == null ? args[k].getClass() : s;
}
}
ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
Method method = Class.forName(classType).getMethod(methodName, classes);
String[] parameterNames = pnd.getParameterNames(method);
HashMap<String, Object> paramMap = new HashMap<>();
assert parameterNames != null;
for (int i = 0; i < parameterNames.length; i++) {
paramMap.put(parameterNames[i], args[i]);
}
return paramMap;
}
}