SpringMVC 使用aop记录用户操作日志

系统监控- 操作日志 使用apo记录用户操作日志
https://github.com/elunez/eladmin

 

1、添加spring配置文件

<!-- 日志 -->
	<context:annotation-config></context:annotation-config>
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
	<bean id="logBean" class="com.test.sys.log.aspect.LogAspect"></bean>

 

2、配置web.xml

 监听RequestContextListener, 获取request

	<!--配置RequestContextListener监听器-->
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
public class RequestHolder {

    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
}

 

3、定义注解

/**
 * @author jie
 * @date 2018-11-24
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
	String value() default "";
}

在登录接口添加注解

    @Log("用户登录")
    @RequestMapping("login")
    public String login(User user, HttpSession session, HttpServletRequest request ) {}

 

 

4、定义拦截处理类


import com.test.base.exception.BadRequestException;
import com.test.base.utils.ThrowableUtil;
import com.test.sys.log.model.SysLog;
import com.test.sys.log.service.SysLogServiceI;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author jie
 * @date 2018-11-24
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    private SysLogServiceI logService;

    private long currentTime = 0L;

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.vizhuo.sys.log.annotation.Log)")
    public void logPointcut() {
        // 该方法无方法体,主要为了让同类中其他方法使用此切入点
    }

    /**
     * 配置环绕通知,使用在方法logPointcut()上注册的切入点
     *
     * @param joinPoint join point for advice
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint){
        Object result = null;
        currentTime = System.currentTimeMillis();
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            throw new BadRequestException(e.getMessage());
        }
        SysLog log = new SysLog("INFO",System.currentTimeMillis() - currentTime);
        logService.add(joinPoint, log);
        return result;
    }

    /**
     * 配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        SysLog log = new SysLog("ERROR",System.currentTimeMillis() - currentTime);
        log.setExceptionDetail(ThrowableUtil.getStackTrace(e));
        logService.add((ProceedingJoinPoint)joinPoint, log);
    }
}

 

5、存储数据库

@Service("SysLogService")
public class SysLogServiceImpl extends BaseServiceImpl<SysLog, SysLogQuery, Integer> implements SysLogServiceI {

    private static final Logger logger = LoggerFactory.getLogger(SysLogServiceImpl.class);


    @Autowired
    public void setSysLogMapper(SysLogMapperI sysLogMapper) {
        setBaseMapper(sysLogMapper);

    }

    private final String LOGINPATH = "login";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(ProceedingJoinPoint joinPoint, SysLog log) {

        // 获取request
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log aopLog = method.getAnnotation(Log.class);

        // 描述
        if (log != null) {
            log.setDescription(aopLog.value());
        }

        // 方法路径
        String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
        if ("com.test.sys.log.controller.SysLogController.findEntityByPager()".equals(methodName)) {
            return;
        }

        //参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();


        if (argValues != null) {
            StringBuffer buffer = new StringBuffer();
            buffer.append("{");
            for (int i = 0; i < argValues.length; i++) {
                buffer.append(" " + argNames[i] + ": " + argValues[i]);
            }
            buffer.append(" }");
            String params = buffer.toString();
            log.setParams(params);

            logger.info(" params............" + params.length());
        }

        // 获取IP地址
        log.setRequestIp(RequestHolder.getIP(request));

//        if(!LOGINPATH.equals(signature.getName())){
//            username = SecurityUtils.getAccount();
//        } else {
//            try {
//                JSONObject jsonObject = new JSONObject(argValues[0]);
//                username = jsonObject.get("username").toString();
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        }

        String account = SecurityUtils.getAccount();
        log.setMethod(methodName);
        log.setAccount(account);


        logger.info(" save log............");
        SysLogMapperI rm = (SysLogMapperI) baseMapper;
        rm.insertEntity(log);
    }

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值