spring aop 可以在不破坏我们程序代码的前提下很好的对程序异常进行打印,网上也有很多这样的例子,我这里写的比较简单,只是针对程序出异常时进行见到的日志打印,代码比较简单。
异常日志处理类
package com.apt.study.exception; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSONObject; @Component @Aspect public class ExceptionToJson { public Logger logger = LoggerFactory.getLogger(ExceptionToJson.class); @Pointcut("execution(* com.apt.study.service..*.*(..))") public void exceptionLog() { } @AfterThrowing(pointcut = "exceptionLog()", throwing="e") public void doAfterThrowing(JoinPoint joinPoint, Throwable e) { try { logger.error("------->Error Class:" + e.getClass().getName()); logger.error("------->Error msg:" + e.getMessage()); logger.error("------->Error method:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")); Object[] arguments = joinPoint.getArgs(); if (arguments != null && arguments.length > 0) { for ( int i = 0; i < arguments.length; i++) { logger.error("------->args[" + i + "]: " + JSONObject.toJSONString(arguments[i])); } } } catch (Exception ex) { //记录本地异常日志 logger.error("------->异常通知异常"); logger.error("------->异常信息:{}", ex.getMessage()); } } }
时间: 2024-10-27 11:25:18