日志记录

1.表

 

 2.实体类

public class Log {
    private int lid;
    private int uid;
    private String ldate;
    private String lcontroller;
    private String lmethod;
    private String lcontent;
    private String exmsg;

3.dao

@Repository
public interface LogDao {
    
    /*private int lid;
    private int uid;
    private String ldate;
    private String lmethod;
    private String lcontent;*/
    
    @Select("select l.*,u.uid,u.uname,u.upwd,u.utype,u.urealname from log l,userinfo u where l.uid=u.uid")
    public List<LogUser> findAllStore();
    
    @Insert("insert into log(uid,ldate,lcontroller,lmethod,lcontent,exmsg) values(#{uid},#{ldate},#{lcontroller},#{lmethod},#{lcontent},#{exmsg})")
    public int addLog(Log log);
    
}

4.service

5.在pom.xmlz配置

<dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging-api</artifactId>
            <version>1.1</version>
        </dependency>
 
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.26</version>
        </dependency>
 
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.26</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.1</version>
        </dependency>

 

6.自定义注解

package com.hopu.zj;

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;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface SystemControllerLog {
     public String operteContent() default "";
}

 

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;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface SystemServiceLog {
     public String operteContent() default "";
}

7.切点类

package com.hopu.zj;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.hopu.entity.Log;
import com.hopu.entity.Userinfo;
import com.hopu.service.LogService;

@Aspect
@Component
public class ArchivesLogAspect {
    //https://blog.csdn.net/it1993/article/details/91381839
    @Autowired
    private LogService logService;
    private static final Logger logger = LoggerFactory.getLogger(SystemControllerLog.class);
    private static SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    @Pointcut("@annotation(SystemServiceLog)")
    public void serviceAspect() {
         //System.out.println("切入点...");
    }
    
    @Pointcut("@annotation(SystemControllerLog)")
    public void controllerAspect() {
         //System.out.println("切入点...");
    }
    
    //前置通知 用于拦截Controller层记录用户的操作 
    
    @Before("controllerAspect()")
    public  void doBefore(JoinPoint joinPoint) throws ClassNotFoundException {  
         System.out.println("=====前置通知开始=====");  
         System.out.println("请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));  
         System.out.println("方法描述:" + getControllerMethodDesc(joinPoint).getLmethod());  
         System.out.println("请求人:" + getUSerMsg().getUname()); 
         // 用户id
         int userId = getUSerMsg().getUid();
         // 控制器名
          String targetName = getControllerMethodDesc(joinPoint).getLcontroller();
         // 方法名
         String methodName = getControllerMethodDesc(joinPoint).getLmethod();
         // 操作说明
         String operteContent = getControllerMethodDesc(joinPoint).getLcontent();
         long beginTime = System.currentTimeMillis();  
         Date date = new Date(beginTime);
         Log logInfo = new Log();
         logInfo.setUid(userId);
         logInfo.setLdate(sdf1.format(date));
         logInfo.setLcontent(operteContent);
         logInfo.setLmethod(methodName);
         logInfo.setLcontroller(targetName);
         logService.addLog(logInfo);
    }
    
    /*@AfterReturning("controllerAspect()")
    public  void after(JoinPoint joinPoint) throws ClassNotFoundException {
        // 用户id
        int userId = getUSerMsg().getUid();
        // 控制器名
         String targetName = getControllerMethodDesc(joinPoint).getLcontroller();
        // 方法名
        String methodName = getControllerMethodDesc(joinPoint).getLmethod();
        // 操作说明
        String operteContent = getControllerMethodDesc(joinPoint).getLcontent();
        Log logInfo = new Log();
        logInfo.setUid(userId);
        logInfo.setLcontent(operteContent);
        logInfo.setLmethod(methodName);
        logInfo.setLcontroller(targetName);
        logService.addLog(logInfo);
    }*/
    
     //异常通知 用于拦截service层记录异常日志
    @org.aspectj.lang.annotation.AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
    public void AfterThrowing(JoinPoint joinPoint, Throwable e) {
        try {
            // 用户id
            int userId = getUSerMsg().getUid();
            // 控制器名
            String targetName = getServiceMethodDesc(joinPoint).getLcontroller();
            // 方法名
            String methodName = getServiceMethodDesc(joinPoint).getLmethod();
            // 操作说明
            String operteContent = getServiceMethodDesc(joinPoint).getLcontent();
            Log logInfo = new Log();
            String exMsg = e.getCause().toString();
            long beginTime = System.currentTimeMillis();  
             Date date = new Date(beginTime);
            if (exMsg != null) {
                logInfo.setUid(userId);
                logInfo.setLdate(sdf1.format(date));
                logInfo.setLcontent(operteContent);
                logInfo.setLmethod(methodName);
                logInfo.setLcontroller(targetName);
                logInfo.setExmsg(exMsg);
                logService.addLog(logInfo);
            }
        } catch (Exception e1) {
            logger.error(e1.getMessage());
        }
    }

    
    //得到用户信息
    public static Userinfo getUSerMsg() {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //请求的ip
        String ip=req.getRemoteAddr();
        // 获取session
        HttpSession session = req.getSession();
        Userinfo user = (Userinfo) session.getAttribute("user");
        return user;
    }
    /**
     * 获取 注解中对方法的描述
     */
    public static Log getControllerMethodDesc(JoinPoint joinPoint) throws ClassNotFoundException {
        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 operteContent = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    operteContent = method.getAnnotation(SystemControllerLog.class).operteContent();
                    break;
                }
            }
        }
        Log logInfo = new Log();
        logInfo.setLcontroller(targetName);
        logInfo.setLmethod(methodName);
        logInfo.setLcontent(operteContent);
        return logInfo;
    }
    
    public static Log getServiceMethodDesc(JoinPoint joinPoint) throws ClassNotFoundException {
        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 operteContent = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    operteContent = method.getAnnotation(SystemServiceLog.class).operteContent();
                    break;
                }
            }
        }
        Log logInfo = new Log();
        logInfo.setLcontroller(targetName);
        logInfo.setLmethod(methodName);
        logInfo.setLcontent(operteContent);
        return logInfo;
    }


}

8.配置文件

<!-- 启动对@AspectJ注解的支持 -->                                                                             <aop:aspectj-autoproxy/>  

<!--通知spring使用cglib而不是jdk的来生成代理方法 AOP可以拦截到Controller->            <aop:aspectj-autoproxy proxy-target-class="true" />  

 

9.controller层使用

//查找所有普通管理员
    @RequestMapping("/user/findAll")
    @ResponseBody
    @SystemControllerLog(operteContent="全查普通管理员")
    public Object findAll(Userinfo user){
        System.out.println("全查普通管理员--------");
        List<Userinfo> list = userService.findAll(user);
        return list;
    }

10.service使用

@Override
    @SystemServiceLog(operteContent="findAllStore方法")
    public List<UserinfoStore> findAllStore() {
        return storeDao.findAllStore();
    }

 

posted @ 2020-08-27 17:49  郭郭同学  阅读(220)  评论(0编辑  收藏  举报