欢迎大家访问我的AI工具网站谷流仓 - guliucang.com,可以直接使用gpt对话
项目基于springboot, 需要引入aop依赖,如下:
<!-- spring aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
首先展示一下ExceptionLogAspect.class的完整代码
package com.leo.glc.aspect;
import com.leo.glc.annotation.OperationLogger;
import com.leo.glc.annotation.VisitLogger;
import com.leo.glc.entity.ExceptionLog;
import com.leo.glc.service.ExceptionLogService;
import com.leo.glc.util.AopUtils;
import com.leo.glc.util.IpAddressUtils;
import com.leo.glc.util.JacksonUtils;
import com.leo.glc.util.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
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.lang.reflect.Method;
import java.util.Map;
/**
* AOP记录异常日志
* @author leo
* @since 1.0
*/
@Component
@Aspect
public class ExceptionLogAspect {
@Autowired
ExceptionLogService exceptionLogService;
/**
* 配置切入点
*/
@Pointcut("execution(* com.leo.glc.controller..*.*(..))")
public void logPointcut() {
}
/**
* 定义了一个异常通知,这个通知对上面定义的logPointcut()切入点中的所有方法有效
*/
@AfterThrowing(value = "logPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Exception e) {
ExceptionLog log = handleLog(joinPoint, e);
exceptionLogService.saveExceptionLog(log);
}
/**
* 设置ExceptionLog对象属性
*
* @return
*/
private ExceptionLog handleLog(JoinPoint joinPoint, Exception e) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String uri = request.getRequestURI();
String method = request.getMethod();
String ip = IpAddressUtils.getIpAddress(request);
String userAgent = request.getHeader("User-Agent");
String description = getDescriptionFromAnnotations(joinPoint);
String error = StringUtils.getStackTrace(e);
ExceptionLog log = new ExceptionLog(uri, method, description, error, ip, userAgent);
Map<String, Object> requestParams = AopUtils.getRequestParams(joinPoint);
log.setParam(StringUtils.substring(JacksonUtils.writeValueAsString(requestParams), 0, 2000));
return log;
}
private String getDescriptionFromAnnotations(JoinPoint joinPoint) {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
OperationLogger operationLogger = method.getAnnotation(OperationLogger.class);
if (operationLogger != null) {
return operationLogger.value();
}
VisitLogger visitLogger = method.getAnnotation(VisitLogger.class);
if (visitLogger != null) {
return visitLogger.value().getBehavior();
}
return "";
}
}
然后我们来看一下上面的代码是如何实现aop记录日志的
首先,类上加上@Aspect
注解,声明这是一个切面类(使用时需要与@Component
注解一起用,表明同时将该类交给spring管理)。
@Component
@Aspect
public class ExceptionLogAspect {
···
}
然后,通过@Pointcut
注解定义切入点
@Pointcut("execution(* com.leo.glc.controller..*.*(..))")
public void logPointcut() {
}
如上,execution(* com.leo.glc.controller..*.*(..))
用于匹配切入点,从左到右解释,*
表示返回所有类型,com.leo.glc.controller
表示匹配controller包,..
表示匹配该包下的所有子包,子孙包,*
表示匹配包下的所有类,*(..)
表示匹配类里面的所有方法,其中(..)
表示任意参数。所以上面的表达式就代表切入点为controller包下的所有类的所有方法。
execution表达式的其他用法见文章: SpringAop切入点execution表达式详解
定义好了切入点之后,通过@AfterThrowing
注解来捕获异常,并对异常进行记录
/**
* 定义了一个异常通知,这个通知对上面定义的logPointcut()切入点中的所有方法有效
*/
@AfterThrowing(value = "logPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Exception e) {
ExceptionLog log = handleLog(joinPoint, e);
exceptionLogService.saveExceptionLog(log);
}
上面这段代码通过。ExceptionLog log = handleLog(joinPoint, e);
生成了实体类,然后通过exceptionLogService.saveExceptionLog(log);
把错误日志记录到数据库,方便后续复查。至此,异常的捕获和持久化到数据库已经完成了。
下面,我们来看一下handleLog方法
/**
* 设置ExceptionLog对象属性
*
* @return
*/
private ExceptionLog handleLog(JoinPoint joinPoint, Exception e) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String uri = request.getRequestURI();
String method = request.getMethod();
String ip = IpAddressUtils.getIpAddress(request);
String userAgent = request.getHeader("User-Agent");
String description = getDescriptionFromAnnotations(joinPoint);
String error = StringUtils.getStackTrace(e);
ExceptionLog log = new ExceptionLog(uri, method, description, error, ip, userAgent);
Map<String, Object> requestParams = AopUtils.getRequestParams(joinPoint);
log.setParam(StringUtils.substring(JacksonUtils.writeValueAsString(requestParams), 0, 2000));
return log;
}
- 通过
RequestContextHolder.getRequestAttributes().getRequest();
获取到request, - 然后再通过request拿到请求路径uri,请求方法,来源ip地址,用户的userAgent等信息。
- 如果可以获取到改方法的注释信息,就添加记录一下。description是通过该切入点上的其他注解来获取到关于该方法的描述信息,比如此处就是通过
@OperationLogger
和@VisitLogger
这两个自定义的注解获取到的,当然不是所有的方法都加上了这些注解。如下getDescriptionFromAnnotations(joinPoint);
方法尝试获取自定义注解的注解信息:
private String getDescriptionFromAnnotations(JoinPoint joinPoint) {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
OperationLogger operationLogger = method.getAnnotation(OperationLogger.class);
if (operationLogger != null) {
return operationLogger.value();
}
VisitLogger visitLogger = method.getAnnotation(VisitLogger.class);
if (visitLogger != null) {
return visitLogger.value().getBehavior();
}
return "";
}
以上就完成了对controller层面的错误日志捕获和记录。