SpringBoot+AOP实现日志记录

SpringBoot+AOP实现日志记录


Spring 三大特性,IOC(控制反转),DI(依赖注入),AOP(面向切面),那其中AOP的主要功能就是将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来。今天我们就来用springBoot Aop 来做日志记录



Maven依赖


    org.springframework.boot
    spring-boot-starter-aop


自定义操作日志注解

import java.lang.annotation.*;

@Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行
@Documented
public @interface OperLog {

    String operModul() default ""; // 操作模块

    String operType() default "";  // 操作类型

    String operDesc() default "";  // 操作说明
}

切面类记录操作日志

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
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.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Aspect
@Component
public class OperLogAspect {

 /**
  * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
  * 描述:哪个方法上带@OperLog注解,就在打印哪个方法的日志
  */
 @Pointcut("@annotation(cn.yx.zg.config.OperLog)")
 public void operLogPoinCut() {
 }

 /**
  * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
  */
 @Pointcut("execution(* cn.yx.zg.controller..*.*(..))")
 public void operExceptionLogPoinCut() {
 }

 /**
  * 正常返回通知,拦截用户操作日志,连接点正常执行完成后执行, 如果连接点抛出异常,则不会执行
  *
  * @param joinPoint 切入点
  * @param keys      返回结果 此处将result的类型声明为Object,意味着对目标方法的返回值不加限制
  */
 @AfterReturning(value = "operLogPoinCut()", returning = "keys")
 public void saveOperLog(JoinPoint joinPoint, Object keys) {
     // 获取RequestAttributes
     RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
     // 从获取RequestAttributes中获取HttpServletRequest的信息
     HttpServletRequest request = (HttpServletRequest) requestAttributes
             .resolveReference(RequestAttributes.REFERENCE_REQUEST);

     Map<String,Object> map = new HashMap<>();
     try {
         map.put("uuid", UUID.randomUUID().toString().replace("-",""));
         // 从切面织入点处通过反射机制获取织入点处的方法
         MethodSignature signature = (MethodSignature) joinPoint.getSignature();
         // 获取切入点所在的方法
         Method method = signature.getMethod();
         // 获取操作
         OperLog opLog = method.getAnnotation(OperLog.class);
         if (opLog != null) {
             String operModul = opLog.operModul();
             String operType = opLog.operType();
             String operDesc = opLog.operDesc();

             map.put("operModul",operModul);// 操作模块
             map.put("operType",operType);// 操作类型
             map.put("operDesc",operDesc);// 操作描述
         }
         // 获取请求的类名
         String className = joinPoint.getTarget().getClass().getName();
         // 获取请求的方法名
         String methodName = method.getName();
         methodName = className + "." + methodName;

         map.put("operMethod",methodName);// 请求方法
         // 请求的参数
         Map<String, String> rtnMap = converMap(request.getParameterMap());
         // 将参数所在的数组转换成json
         String params = JSON.toJSONString(rtnMap);
         map.put("params",params);// 请求参数
         map.put("result",JSON.toJSONString(keys));// 返回结果
         map.put("requestURI",request.getRequestURI());// 请求URI
         /**
          * 可以进行入库,只用写个Mapper文件,进行个插入即可;本处只进行打印
          */
         System.out.println("打印操作日志:"+map.toString());
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 /**
  * 异常返回通知,用于拦截异常日志信息 连接点抛出异常后执行
  *
  * @param joinPoint 切入点
  * @param e         异常信息
  */
 @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
 public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
     // 获取RequestAttributes
     RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
     // 从获取RequestAttributes中获取HttpServletRequest的信息
     HttpServletRequest request = (HttpServletRequest) requestAttributes
             .resolveReference(RequestAttributes.REFERENCE_REQUEST);

     Map<String,Object> map = new HashMap<>();
     try {
         // 从切面织入点处通过反射机制获取织入点处的方法
         MethodSignature signature = (MethodSignature) joinPoint.getSignature();
         // 获取切入点所在的方法
         Method method = signature.getMethod();
         map.put("uuid", UUID.randomUUID().toString().replace("-",""));
         // 获取请求的类名
         String className = joinPoint.getTarget().getClass().getName();
         // 获取请求的方法名
         String methodName = method.getName();
         methodName = className + "." + methodName;
         // 请求的参数
         Map<String, String> rtnMap = converMap(request.getParameterMap());
         // 将参数所在的数组转换成json
         String params = JSON.toJSONString(rtnMap);

         map.put("params",params);// 请求参数
         map.put("methodName",methodName);// 请求方法名
         map.put("excName",e.getClass().getName());
         map.put("excMessage",stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));// 异常信息
         map.put("requestURI",request.getRequestURI());// 操作URI
         map.put("excCreateTime",new Date());// 发生异常时间
         /**
          * 可以进行入库,只用写个Mapper文件,进行个插入即可;本处只进行打印
          */
         System.out.println("打印异常日志:"+map.toString());
     } catch (Exception e2) {
         e2.printStackTrace();
     }
 }

 /**
  * 转换request 请求参数
  *
  * @param paramMap request获取的参数数组
  */
 public Map<String, String> converMap(Map<String, String[]> paramMap) {
     Map<String, String> rtnMap = new HashMap<String, String>();
     for (String key : paramMap.keySet()) {
         rtnMap.put(key, paramMap.get(key)[0]);
     }
     return rtnMap;
 }

 /**
  * 转换异常信息为字符串
  *
  * @param exceptionName    异常名称
  * @param exceptionMessage 异常信息
  * @param elements         堆栈信息
  */
 public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
     StringBuffer strbuff = new StringBuffer();
     for (StackTraceElement stet : elements) {
         strbuff.append(stet + "\n");
     }
     String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
     return message;
 }
}

Controller类方法-测试操作日志

方法内没异常,所以没触发异常的操作日志
URI:http://localhost:8080/add?username=zg&password=12

@RequestMapping(value = "/add", name = "haha")
@OperLog(operModul = "测试模块",operType = "ADD",operDesc = "描述测试新增方法")
public String add(String username, String password) {
    return username + ":" + password;
}

打印操作日志:{result=“zg:12”, operDesc=描述测试新增方法, operModul=测试模块, requestURI=/add, operType=ADD, params={“password”:“12”,“username”:“zg”}, uuid=d71454e0b4144d8f9de83e2c1e454d45, operMethod=cn.yx.zg.controller.MvcController.add}


Controller类方法-测试异常日志
URI:http://localhost:8080/add?username=zg&password=12
打印异常日志:{requestURI=/add, params={“password”:“12”,“username”:“zg”}, uuid=b42fe6c905a84450bc1866a93e6739a2, excCreateTime=Wed Jan 12 17:33:15 CST 2022,excMessage=java.lang.ArithmeticException:/ by zerocn.yx.zg.controller.MvcController.add(MvcController.java:30)cn.yx.zg.controller.MvcController F a s t C l a s s B y S p r i n g C G L I B FastClassBySpringCGLIB FastClassBySpringCGLIB330d9f59.invoke()org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)org.springframework.aop.framework.CglibAopProxy C g l i b M e t h o d I n v o c a t i o n . i n v o k e J o i n p o i n t ( C g l i b A o p P r o x y . j a v a : 779 ) o r g . s p r i n g f r a m e w o r k . a o p . f r a m e w o r k . R e f l e c t i v e M e t h o d I n v o c a t i o n . p r o c e e d ( R e f l e c t i v e M e t h o d I n v o c a t i o n . j a v a : 163 ) o r g . s p r i n g f r a m e w o r k . a o p . f r a m e w o r k . C g l i b A o p P r o x y CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:779)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)org.springframework.aop.framework.CglibAopProxy CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:779)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)org.springframework.aop.framework.CglibAopProxyCglibMethodInvocation.proceed(CglibAopProxy.java:750)
org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:64)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
org.springframework.aop.framework.CglibAopProxy C g l i b M e t h o d I n v o c a t i o n . p r o c e e d ( C g l i b A o p P r o x y . j a v a : 750 ) o r g . s p r i n g f r a m e w o r k . a o p . f r a m e w o r k . a d a p t e r . A f t e r R e t u r n i n g A d v i c e I n t e r c e p t o r . i n v o k e ( A f t e r R e t u r n i n g A d v i c e I n t e r c e p t o r . j a v a : 57 ) o r g . s p r i n g f r a m e w o r k . a o p . f r a m e w o r k . R e f l e c t i v e M e t h o d I n v o c a t i o n . p r o c e e d ( R e f l e c t i v e M e t h o d I n v o c a t i o n . j a v a : 175 ) o r g . s p r i n g f r a m e w o r k . a o p . f r a m e w o r k . C g l i b A o p P r o x y CglibMethodInvocation.proceed(CglibAopProxy.java:750)org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:57)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175)org.springframework.aop.framework.CglibAopProxy CglibMethodInvocation.proceed(CglibAopProxy.java:750)org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:57)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175)org.springframework.aop.framework.CglibAopProxyCglibMethodInvocation.proceed(CglibAopProxy.java:750)org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)org.springframework.aop.framework.CglibAopProxy C g l i b M e t h o d I n v o c a t i o n . p r o c e e d ( C g l i b A o p P r o x y . j a v a : 750 ) o r g . s p r i n g f r a m e w o r k . a o p . f r a m e w o r k . C g l i b A o p P r o x y CglibMethodInvocation.proceed(CglibAopProxy.java:750)org.springframework.aop.framework.CglibAopProxy CglibMethodInvocation.proceed(CglibAopProxy.java:750)org.springframework.aop.framework.CglibAopProxyDynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692)cn.yx.zg.controller.MvcController E n h a n c e r B y S p r i n g C G L I B EnhancerBySpringCGLIB EnhancerBySpringCGLIBb06b1cac.add()sun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethod)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:497)org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol C o n n e c t i o n H a n d l e r . p r o c e s s ( A b s t r a c t P r o t o c o l . j a v a : 893 ) o r g . a p a c h e . t o m c a t . u t i l . n e t . N i o E n d p o i n t ConnectionHandler.process(AbstractProtocol.java:893) org.apache.tomcat.util.net.NioEndpoint ConnectionHandler.process(AbstractProtocol.java:893)org.apache.tomcat.util.net.NioEndpointSocketProcessor.doRun(NioEndpoint.java:1707)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor W o r k e r . r u n ( T h r e a d P o o l E x e c u t o r . j a v a : 617 ) o r g . a p a c h e . t o m c a t . u t i l . t h r e a d s . T a s k T h r e a d Worker.run(ThreadPoolExecutor.java:617) org.apache.tomcat.util.threads.TaskThread Worker.run(ThreadPoolExecutor.java:617)org.apache.tomcat.util.threads.TaskThreadWrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
, methodName=cn.yx.zg.controller.MvcController.add, excName=java.lang.ArithmeticException}

你可能感兴趣的:(研究,借鉴,spring,boot,java,spring)