springboot項目使用切面記錄用戶操作日志


https://blog.csdn.net/qq_36752632/article/details/79444257

 

https://blog.csdn.net/WoddenFish/article/details/82593850?utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&dist_request_id=1328761.1432.16171810920315613&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control

 

1、引入springboot-aop集成jar

          Spring-boot-start-aop

2、application.yml中啟用聲明

#spring配置
spring:
#切面啟用
aop:
proxy-target-class: true
auto: true
3、自定義一個攔截controller的注解

package cn.annotation;

import java.lang.annotation.*;

/**
* Title: SystemControllerLog
* @date 2018年8月31日
* @version V1.0
* Description: 自定義注解,攔截controller
*/

@Target({ElementType.PARAMETER, ElementType.METHOD})//作用在參數和方法上
@Retention(RetentionPolicy.RUNTIME)//運行時注解
@Documented//表明這個注解應該被 javadoc工具記錄
public @interface SystemControllerLog {
String description() default "";
}
4、自定義一個攔截service的注解
package cn.annotation;

import java.lang.annotation.*;

/**
* Title: SystemControllerLog
* @date 2018年8月31日
* @version V1.0
* Description: 自定義注解,攔截service
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceLog {
String description() default "";
}
 

5、定義日志記錄切面

package cn.annotation;

import cn.pojo.Action;
import cn.pojo.User;
import cn.service.ActionService;
import cn.utils.IpUtils;
import cn.utils.JsonUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
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.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
* Title: SystemControllerLog
* @date 2018年8月31日
* @version V1.0
* Description: 切點類
*/
@Aspect
@Component
@SuppressWarnings("all")
public class SystemLogAspect {
//注入Service用於把日志保存數據庫,實際項目入庫采用隊列做異步
@Resource
private ActionService actionService;
//本地異常日志記錄對象
private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
//Service層切點
@Pointcut("@annotation(cn.annotation.SystemServiceLog)")
public void serviceAspect(){
}

//Controller層切點
@Pointcut("@annotation(cn.oa.annotation.SystemControllerLog)")
public void controllerAspect(){
}

/**
* @Description 前置通知 用於攔截Controller層記錄用戶的操作
* @date 2018年9月3日 10:38
*/

@Before("controllerAspect()")
public void doBefore(JoinPoint joinPoint){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpSession session = request.getSession();
//讀取session中的用戶
User user = (User) session.getAttribute("user");

String ip = IpUtils.getIpAddr(request);

try {
//*========控制台輸出=========*//
System.out.println("==============前置通知開始==============");
System.out.println("請求方法" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()));
System.out.println("方法描述:" + getControllerMethodDescription(joinPoint));
System.out.println("請求人:"+user.getUsername());
System.out.println("請求ip:"+ip);

//*========數據庫日志=========*//
Action action = new Action();
action.setActionDes(getControllerMethodDescription(joinPoint));
action.setActionType("0");
action.setActionIp(ip);
action.setUserId(user.getId());
action.setActionTime(new Date());
//保存數據庫
actionService.add(action);

}catch (Exception e){
//記錄本地異常日志
logger.error("==前置通知異常==");
logger.error("異常信息:{}",e.getMessage());
}
}

/**
* @Description 異常通知 用於攔截service層記錄異常日志
* @date 2018年9月3日 下午5:43
*/
@AfterThrowing(pointcut = "serviceAspect()",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 = IpUtils.getIpAddr(request);
//獲取用戶請求方法的參數並序列化為JSON格式字符串
String params = "";
if (joinPoint.getArgs()!=null&&joinPoint.getArgs().length>0){
for (int i = 0; i < joinPoint.getArgs().length; i++) {
params+= JsonUtils.objectToJson(joinPoint.getArgs()[i])+";";
}
}
try{
/*========控制台輸出=========*/
System.out.println("=====異常通知開始=====");
System.out.println("異常代碼:" + e.getClass().getName());
System.out.println("異常信息:" + e.getMessage());
System.out.println("異常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
System.out.println("方法描述:" + getServiceMethodDescription(joinPoint));
System.out.println("請求人:" + user.getUsername());
System.out.println("請求IP:" + ip);
System.out.println("請求參數:" + params);
/*==========數據庫日志=========*/
Action action = new Action();
action.setActionDes(getServiceMethodDescription(joinPoint));
action.setActionType("1");
action.setUserId(user.getId());
action.setActionIp(ip);
action.setActionTime(new Date());
//保存到數據庫
actionService.add(action);
}catch (Exception ex){
//記錄本地異常日志
logger.error("==異常通知異常==");
logger.error("異常信息:{}", ex.getMessage());
}
}


/**
* @Description 獲取注解中對方法的描述信息 用於service層注解
* @date 2018年9月3日 下午5:05
*/
public static String getServiceMethodDescription(JoinPoint joinPoint)throws Exception{
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 description = "";
for (Method method:methods) {
if (method.getName().equals(methodName)){
Class[] clazzs = method.getParameterTypes();
if (clazzs.length==arguments.length){
description = method.getAnnotation(SystemServiceLog.class).description();
break;
}
}
}
return description;
}



/**
* @Description 獲取注解中對方法的描述信息 用於Controller層注解
* @date 2018年9月3日 上午12:01
*/
public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
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 description = "";
for (Method method:methods) {
if (method.getName().equals(methodName)){
Class[] clazzs = method.getParameterTypes();
if (clazzs.length==arguments.length){
description = method.getAnnotation(SystemControllerLog.class).description();
break;
}
}
}
return description;
}
}
6、開始使用

    1)@SystemControllerLog(description = "")

          注解加在控制器中方法上面,括號里寫上操作描述

 

 

    2)用於監控service異常,可以不使用

        @SystemServiceLog(description = "")

        注解加在service層方法上面,括號里寫上操作描述

(此處為AOP攔截Service記錄異常信息。方法不需要加try-catch)

------------------------------------------------------------------------------------------------------

項目地址:https://gitee.com/lwydyby/wwmxd-log/
1. 在需要記錄的方法上使用注解EnableGameleyLog
參數如下:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface EnableGameleyLog {
/**
* 操作的中文說明 可以直接調用ModifyName
* @return
*/
String name() default "";

/**
* 獲取編輯信息的解析類,目前為使用id獲取,復雜的解析需要自己實現,默認不填寫
* 則使用默認解析類
* @return
*/
Class parseclass() default DefaultContentParse.class;

/**
* 查詢數據庫所調用的class文件
* @return
*/
Class serviceclass() default IService.class;

/**
* 前台字段名稱
*/
String[] feildName() default {"id"};

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
簡單例子:
“`
@EnableGameleyLog(name = ModifyName.SAVE,serviceclass = DemoService.class)
public BaseResponse addDemo(@RequestBody Demo demo){

}

2.編寫解析類,默認的解析類為使用id查詢,自定義的解析類請繼承ContentParser接口,並在注解中賦值
1
/**
* 基礎解析類
* 單表編輯時可以直接使用id來查詢
* 如果為多表復雜邏輯,請自行編寫具體實現類
* @author lw
* @date 2018-03-02
*/
public class DefaultContentParse implements ContentParser {
@Override
public Object getResult(Map

3.默認的操作方式有:
```
public class ModifyName {
public final static String SAVE="新建";
public final static String UPDATE="編輯";
public final static String DELETE="刪除";
}
1
2
3
4
5
6
7
4.如需記錄操作字段中文請在entity中使用DataName注解
如:

@DataName(name="操作日期")
private String modifydate;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM