• 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

  • 相关阅读:
    生活的真谛
    WSDL文件简介(附例子)
    关于智慧
    叔叔的去世
    google labs
    项目需求工具
    agent/angel/angle
    关于地图投影的C程序的一些说明
    Ubuntu下开启Apache重写扩展
    PHP内置函数之ctype_alnum() 函数检查字符串是否由字符和数字组成
  • 原文地址:https://www.cnblogs.com/angin-iit/p/10401483.html
Copyright © 2020-2023  润新知