springboot項目如何使用切面記錄用戶操作日志
更新時間:2022年10月31日 12:08:13 作者:WoddenFish
這篇文章主要介紹了springboot項目如何使用切面記錄用戶操作日志,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
1、引入springboot-aop集成jar
Spring-boot-start-aop
2、application.yml中啟用聲明
#spring配置
spring:
#切面啟用
aop:
proxy-target-class: true
auto: true3、自定義一個攔截controller的注解
package cn.annotation;
import java.lang.annotation.*;
/**
* Title: SystemControllerLog
* @date 2018年8月31日
* @version V1.0
* Description: 自定義注解,攔截controller
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})//作用在參數(shù)和方法上
@Retention(RetentionPolicy.RUNTIME)//運行時注解
@Documented//表明這個注解應(yīng)該被 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用于把日志保存數(shù)據(jù)庫,實際項目入庫采用隊列做異步
@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);
//*========數(shù)據(jù)庫日志=========*//
Action action = new Action();
action.setActionDes(getControllerMethodDescription(joinPoint));
action.setActionType("0");
action.setActionIp(ip);
action.setUserId(user.getId());
action.setActionTime(new Date());
//保存數(shù)據(jù)庫
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);
//獲取用戶請求方法的參數(shù)并序列化為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("請求參數(shù):" + params);
/*==========數(shù)據(jù)庫日志=========*/
Action action = new Action();
action.setActionDes(getServiceMethodDescription(joinPoint));
action.setActionType("1");
action.setUserId(user.getId());
action.setActionIp(ip);
action.setActionTime(new Date());
//保存到數(shù)據(jù)庫
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)用于監(jiān)控service異常,可以不使用
@SystemServiceLog(description = "")
注解加在service層方法上面,括號里寫上操作描述
(此處為AOP攔截Service記錄異常信息。方法不需要加try-catch)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實現(xiàn)提取不重復(fù)的整數(shù)實例
這篇文章主要介紹了Java實現(xiàn)提取不重復(fù)的整數(shù)實例,具有一定借鑒價值,需要的朋友可以參考下2017-12-12
Sentinel實現(xiàn)動態(tài)配置的集群流控的方法
這篇文章主要介紹了Sentinel實現(xiàn)動態(tài)配置的集群流控,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04
SpringBoot環(huán)境屬性占位符解析和類型轉(zhuǎn)換方式
這篇文章主要介紹了SpringBoot環(huán)境屬性占位符解析和類型轉(zhuǎn)換方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
Springboot設(shè)置文件上傳大小限制的實現(xiàn)示例
Spring Boot工程嵌入的tomcat限制了請求的文件大小默認為1MB,單次請求的文件的總數(shù)不能大于10Mb,本文主要介紹了Springboot設(shè)置文件上傳大小限制的實現(xiàn)示例,感興趣的可以了解一下2023-11-11
Spring Boot JPA如何把ORM統(tǒng)一起來
Spring Data JPA 是 Spring 基于 ORM 框架、JPA 規(guī)范的基礎(chǔ)上封裝的一套JPA應(yīng)用框架,可使開發(fā)者用極簡的代碼即可實現(xiàn)對數(shù)據(jù)的訪問和操作,本文給大家詳細介紹了Spring Boot JPA如何把ORM統(tǒng)一起來,感興趣的朋友一起看看吧2018-04-04

