Java使用SpringAop日志处理

1.编写配置 Aspect

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;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperLog {

    /**
     * 操作模块
     *
     * @return
     */
    String module() default "";

    /**
     * 操作类型
     *
     * @return
     */
    String type() default "";

    /**
     * 操作描述
     *
     * @return
     */
    String desc() default "";

    /**
     * id名称,主键名称
     *
     * @return
     */
    String idName() default "id";

    /**
     * 获取更新前数据的service
     *
     * @return
     */
    String beforeUpdateService() default "";
}
import com.alibaba.fastjson.JSON;
import java.lang.reflect.Method;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * OperLogAspect <br>
 *
 * @version 1.0 <br>
 * @since 1.0 <br>
 */
@Slf4j
@Aspect
@Component
public class OperLogAspect {

    @Autowired
    private SysLogOperMapper sysLogOperMapper;

    @Autowired
    private SysLogFailMapper sysLogFailMapper;

    @Autowired
    private LogServiceContext logServiceContext;

    @Around(value = "@annotation(operLog)")
    public Object saveOperLog(ProceedingJoinPoint joinPoint, OperLog operLog) throws Throwable {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
            .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        // 请求的参数
        Object[] args = joinPoint.getArgs();

        SysLogOper sysLogOper = new SysLogOper();

        Object result = null;
        try {

            String logServiceName = operLog.beforeUpdateService();
            if (StringUtils.isNotBlank(logServiceName)) {
                ILogService logService = logServiceContext.getLogService(logServiceName);
                if (logService != null) {
                    Map<String, Object> valueMap = JsonUtil.convertToMap(args[0]);
                    String beforeUpdate = logService.getBeforeUpdate(String.valueOf(valueMap.get(operLog.idName())));
                    if (StringUtils.isNotBlank(beforeUpdate)) {
                        sysLogOper.setOperBeforeUpdate(beforeUpdate);
                    }
                }
            }

            result = joinPoint.proceed(args);
        } catch (Throwable t) {
            sysLogOper.setFailMessage(stackTraceToString(t.getClass().getName(), t.getMessage(), t.getStackTrace()));
            sysLogOper.setStatus(LogStatus.EXCEPTION.getCode());

            throw t;
        } finally {
            sysLogOper.setOperModule(operLog.module());
            sysLogOper.setOperType(operLog.type());
            sysLogOper.setOperDesc(operLog.desc());

            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();

            // 获取请求的方法名
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            String methodName = className + "." + method.getName();
            sysLogOper.setOperMethod(methodName);

            // 请求的参数
            if (args != null) {
                sysLogOper.setOperRequest(JSON.toJSONString(args));
            }

            if (result != null) {
                sysLogOper.setOperResponse(JSON.toJSONString(result));
            }

            sysLogOper.setOperUserId(SecurityUtils.getLoginUserId());
            sysLogOper.setOperIp(IpUtil.getIpAddress(request));
            sysLogOper.setOperUri(request.getRequestURI());

            sysLogOperMapper.insert(sysLogOper);
        }

        return result;
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName 异常名称
     * @param exceptionMessage 异常信息
     * @param elements 堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }
}

3.在 Controller添加注解

 @OperLog(module = "xxx管理", type = "update", desc = "更新")

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值