zoukankan      html  css  js  c++  java
  • Springboot项目使用aop添加日志

    @Aspect
    @Component
    public class Log {
        private static Logger logger = LogManager.getLogger(Log.class);
        private String method;
        private String ip;
        private int port;
        private String host;
        private String url;
    
        /**
         * 定义切入点
         */
        @Pointcut("execution(public * com.angin.iit.controller..*.*(..))")
        public void log() {
        }
    
        /**
         * 执行方法前 获取client参数
         *
         * @param joinPoint
         */
        @Before("log()")
        public void doBefore(JoinPoint joinPoint) {
            //取到request
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            ip = request.getRemoteAddr();//客户端ip
            host = request.getRemoteHost();//客户端主机
            method = request.getMethod();//客户端请求方法
            port = request.getRemotePort();//客户端请求port
            url=request.getRequestURL().toString();//请求url
            //记录client信息
            logger.info("client:ip=" + ip + ";host=" + host + ";method=" + method + ";port=" + port+";url="+url);
            //类名
            String classname = joinPoint.getTarget().getClass().getSimpleName();
            //方法名
            String methodName = joinPoint.getSignature().getName();
            //参数
            List<Object> args = Arrays.asList(joinPoint.getArgs());
            String paraJsonString = JSON.toJSONString(args, SerializerFeature.DisableCircularReferenceDetect);
            //日志记录 类 方法 参数
            logger.info("class name: " + classname + ", method name: " + methodName + ";parameters: " + paraJsonString);
        }
    
        /**
         * 方法执行
         *
         * @param proceedingJoinPoint
         * @return
         * @throws Throwable
         */
        @Around("log()")
        public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            Object obj = proceedingJoinPoint.proceed();
            logger.info("return:" + obj);
            return obj;
        }
    
        /**
         * 异常处理
         *
         * @param e
         */
        @AfterThrowing(pointcut = "log()", throwing = "e")
        public void doException(Throwable e) {
            if (e != null) {
                logger.error("doException系统异常:" + e.getMessage(), e);
            }
        }

    之前记录日志的时候,都是在controller里 每个方法中添加,使用aop 节约了很多时间,而且维护起来更方便。

    找到那个感觉 就算打开了那个脑洞

    本文来自博客园,作者:xiao~xiao,转载请注明原文链接:https://www.cnblogs.com/angin-iit/p/10401483.html

  • 相关阅读:
    Shiro理解与总结
    spark教程(14)-共享变量
    Hive 教程(十)-UDF
    multivariate_normal 多元正态分布
    windows 安装 python 踩坑记录
    EM 算法(三)-GMM
    EM 算法(二)-KMeans
    EM 算法(一)-原理
    sklearn-GDBT
    集成学习-Boosting 模型深度串讲
  • 原文地址:https://www.cnblogs.com/angin-iit/p/10401483.html
Copyright © 2011-2022 走看看