美文网首页
springboot AOP自定义注解日志

springboot AOP自定义注解日志

作者: lowkey港 | 来源:发表于2020-12-06 16:23 被阅读0次

1.导包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

2.相关枚举
a.业务操作类型

package com.kc.framework.aspectj.lang.enums;

/**
 * 业务操作类型
 * 
 * @author hunter
 *
 */
public enum BusinessType
{
     /**
     * 其它
     */
    OTHER,

    /**
     * 新增
     */
    INSERT,

    /**
     * 修改
     */
    UPDATE,

    /**
     * 删除
     */
    DELETE,

    /**
     * 授权
     */
    GRANT,

    /**
     * 导出
     */
    EXPORT,

    /**
     * 导入
     */
    IMPORT,
    /**
     * 查询
     */
    QUERY,
    /**
     * 统计
     */
    STAT,
    /**
     * 打印
     */
    PRINT,
    /**
     * 检索
     */
    FIND,
    /**
     * 返回
     */
    BACK,
    /**
     * 重置
     */
    RESET,
    /**
     * 上传
     */
    UPLOAD,
    /**
     * 刷新
     */
    REFRESH,
}

b.操作人类别

package com.kc.framework.aspectj.lang.enums;

/**
 * 操作人类别
 * 
 * @author hunter
 *
 */
public enum OperatorType
{
    /**
     * 其它
     */
    OTHER,

    /**
     * 后台用户
     */
    MANAGE,

    /**
     * 手机端用户
     */
    MOBILE
}

3.自定义注解

package com.kc.framework.aspectj.lang.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.kc.framework.aspectj.lang.enums.BusinessType;
import com.kc.framework.aspectj.lang.enums.OperatorType;

/**
 * @ClassName interface 
 * @Description 自定义操作日志记录注解
 * @Author HuGang 1042258937@qq.com
 * @Date 2020/7/2 9:40
 * @Version 1.0
 */
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log
{
    /**
     * 模块 
     */
    public String title() default "";

    /**
     * 功能
     */
    public BusinessType businessType() default BusinessType.OTHER;

    /**
     * 操作人类别
     */
    public OperatorType operatorType() default OperatorType.MANAGE;

    /**
     * 是否保存请求的参数
     */
    public boolean isSaveRequestData() default true;
    
    /**
     * 是否保存返回的参数
     * @return
     */
    public boolean isSaveResponseData() default true;

    /**
     * 自定义日志内容
     * @return
     */
    String msg() default "";
}

4.日志实体类

@Excel导出注解不需要的自己可以删除

a.创建表结构

-- Create table
create table T_FJGL_OPER_LOG
(
  oper_id        VARCHAR2(32) default sys_guid() not null,
  title          VARCHAR2(50),
  business_type  NUMBER default 0,
  method         VARCHAR2(128),
  operator_type  NUMBER default 0,
  oper_name      VARCHAR2(50),
  dept_id        VARCHAR2(12),
  dept_name      VARCHAR2(50),
  oper_url       VARCHAR2(256),
  oper_ip        VARCHAR2(50),
  oper_location  VARCHAR2(256),
  oper_param     VARCHAR2(2048),
  status         NUMBER default 0,
  error_msg      VARCHAR2(4000),
  request_method VARCHAR2(16),
  json_result    VARCHAR2(4000),
  oper_time      DATE,
  msg            VARCHAR2(4000)
)
tablespace FJ_DATA
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );
-- Add comments to the table 
comment on table T_FJGL_OPER_LOG
  is '操作日志记录';
-- Add comments to the columns 
comment on column T_FJGL_OPER_LOG.oper_id
  is '日志主键';
comment on column T_FJGL_OPER_LOG.title
  is '模块标题';
comment on column T_FJGL_OPER_LOG.business_type
  is '业务类型(0其它 1新增 2修改 3删除)';
comment on column T_FJGL_OPER_LOG.method
  is '方法名称';
comment on column T_FJGL_OPER_LOG.operator_type
  is '操作类别(0其它 1后台用户 2手机端用户)';
comment on column T_FJGL_OPER_LOG.oper_name
  is '操作人员';
comment on column T_FJGL_OPER_LOG.dept_id
  is '部门编号';
comment on column T_FJGL_OPER_LOG.dept_name
  is '部门名称';
comment on column T_FJGL_OPER_LOG.oper_url
  is '请求URL';
comment on column T_FJGL_OPER_LOG.oper_ip
  is '主机地址';
comment on column T_FJGL_OPER_LOG.oper_location
  is '操作地点';
comment on column T_FJGL_OPER_LOG.oper_param
  is '请求参数';
comment on column T_FJGL_OPER_LOG.status
  is '操作状态(0正常 1异常)';
comment on column T_FJGL_OPER_LOG.error_msg
  is '错误消息';
comment on column T_FJGL_OPER_LOG.request_method
  is '请求方式';
comment on column T_FJGL_OPER_LOG.json_result
  is '返回结果';
comment on column T_FJGL_OPER_LOG.oper_time
  is '操作时间';
comment on column T_FJGL_OPER_LOG.msg
  is '自定义日志信息';
-- Create/Recreate indexes 
create index IDX_FJGL_OPER_LOG_OPER_TIME on T_FJGL_OPER_LOG (OPER_TIME)
  tablespace FJ_INDEX
  pctfree 10
  initrans 2
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );
-- Create/Recreate primary, unique and foreign key constraints 
alter table T_FJGL_OPER_LOG
  add constraint PK_FJGL_OPER_LOG_ID primary key (OPER_ID)
  using index 
  tablespace FJ_DATA
  pctfree 10
  initrans 2
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );

b.创建实体

package com.kc.project.entity;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.kc.framework.aspectj.lang.annotation.Excel;
import com.kc.framework.web.domain.BaseEntity;

/**
 * 操作日志记录表 oper_log
 * 
 * @author hunter
 */
public class OperLog extends BaseEntity
{
    private static final long serialVersionUID = 1L;

    /** 日志主键 */
    @Excel(name = "操作编号",width = 35,height=25)
    private String operId;

    /** 操作模块 */
    @Excel(name = "操作模块",height=25)
    private String title;

    /** 操作业务类型 */
    @Excel(name = "业务类型",height=25, readConverterExp = "0=其它,1=新增,2=修改,3=删除,4=授权,5=导出,6=导入,7=强退,8=生成代码,9=清空数据")
    private Integer businessType;

    /** 业务类型数组 */
    private Integer[] businessTypes;
    
    /** 请求方法 */
    @Excel(name = "请求方法",height=25)
    private String method;
    
    /** 请求方式 */
    @Excel(name = "请求方式")
    private String requestMethod;

    /** 操作人类别 */
    @Excel(name = "操作类别",height=25, readConverterExp = "0=其它,1=后台用户,2=手机端用户")
    private Integer operatorType;

    /** 操作人员 */
    @Excel(name = "操作人员",height=25)
    private String operName;
    
    /** 部门ID */
    private String deptId;

    /** 部门名称 */
    @Excel(name = "部门名称",height=25)
    private String deptName="未知部门";

    /** 请求url */
    @Excel(name = "请求地址",height=25)
    private String operUrl;

    /** 操作地址 */
    @Excel(name = "操作地址",height=25)
    private String operIp;

    /** 操作地点 */
    @Excel(name = "操作地点",height=25)
    private String operLocation;

    /** 请求参数 */
    @Excel(name = "请求参数",height=25)
    private String operParam;

    /** 返回参数 */
    @Excel(name = "返回参数")
    private String jsonResult;
    
    /** 状态0正常 1异常 */
    @Excel(name = "状态", readConverterExp = "0=正常,1=异常",height=25)
    private Integer status;

    /** 错误消息 */
    @Excel(name = "错误消息",height=25)
    private String errorMsg;

    /** 操作时间 */
    @Excel(name = "操作时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss",height=25)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date operTime;

    /** 自定义日志内容 */
    @Excel(name = "自定义日志内容",height=25)
    private String msg;

    public String getOperId()
    {
        return operId;
    }

    public void setOperId(String operId)
    {
        this.operId = operId;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public Integer getBusinessType()
    {
        return businessType;
    }

    public void setBusinessType(Integer businessType)
    {
        this.businessType = businessType;
    }

    public Integer[] getBusinessTypes() {
        return businessTypes;
    }

    public void setBusinessTypes(Integer[] businessTypes) {
        this.businessTypes = businessTypes;
    }

    public String getMethod()
    {
        return method;
    }

    public void setMethod(String method)
    {
        this.method = method;
    }

    public Integer getOperatorType()
    {
        return operatorType;
    }

    public void setOperatorType(Integer operatorType)
    {
        this.operatorType = operatorType;
    }

    public String getOperName()
    {
        return operName;
    }

    public void setOperName(String operName)
    {
        this.operName = operName;
    }
    
    public String getDeptId() {
        return deptId;
    }

    public void setDeptId(String deptId) {
        this.deptId = deptId;
    }
    
    public String getDeptName()
    {
        return deptName;
    }

    public void setDeptName(String deptName)
    {
        this.deptName = deptName;
    }

    public String getOperUrl()
    {
        return operUrl;
    }

    public void setOperUrl(String operUrl)
    {
        this.operUrl = operUrl;
    }

    public String getOperIp()
    {
        return operIp;
    }

    public void setOperIp(String operIp)
    {
        this.operIp = operIp;
    }

    public String getOperLocation()
    {
        return operLocation;
    }

    public void setOperLocation(String operLocation)
    {
        this.operLocation = operLocation;
    }

    public String getOperParam()
    {
        return operParam;
    }

    public void setOperParam(String operParam)
    {
        this.operParam = operParam;
    }

    public Integer getStatus()
    {
        return status;
    }

    public void setStatus(Integer status)
    {
        this.status = status;
    }

    public String getErrorMsg()
    {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg)
    {
        this.errorMsg = errorMsg;
    }

    public Date getOperTime()
    {
        return operTime;
    }

    public void setOperTime(Date operTime)
    {
        this.operTime = operTime;
    }
    
    public String getRequestMethod() {
        return requestMethod;
    }

    public void setRequestMethod(String requestMethod) {
        this.requestMethod = requestMethod;
    }

    public String getJsonResult() {
        return jsonResult;
    }

    public void setJsonResult(String jsonResult) {
        this.jsonResult = jsonResult;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
        public String toString() {
            return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
                .append("operId", getOperId())
                .append("title", getTitle())
                .append("businessType", getBusinessType())
                .append("businessTypes", getBusinessTypes())
                .append("method", getMethod())
                .append("requestMethod", getRequestMethod())
                .append("operatorType", getOperatorType())
                .append("operName", getOperName())
                .append("deptName", getDeptName())
                .append("operUrl", getOperUrl())
                .append("operIp", getOperIp())
                .append("operLocation", getOperLocation())
                .append("operParam", getOperParam())
                .append("status", getStatus())
                .append("errorMsg", getErrorMsg())
                .append("operTime", getOperTime())
                    .append("msg", getMsg())
                .toString();
        }
}

5.自定义修改注解类 LogUtils

package com.kc.common.utils.log;

import com.kc.common.constant.LogConstants;
import com.kc.framework.aspectj.lang.annotation.Log;

/**
 * @ClassName LogUtils
 * @Description TODO
 * @Author HuGang 1042258937@qq.com
 * @Date 2020/7/2 9:40
 * @Version 1.0
 */
public class LogUtils {

    private static LogUtils mInstance;

    private LogUtils() {
    }

    public static LogUtils get() {
        if (mInstance == null) {
            synchronized (LogUtils.class) {
                if (mInstance == null) {
                    mInstance = new LogUtils();
                }
            }
        }
        return mInstance;
    }

    public void setLog(String msg) {
        String className = Thread.currentThread().getStackTrace()[2].getClassName();
        String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
        AnnotationUtils.get().setAnnotatioinFieldValue(className, methodName, Log.class.getName(), LogConstants.MSG, msg);
    }
}

6.异步任务管理器 AsyncManager

package com.kc.framework.manager;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.kc.common.utils.Threads;
import com.kc.common.utils.spring.SpringUtils;

/**
 * 异步任务管理器
 * 
 * @author Hunter
 */
public class AsyncManager
{
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 异步操作任务调度线程池
     */
    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");

    /**
     * 单例模式
     */
    private static AsyncManager me = new AsyncManager();

    public static AsyncManager me(){
        return me;
    }

    /**
     * 执行任务
     * 
     * @param task 任务
     */
    public void execute(TimerTask task){
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown(){
        Threads.shutdownAndAwaitTermination(executor);
    }
}

7.AOP切点类

package com.kc.framework.aspectj;

import java.lang.reflect.Method;
import java.util.Map;

import com.kc.common.constant.LogConstants;
import com.kc.common.utils.log.AnnotationUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.kc.common.utils.ServletUtils;
import com.kc.common.utils.StringUtils;
import com.kc.common.utils.security.ShiroUtils;
import com.kc.framework.aspectj.lang.annotation.Log;
import com.kc.framework.aspectj.lang.enums.BusinessStatus;
import com.kc.framework.manager.AsyncManager;
import com.kc.framework.manager.factory.AsyncFactory;

import com.kc.project.entity.OperLog;
import com.kc.project.entity.User;

/**
 * 操作日志记录处理
 * 
 * @author Hunter
 */
@Aspect
@Component
public class LogAspect{
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    // 配置织入点
    @Pointcut("@annotation(com.kc.framework.aspectj.lang.annotation.Log)")
    public void logPointCut()
    {
    }

    /**
     * 前置通知 用于拦截操作
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doBefore(JoinPoint joinPoint, Object jsonResult){
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     * 
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e){
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult){
        try{
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null){
                return;
            }

            // 获取当前的用户
            User currentUser = ShiroUtils.getSysUser();

            // *========数据库日志=========*//
            OperLog operLog = new OperLog();

            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            String msg = AnnotationUtils.get().getAnnotatioinFieldValue(className, methodName, Log.class.getName(), LogConstants.MSG);
            operLog.setMsg(msg);

            operLog.setOperName("匿名");
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            // 请求的地址
            String ip = ShiroUtils.getIp();
            operLog.setOperIp(ip);
            // 返回参数
            if(controllerLog.isSaveResponseData())
                operLog.setJsonResult(JSONObject.toJSONString(jsonResult));
            
            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
            if (currentUser != null){
                operLog.setOperName(currentUser.getName());
                if (StringUtils.isNotNull(currentUser.getDeptName())
                        && StringUtils.isNotEmpty(currentUser.getDeptName()))
                {
                    operLog.setDeptName(currentUser.getDeptName());
                    operLog.setDeptId(currentUser.getDeptId());
                }
            }

            if (e != null){
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            operLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(controllerLog, operLog);
            // 保存数据库
            AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
        }catch (Exception exp){
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     * 
     * @param log 日志
     * @param operLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(Log log, OperLog operLog) throws Exception{
        // 设置action动作
        operLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperatorType(log.operatorType().ordinal());
        // 是否需要保存request,参数和值
        if (log.isSaveRequestData())
        {
            // 获取参数的信息,传入到数据库中。
            setRequestValue(operLog);
        }
    }

    /**
     * 获取请求的参数,放到log中
     * 
     * @param operLog
     * @param request
     */
    private void setRequestValue(OperLog operLog){
        Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
        String params = JSONObject.toJSONString(map);
        operLog.setOperParam(StringUtils.substring(params, 0, 2000));
    }

    /**
     * 是否存在注解,如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) throws Exception{
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null){
            return method.getAnnotation(Log.class);
        }
        return null;
    }
}

8.使用时添加注解


image.png

效果


image.png
image.png

相关文章

网友评论

      本文标题:springboot AOP自定义注解日志

      本文链接:https://www.haomeiwen.com/subject/pebowktx.html