日志管理(spring AOP切面拦截)

**最近,在写日志管理的东西呢,用了几种方法试,还是拦截比较好用,直接截下来传入到数据库中存储。 写的时候,真是头疼啊,作为一个新手,要弄这个没有头绪的东西,从手足无措,到后来慢慢的习惯了加速敲代码,真是舒服!哈哈。

哦~对了,忘了说了,不需要用到Dao层哦。
首先,来一个POJO实体类吧,我看他们都是写的只有系统获取到的那些类名啊,方法啊什么的。我的有那么一点点的不同。
本来呢,准备黏贴代码上去的,可是看着太丑了,所有我就截图了,见谅哈。
这个上面的注释呢,看不懂的可以看我上几篇的spring注解哦,里面都有详细的解释。
**

在这里插入图片描述
好像我需要的数据也不是很多。
接着呢,弄一个拦截类的controller和一个service吧。
在这里插入图片描述
在这里插入图片描述
**

这个应该很好理解吧,为了能够获取到需要的属性。 算了,为了你们好,我还是把代码黏上来吧,不然可能你们跟着敲都要好久的,就当给你们模板了慢慢改吧。 这个呢,是最主要的东西了!!!!Aop切面拦截

**

package com.ss.crm.aop;

import com.ss.crm.entity.Log;
import com.ss.crm.entity.User;
import com.ss.crm.interceptor.SystemControllerLog;
import com.ss.crm.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class SystemLogAspect {

@Autowired
private LogService ls;

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


//Controller层切点
@Pointcut("execution (* com.ss.crm.controller..*.*(..))")
public void controllerAspect() {
}

/**
 * 前置通知 用于拦截Controller层记录用户的操作
 *
 * @param joinPoint 切点
 */
@Before("controllerAspect()")
public void doBefore(JoinPoint joinPoint) {
    /*用isDebugEnabled方法判断下是能提升性能的*/
    if (logger.isInfoEnabled()) {
        logger.info("before " + joinPoint);
    }
}
/**
 * 后置通知 用于拦截Controller层记录用户的操作
 *
 * @param joinPoint 切点
 */
@After("controllerAspect()")
public void after(JoinPoint joinPoint) {

    /* HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
      HttpSession session = request.getSession();  */
    //读取session中的用户
    // User user = (User) session.getAttribute("user");
    //请求的IP
    //String ip = request.getRemoteAddr();
    User user = new User();
    user.setUserId(1);
  /*  System.out.println("userid会打印什么 : " + user.getUserId());*/
    try {

        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String logType = "";
        String logContent = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    logType = method.getAnnotation(SystemControllerLog.class).actionType();
                    logContent = method.getAnnotation(SystemControllerLog.class).descrption();
                    break;
                }
            }
        }
        //*========控制台输出=========*//
        System.out.println("请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
        System.out.println("方法描述:" + logContent);
        System.out.println("请求人:" + user.getUserName());
        //*========数据库日志=========*//
        Log log = new Log();
        log.setUserId(1);
        log.setLogType(logType);
        log.setLogContent(logContent);
        log.setLogErrorCode(HttpStatus.OK.toString());
        log.setLogDate(new Date());
        //保存数据库
        ls.getInsertLog(log);
    } catch (Exception e) {
        //记录本地异常日志
        logger.error("异常信息:{}", e.getMessage());
    }
}

//配置后置返回通知,使用在方法aspect()上注册的切入点
@AfterReturning("controllerAspect()")
public void afterReturn(JoinPoint joinPoint) {
    if (logger.isInfoEnabled()) {
        logger.info("afterReturn " + joinPoint);
    }
}

/**
 * 异常通知 用于拦截记录异常日志
 *
 * @param joinPoint
 * @param e
 */
@AfterThrowing(pointcut = "controllerAspect()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
             /*HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
     HttpSession session = request.getSession();
     //读取session中的用户
    User user = (User) session.getAttribute("user");
     //获取请求ip
     String ip = request.getRemoteAddr(); */

    User user = new User();
    user.setUserId(1);

    String logResult = "";
    try {

        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String logType = "";
        String logContent = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    logType = method.getAnnotation(SystemControllerLog.class).actionType();
                    logContent = method.getAnnotation(SystemControllerLog.class).descrption();
                    break;
                }
            }
        }
        /*========控制台输出=========*/
        System.out.println("异常代码:" + e.getClass().getName());
        System.out.println("异常信息:" + e.getMessage());
        System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
        System.out.println("方法描述:" + logContent);
        System.out.println("请求人:" + user.getUserName());
        /*==========数据库日志=========*/
        Log log = new Log();
        log.setUserId(1);
        log.setLogType(logType);
        log.setLogContent(logContent);
        log.setLogErrorCode(e.getMessage());
        log.setLogDate(new Date());
        //保存数据库
        ls.getInsertLog(log);
    } catch (Exception ex) {
        //记录本地异常日志
        logger.error("异常信息:{}", ex.getMessage());
    }
    /*==========记录本地异常日志==========*/
    logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage());

}

}

根据对应的数据获取,慢慢看咯。
后面还有service和mapper应该不需要吧?好吧,那我还是弄一个例子上来吧。
Mapper层
在这里插入图片描述
咳咳,我比较懒,就没有删除后面那个获取的页数和一页显示多少数据
(start,currentPageSize),你们忽略他们就好哈,可以不写东西的。
这个是XML,我也没有删掉,反正你们正常把后面的删除就好啦。
在这里插入图片描述
Service层,同上咯
在这里插入图片描述
这里serviceImpl层页数把括号内的清空也是一样的,因为里面是我分页查询的条件咯。哦,对了,别忘了加注解@Service
在这里插入图片描述
难受,忘了controller层不删除那些没用的会报错了,你们可以放心用,没事的,没用什么影响,在你们那里是完好的。
别忘了在类上面加一个@Controller
这里的actionType是类型,descrption是对什么进行的操作。

在这里插入图片描述
好了,这就是所有的代码了,我就不贴网页查询的数据咯。
在这里插入图片描述
感谢观看,前台应该不用吧? 需要的留言哦。

猜你喜欢

转载自blog.csdn.net/nan961136007/article/details/86554522