springboot 日志模块

OperLog.java

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;

/**
 * 自定义操作日志注解
 * @author lkj
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperLog {
    String operModul() default ""; // 操作模块
    String operType() default "";  // 操作类型
    String operDesc() default "";  // 操作说明
}

OperLogAspect.java

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import xxx.xxx.xxx.commons.OprLogConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * 切面处理类,操作日志异常日志记录处理
 *
 * @author wu
 * @date 2019/03/21
 */
@Aspect
@Component
@Slf4j
public class OperLogAspect {

    @Autowired
    LogService logService;

    @Autowired
    UserService userService;

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.xxx.xxx.OperLog)")
    public void operLogPoinCut() {

    }

    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.xxx.xxx.controller..*.*(..))")
    public void operExceptionLogPoinCut() {

    }

    /**
     * 正常返回通知,拦截用户操作日志,连接点正常执行完成后执行, 如果连接点抛出异常,则不会执行
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        getLog(joinPoint, null);
    }

    /**
     * 异常返回通知,用于拦截异常日志信息 连接点抛出异常后执行
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        getLog(joinPoint, e);
    }

    /**
     * 获取封装log对象
     * @param joinPoint
     * @return
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void getLog(JoinPoint joinPoint, Throwable e) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        Object[] args = joinPoint.getArgs();
        Class<?> clazz = joinPoint.getTarget().getClass();
        Signature signature = joinPoint.getSignature();
        MethodSignature ms = (MethodSignature) signature;
        Method targetMethod = null;
        try {
            targetMethod = clazz.getDeclaredMethod(ms.getName(), ms.getParameterTypes());
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        OperLog olog = targetMethod.getAnnotation(OperLog.class);
        if(olog == null) {
            return;
        }
        //TODO 下面写自己需求!
        String IP = IpUtils.getIpAddr(request); //获取ip 根据日志需要
        LogPojo log = new LogPojo(); //自定义的日志对象
        try {
            String userId = JwtUtil.getUserId(request.getHeader("token"));//根据token获取用户id
            if(!StringUtils.isEmpty(userId)) {
                QueryWrapper<User> qw = new QueryWrapper<>();
                qw.select("user_name", "name").eq("user_name", userId);
                User user = userService.getOne(qw);
                log.setName(user.getName());
                log.setUserName(user.getUsername());
            }
        } catch (Exception exception) {
            System.err.println("没有获取到用户信息!");
        }
        log.setId(UUID.randomUUID().toString());
        log.setModel(olog.operModul());
        log.setType(olog.operType());
        log.setDescibes(olog.operDesc());
        log.setIp(IP);
        log.setAddress(AddressUtils.getRealAddressByIP(IP));
        log.setUrl(request.getServletPath());
        log.setParams(JSONObject.toJSONString(args));
        if(e != null) {
            log.setError(e.getMessage());
            log.setStatus(OprLogConst.fail);
        } else {
            log.setStatus(OprLogConst.OK);
        }
        logService.save(log); //存入日志对象
    }
}

OprLogConst.java

public class OprLogConst {

    public static final String ADD = "插入";

    public static final String UPDATE = "更新";

    public static final String SELECT = "查询";

    public static final String DELETE = "删除";

    public static final String EXPORT = "导出";

    public static final String IMPORT = "导入";

    public static final Integer OK = 200;

    public static final Integer fail = 500;

}

示例

    @OperLog(operModul = "字典管理", operType = OprLogConst.ADD, operDesc = "保存/修改类别字典信息")
    @RequestMapping("/saveParams")
    @ResponseBody
    public RespBean saveParams(Params params) {
    	return null;
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值