使用切面在controller层记录操作日志

日志切面

package com.feedback.service.common.aop.log;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 日志aop
 */
@Slf4j
@Aspect
@Component
public class LogAop {

    @Resource
    private OperationLogClient operationLogClient;

    @Value("${spring.application.name}")
    private String applicationName;


    @Pointcut(value = "@annotation(com.haier.hopm.feedback.api.common.annotations.Log)")
    public void cutService() {
    }

    @Around("cutService()")
    public Object recordSysLog(ProceedingJoinPoint point) throws Throwable {
        long startTime = System.currentTimeMillis();
        //先执行业务
        Object result = point.proceed();
        long endTime = System.currentTimeMillis();
        try {
            handle(point, endTime - startTime, UserUtil.getUserInfo(), JSONUtil.toJsonStr(result), null);
        } catch (Exception e) {
            log.error("日志记录出错!", e);
        }
        return result;
    }

    @AfterThrowing(pointcut = "cutService()", throwing = "e")
    public void doAfterThrowing(JoinPoint point, Throwable e) {
        try {
            handle(point, null, UserUtil.getUserInfo(), null, e);
        } catch (Exception ex) {
            log.error("日志记录出错!", ex);
        }
    }

    private void handle(JoinPoint point, Long methodProcessTime, SysUserDTO sysUserDTO, String outParamStr, Throwable e) throws Exception {
        //获取拦截的方法名
        Signature sig = point.getSignature();
        MethodSignature msig = null;
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        msig = (MethodSignature) sig;
        Object target = point.getTarget();
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        String methodName = currentMethod.getName();
        //获取拦截方法的参数
        Object[] params = point.getArgs();
        //获取操作名称
        Log annotation = currentMethod.getAnnotation(Log.class);
        String moduleName = annotation.moduleName();
        String operationName = annotation.value();
        OperationLogDTO operationLog = new OperationLogDTO();
        operationLog.setModuleName(applicationName);
        operationLog.setOperationName(operationName);
        operationLog.setMethodName(methodName);
        //sysLog.setParams(Arrays.toString(params));
        operationLog.setParamJson(JSONUtil.toJsonStr(params));
        operationLog.setResultJson(outParamStr);
        operationLog.setTime(methodProcessTime);
        operationLog.setRequestUrl(RequestContextHolderUtil.requestUrl());
        operationLog.setRequestMethod(RequestContextHolderUtil.requestMethod());
        operationLog.setUserAgent(RequestContextHolderUtil.getUserAgent());
        operationLog.setIp(RequestContextHolderUtil.getRemoteAddr());
        operationLog.setSuccess(Boolean.TRUE);
        operationLog.setCreateTime(new Date());
        if (sysUserDTO != null) {
            operationLog.setCreateBy(sysUserDTO.getUserAccount());
            operationLog.setCreateByName(sysUserDTO.getUserName());
        }
        if (e != null) {
            operationLog.setSuccess(Boolean.FALSE);
            operationLog.setErrorMsg(ExceptionUtil.getMessage(e));
        }
        operationLogClient.save(operationLog);
    }

}

日志注解

package com.feedback.api.common.annotations;

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;

/**
 * 系统日志注解
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Log {
    String value() default "";

    String moduleName() default "";

}

保存日志实体类

package com.feedback.api.dto;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value = "OperationLogDTO", description = "系统操作日志表")
public class OperationLogDTO extends BaseDTO {

    @ApiModelProperty(value = "操作名称")
    private String operationName;

    @ApiModelProperty(value = "方法名称")
    private String methodName;

    @ApiModelProperty(value = "微服务名称")
    private String moduleName;

    @ApiModelProperty(value = "成功失败标记:0-失败;1-成功")
    private Boolean success;

    @ApiModelProperty(value = "请求参数")
    private String paramJson;

    @ApiModelProperty(value = "返回参数")
    private String resultJson;


    @ApiModelProperty(value = "异常信息")
    private String errorMsg;


    @ApiModelProperty(value = "执行时长(毫秒)")
    private Long time;


    @ApiModelProperty(value = "IP地址")
    private String ip;

    @ApiModelProperty(value = "请求地址")
    private String requestUrl;


    @ApiModelProperty(value = "请求方法")
    private String requestMethod;


    @ApiModelProperty(value = "浏览器信息")
    private String userAgent;


    @ApiModelProperty(value = "创建人姓名")
    protected String createByName;


}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值