Springboot 通过aop捕获并记录异常日志

文章介绍了如何在SpringBoot项目中使用AOP实现异常日志记录,包括定义切点、异常通知以及如何获取和处理方法的自定义注解信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

欢迎大家访问我的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层面的错误日志捕获和记录。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值