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

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

 

1、添加spring配置文件


	
	
	

 

2、配置web.xml

 监听RequestContextListener, 获取request

	
	
		org.springframework.web.context.request.RequestContextListener
	
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 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);
    }

 

 

 

你可能感兴趣的:(【Java】)