Spring Boot 使用AOP切面实现后台日志管理模块

设计原则和思路:

  • 元注解方式结合AOP,灵活记录操作日志
  • 能够记录详细错误日志为运维提供支持
  • 日志记录尽可能减少性能影响

1.定义日志记录元注解

Spring Boot 使用AOP切面实现后台日志管理模块_第1张图片

Spring Boot 使用AOP切面实现后台日志管理模块_第2张图片

2.定义用于记录日志的实体类

import java.io.Serializable;
import com.leon.common.util.StringUtils;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
import java.util.Map;

/**
 * 日志类-记录用户操作行为
 * @author lin.r.x
 *
 */
public class Log implements Serializable{
    private static final long serialVersionUID = 1L;

    private String logId;           //日志主键  
    private String type;            //日志类型  
    private String title;           //日志标题  
    private String remoteAddr;          //请求地址  
    private String requestUri;          //URI   
    private String method;          //请求方式  
    private String params;          //提交参数  
    private String exception;           //异常    
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date operateDate;           //开始时间  
    private String timeout;         //结束时间  
    private String userId;          //用户ID  
    private String resultParams;    //返回参数

    public String getLogId() {
        return StringUtils.isBlank(logId) ? logId : logId.trim();
    }
    public void setLogId(String logId) {
        this.logId = logId;
    }
     public String getResultParams() {
        return resultParams;
    }
    public void setResultParams(String resultParams) {
        this.resultParams = resultParams;
    }

    public String getType() {
        return StringUtils.isBlank(type) ? type : type.trim();
    }
    public void setType(String type) {
        this.type = type;
    }


    public String getTitle() {
        return StringUtils.isBlank(title) ? title : title.trim();
    }
    public void setTitle(String title) {
        this.title = title;
    }


    public String getRemoteAddr() {
        return StringUtils.isBlank(remoteAddr) ? remoteAddr : remoteAddr.trim();
    }
    public void setRemoteAddr(String remoteAddr) {
        this.remoteAddr = remoteAddr;
    }


    public String getRequestUri() {
        return StringUtils.isBlank(requestUri) ? requestUri : requestUri.trim();
    }
    public void setRequestUri(String requestUri) {
        this.requestUri = requestUri;
    }


    public String getMethod() {
        return StringUtils.isBlank(method) ? method : method.trim();
    }
    public void setMethod(String method) {
        this.method = method;
    }


    public String getParams() {
        return StringUtils.isBlank(params) ? params : params.trim();
    }
    public void setParams(String params) {
        this.params = params;
    }

    /**
     * 设置请求参数
     * @param paramMap
     */
    public void setMapToParams(Map paramMap) {
        if (paramMap == null){
            return;
        }
        StringBuilder params = new StringBuilder();
        for (Map.Entry param : ((Map)paramMap).entrySet()){
            params.append(("".equals(params.toString()) ? "" : "&") + param.getKey() + "=");
            String paramValue = (param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : "");
            params.append(StringUtils.abbr(StringUtils.endsWithIgnoreCase(param.getKey(), "password") ? "" : paramValue, 100));
        }
        this.params = params.toString();
    }


    public String getException() {
        return StringUtils.isBlank(exception) ? exception : exception.trim();
    }
    public void setException(String exception) {
        this.exception = exception;
    }


    public Date getOperateDate() {
        return operateDate;
    }
    public void setOperateDate(Date operateDate) {
        this.operateDate = operateDate;
    }


    public String getTimeout() {
        return StringUtils.isBlank(timeout) ? timeout : timeout.trim();
    }
    public void setTimeout(String timeout) {
        this.timeout = timeout;
    }


    public String getUserId() {
        return StringUtils.isBlank(userId) ? userId : userId.trim();
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }

}

工具类代码:

Spring Boot 使用AOP切面实现后台日志管理模块_第3张图片

3.定义日志AOP切面类(日志新增及修改其它业务操作不做介绍):

package com.isoftstone.api.common.log.aspect;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import com.isoftstone.api.common.config.security.UserUtils;
import com.isoftstone.api.common.log.target.SystemControllerLog;
import com.isoftstone.api.common.log.target.SystemServiceLog;
import com.isoftstone.api.common.log.utils.DateUtils;
import com.isoftstone.api.common.log.utils.UuidUtils;
import com.isoftstone.api.common.utils.JsonUtils;
import com.isoftstone.api.common.utils.redis.RedisUtil;
import com.isoftstone.api.log.entity.Log;
import com.isoftstone.api.log.service.LogService;
import com.isoftstone.api.system.entity.Users;


/**
* @author leon
* @createDate 2018年6月6日 上午10:33:35
* @version v1.0
* @classRemarks 日志切面类
*/
@Aspect
@Component
public class SystemLogAspect {
    
    private static Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
    
    private static final ThreadLocal beginTimeThreadLocal = new NamedThreadLocal("ThreadLocal beginTime");
    private static final ThreadLocal logThreadLocal =  new NamedThreadLocal("ThreadLocal log");

    private static final ThreadLocal currentUser=new NamedThreadLocal<>("ThreadLocal user");
    
    @Autowired(required=false)
    HttpServletRequest request;

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;
    
    @Autowired
    LogService logService;
    
    @Autowired
    RedisUtil redisUtil;
    
    /**
     * Service层切点
     */
    @Pointcut("@annotation(com.isoftstone.api.common.log.target.SystemServiceLog)")
    public void serviceAspect(){}
    
    /**
     * Controller层切点 注解拦截
     */
    @Pointcut("@annotation(com.isoftstone.api.common.log.target.SystemControllerLog)")
    public void controllerAspect(){}
    
    /*@Pointcut("execution(* com.isoftstone.api.*.controller.*.*(..))")
    public void controllerPointerCut(){}*/

    /**
     * 前置通知 用于拦截Controller层记录用户的操作的开始时间
     * @param joinPoint 切点
     * @throws InterruptedException
     */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) throws InterruptedException{
        
        logger.info("进入日志切面前置通知!!");
        Date beginTime=new Date();
        beginTimeThreadLocal.set(beginTime);//线程绑定变量(该数据只有当前请求的线程可见)  
        if (logger.isDebugEnabled()){//这里日志级别为debug
            logger.debug("开始计时: {}  URI: {}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
                .format(beginTime), request.getRequestURI());
        }

        //读取session中的用户
        /*HttpSession session = request.getSession();       
        Users user = (Users) session.getAttribute("ims_user"); */   
        Users user=UserUtils.getUser(redisUtil);
        currentUser.set(user);

    }

    /**
     * 后置通知 用于拦截Controller层记录用户的操作
     * @param joinPoint 切点
     */
    @After("controllerAspect()")
    public void doAfter(JoinPoint joinPoint) {
        logger.info("进入日志切面后置通知!!");
        Users user = currentUser.get();
        if(user !=null){
            String title="";
            String type="info";                       //日志类型(info:入库,error:错误)
            String remoteAddr=request.getRemoteAddr();//请求的IP
            String requestUri=request.getRequestURI();//请求的Uri
            String method=request.getMethod();        //请求的方法类型(post/get)
            Map params=request.getParameterMap(); //请求提交的参数
            
            try {
                title=getControllerMethodDescription2(joinPoint);
            } catch (Exception e) {
                e.printStackTrace();
            }    
            // 打印JVM信息。
            long beginTime = beginTimeThreadLocal.get().getTime();//得到线程绑定的局部变量(开始时间)  
            long endTime = System.currentTimeMillis();  //2、结束时间  
            if (logger.isDebugEnabled()){
                logger.debug("计时结束:{}  URI: {}  耗时: {}   最大内存: {}m  已分配内存: {}m  已分配内存中的剩余空间: {}m  最大可用内存: {}m",
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(endTime),
                        request.getRequestURI(),
                        DateUtils.formatDateTime(endTime - beginTime),
                        Runtime.getRuntime().maxMemory()/1024/1024,
                        Runtime.getRuntime().totalMemory()/1024/1024,
                        Runtime.getRuntime().freeMemory()/1024/1024,
                        (Runtime.getRuntime().maxMemory()-Runtime.getRuntime().totalMemory()+Runtime.getRuntime().freeMemory())/1024/1024);
            }
            logger.info("设置日志信息存储到表中!!");
            Log log=new Log();
            log.setLogId(UuidUtils.creatUUID());
            log.setTitle(title);
            log.setType(type);
            log.setRemoteAddr(remoteAddr);
            log.setRequestUri(requestUri);
            log.setMethod(method);
            log.setMapToParams(params);
            log.setException("无异常!");
            log.setUserId(user.getUsername());
            Date operateDate=beginTimeThreadLocal.get();
            log.setOperateDate(operateDate);
            log.setTimeout(DateUtils.formatDateTime(endTime - beginTime));

            //1.直接执行保存操作
            //this.logService.addLog(log);

            //2.优化:异步保存日志
            //new SaveLogThread(log, logService).start();

            //3.再优化:通过线程池来执行日志保存
            threadPoolTaskExecutor.execute(new SaveLogThread(log, logService));
            logThreadLocal.set(log);
        }

    }
    
    @AfterReturning(returning = "res", pointcut = "controllerAspect()")
    public void doAfterReturning(Object res) throws Throwable {
        // 处理完请求,返回内容
        logger.info("==========返回参数日志=========");
        logger.info("返回接口响应参数:"+JsonUtils.obj2JSON(res));
        Log log = logThreadLocal.get();
        if (log!=null) {
            log.setResultParams(JsonUtils.obj2JSON(res));
            logger.info("==========更新日志参数=========");
            new UpdateLogThread(log, logService).start();
        }
    }

    /**
     *  异常通知 记录操作报错日志
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(pointcut = "controllerAspect()", throwing = "e")  
    public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        logger.info("进入日志切面异常通知!!");
        logger.info("异常信息:"+e.getMessage());
        Log log = logThreadLocal.get();
        if (log!=null) {
            log.setType("error");
            log.setException(e.toString());
            new UpdateLogThread(log, logService).start();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于service层注解
     * @param joinPoint切点
     * @return discription
     */
    public static String getServiceMthodDescription2(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SystemServiceLog serviceLog = method.getAnnotation(SystemServiceLog.class);
        String discription = serviceLog.description();
        return discription;
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint 切点
     * @return discription
     */
    public static String getControllerMethodDescription2(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SystemControllerLog controllerLog = method.getAnnotation(SystemControllerLog.class);
        String discription = controllerLog.description();
        return discription;
    }

    /**
     * 保存日志线程
     */
    private static class SaveLogThread implements Runnable {
        private Log log;
        private LogService logService;

        public SaveLogThread(Log log, LogService logService) {
            this.log = log;
            this.logService = logService;
        }

        @Override
        public void run() {
            logService.addLog(log);
        }
    }

    /**
     * 日志更新线程
     */
    private static class UpdateLogThread extends Thread {
        private Log log;
        private LogService logService;

        public UpdateLogThread(Log log, LogService logService) {
            super(UpdateLogThread.class.getSimpleName());
            this.log = log;
            this.logService = logService;
        }

        @Override
        public void run() {
            this.logService.putLog(log);
        }
    }


}

线程池配置代码:

package com.isoftstone.api.common.log.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
* @author leon
* @createDate 2018年6月6日 上午11:23:22
* @version v1.0
* @classRemarks 线程池配置
*/

@Configuration
@ConfigurationProperties(prefix="threadpool")
public class ExecutePoolConfiguration {
    
    private static Logger logger = LoggerFactory.getLogger(ExecutePoolConfiguration.class);

    /**
     * application.yml 配置方式
        threadpool:
          core-pool-size: 10
          max-pool-size: 20
          queue-capacity: 1000
          keep-alive-seconds: 300
     */
    @Value("${threadpool.core-pool-size}")
    private int corePoolSize;

    @Value("${threadpool.max-pool-size}")
    private int maxPoolSize;

    @Value("${threadpool.queue-capacity}")
    private int queueCapacity;

    @Value("${threadpool.keep-alive-seconds}")
    private int keepAliveSeconds;


    @Bean(name="threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setKeepAliveSeconds(keepAliveSeconds);
        pool.setCorePoolSize(corePoolSize);//核心线程池数
        pool.setMaxPoolSize(maxPoolSize); // 最大线程
        pool.setQueueCapacity(queueCapacity);//队列容量
        pool.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy()); //队列满,线程被拒绝执行策略
        return pool;
    }

}

属性文件中添加下列配置:

Spring Boot 使用AOP切面实现后台日志管理模块_第4张图片

4.spring boot配置扫描切面,开启@AspectJ注解的支持

Spring Boot 使用AOP切面实现后台日志管理模块_第5张图片

5.使用范例LoginController方法中添加日志注解

Spring Boot 使用AOP切面实现后台日志管理模块_第6张图片

6.运行效果

Spring Boot 使用AOP切面实现后台日志管理模块_第7张图片

你可能感兴趣的:(#,Java基础,#,spring,boot,#,Spring,boot学习与项目实践)