利用 spring aop 的 around 来实现日志拦截器,此拦截器负责打印抛出到顶层的异常日志。
具体实现
引入相关切面依赖
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.9</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.9</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency>
实现日志拦截器
拦截异常打印日志,注意用线程本地变量startLocal,来做一个是否为第一个(入口)本地方法的标志。这样做的目的是为了避免重复在每个方法里catch异常, 抛出异常操作的时候打印异常。注意catch的是 java.lang.Throwable级别的异常。包括所有的errors 和 exceptions。
public class LogInterceptor { private final Logger logger = LoggerFactory.getLogger(LogInterceptor.class); /** * 首次进入标志 */ private static final ThreadLocal<Boolean> startLocal = new ThreadLocal<Boolean>(); public Object doLog(ProceedingJoinPoint jp) throws Throwable { Boolean isStart = startLocal.get(); // 做源头标记 if (isStart == null) { startLocal.set(true); if (logger.isDebugEnabled()) { LogUtils.debug(logger, "----------开始进入全局日志记录拦截器-------------"); } } try { // 执行目标方法 return jp.proceed(); } catch (Throwable e) { if (isStart == null) { logger.warn("业务执行出现未知异常:", e); } throw e; } finally { if (isStart == null) { startLocal.remove(); } } } }
日志拦截器的配置
配置拦截器,配置切面作用的范围的表达式
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://

