首先添加jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package com.kq.configmanager.annotation;
import java.lang.annotation.*;
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OperationLogDetail {
/**
* 方法描述,可使用占位符获取参数:{{tel}}
*/
String detail() default "";
/**
* 要执行的具体操作
* @return
*/
public String operationName() default "";
/**
* 操作类型(enum):主要是select,insert,update,delete
*/
public String operationType() default "";
}
切入点为这个下面的类:
package com.kq.configmanager.aop;
import java.lang.reflect.Method;
import java.util.*;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kq.configmanager.annotation.OperationLogDetail;
import com.kq.configmanager.domain.OperationLog;
import com.kq.configmanager.service.IDssConfigLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
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 org.springframework.web.multipart.MultipartFile;
/**
* Created by xu on 2021/3/13.
*/
@Aspect
@Component
public class LogAspect {
/**
* 注入service
*/
@Autowired
private IDssConfigLogService iDssConfigLogService;
private static final Logger logger = LoggerFactory.getLogger(LogAspect. class);
//切入点
@Pointcut("execution (* com.kq.configmanager.controller.release.*.*(..))")
public void controllerAspect() {}
/**
* 前置通知 用于拦截Controller层记录用户的操作、再切入点之前要干的
*
* @param joinPoint 切点
*/
@Before("controllerAspect()")
public void doBefore(JoinPoint joinPoint) {
System.out.println("==========执行controller前置通知===============");
if(logger.isInfoEnabled()){
logger.info("before " + joinPoint);
}
}
/**
* 配置controller环绕通知,使用在方法aspect()上注册的切入点
* @param joinPoint
*/
@Around("controllerAspect()")
public void around(JoinPoint joinPoint){
System.out.println("==========开始执行controller环绕通知===============");
long start = System.currentTimeMillis();
try {
((ProceedingJoinPoint) joinPoint).proceed();
long end = System.currentTimeMillis();
if(logger.isInfoEnabled()){
logger.info("around " + joinPoint + "\tUse time : " + (end - start) + " ms!");
}
addOperationLog(joinPoint);
System.out.println("==========结束执行controller环绕通知===============");
} catch (Throwable e) {
long end = System.currentTimeMillis();
if(logger.isInfoEnabled()){
logger.info("around " + joinPoint + "\tUse time : " + (end - start) + " ms with exception : " + e.getMessage());
}
}
}
private void addOperationLog(JoinPoint joinPoint){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpSession session = request.getSession();
//读取session中的用户
String userId = String.valueOf(session.getAttribute("userId"));
String userName = String.valueOf(session.getAttribute("userName"));
OperationLog operationLog = new OperationLog();
operationLog.setId(IdUtil.randomUUID());
operationLog.setInsertTime(new Date());
operationLog.setUserId(userId);
operationLog.setUserName(userName);
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 operationType = "";
String operationName = "";
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
operationType = method.getAnnotation(OperationLogDetail.class).operationType();
operationName = method.getAnnotation(OperationLogDetail.class).operationName();
break;
}
}
}
if(operationType.equals("insert")){
operationLog.setUserContent(operationName);
operationLog.setOperationType(operationType);
iDssConfigLogService.insert(operationLog);
}else if(operationType.equals("updateStatus1")){
operationLog.setUserContent(operationName);
operationLog.setOperationType(operationType);
iDssConfigLogService.insert(operationLog);
}else if(operationType.equals("updateStatus2")){
operationLog.setUserContent(operationName);
operationLog.setOperationType(operationType);
iDssConfigLogService.insert(operationLog);
}else if(operationType.equals("updateData")){
String paramter = "";
//请求的参数
Object[] args = joinPoint.getArgs();
Object[] arguments1 = new Object[args.length];
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
continue;
}
arguments1[i] = args[i];
}
if (arguments1 != null) {
try {
paramter = JSONObject.toJSONString(arguments1);
} catch (Exception e) {
paramter = arguments1.toString();
}
}
List<Map<String, Object>> maps = toListMap(paramter);
Object satelliteSensor = maps.get(0).get("satelliteSensor");
Object sceneStartTime = maps.get(0).get("sceneStartTime");
Object sceneEndTime = maps.get(0).get("sceneEndTime");
Object productStartTime = maps.get(0).get("productStartTime");
Object productEndTime = maps.get(0).get("productEndTime");
Object dbStartTime = maps.get(0).get("dbStartTime");
Object dbEndTime = maps.get(0).get("dbEndTime");
Object requirement = maps.get(0).get("requirement");
StringBuilder sb = new StringBuilder("修改");
if(satelliteSensor!=null){
sb.append("卫星为"+satelliteSensor+",");
}
if (sceneStartTime!=null){
sb.append("采集时间为"+sceneStartTime+" "+sceneEndTime+",");
}
if(productStartTime!=null){
sb.append("生产时间为"+productStartTime+" "+productEndTime+",");
}
if(dbStartTime!=null){
sb.append("入库时间为"+dbStartTime+" "+dbEndTime+",");
}
if(requirement!=null){
sb.append("需求说明为"+requirement+",");
}
operationName = sb.toString().substring(0,sb.toString().length()-1);
//*========数据库日志=========*//
//保存数据库
operationLog.setUserContent(operationName);
operationLog.setOperationType(operationType);
iDssConfigLogService.insert(operationLog);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 后置通知 用于拦截Controller层记录用户的操作
*
* @param joinPoint 切点
*/
@After("controllerAspect()")
public void after(JoinPoint joinPoint) {
System.out.println("=====controller后置通知结束=====");
}
//配置后置返回通知,使用在方法aspect()上注册的切入点
@AfterReturning("controllerAspect()")
public void afterReturn(JoinPoint joinPoint){
System.out.println("=====执行controller后置返回通知=====");
if(logger.isInfoEnabled()){
logger.info("afterReturn " + joinPoint);
}
}
/**
* 异常通知 用于拦截记录异常日志
*
* @param joinPoint
* @param e
*/
@AfterThrowing(pointcut = "controllerAspect()", throwing="e")
public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
logger.error("异常方法:{}异常代码:{}异常信息:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage());
}
public List<Map<String, Object>> toListMap(String json){
List<Object> list =JSON.parseArray(json);
List< Map<String,Object>> listw = new ArrayList<Map<String,Object>>();
for (Object object : list){
Map <String,Object> ret = (Map<String, Object>) object;//取出list里面的值转为map
listw.add(ret);
}
System.out.println(listw);
return listw;
}
}
在方法上添加:@OperationLogDetail(operationType=“insert”,operationName=“创建”)
package com.kq.configmanager.controller.release;
import cn.hutool.core.util.IdUtil;
import com.kq.common.exception.BaseException;
import com.kq.configmanager.annotation.OperationLogDetail;
import com.kq.configmanager.controller.BaseController;
import com.kq.configmanager.domain.DssConfigRelease;
import com.kq.configmanager.service.IDssConfigLogService;
import com.kq.configmanager.service.IDssConfigReleaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
/**
* (DssConfigRelease)表控制层
*
* @author makejava
* @since 2021-03-12 13:59:28
*/
@Api(value = "DssConfigReleaseController",description = "发布配置管理")
@Controller
@RequestMapping("dssConfigRelease")
public class DssConfigReleaseController extends BaseController<DssConfigRelease,IDssConfigReleaseService> {
@Autowired
private IDssConfigReleaseService iDssConfigReleaseService;
@Autowired
private IDssConfigLogService iDssConfigLogService;
@ApiOperation(value = "新增发布配置管理")
@RequestMapping(value = "/save.do",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@OperationLogDetail(operationType="insert",operationName="创建")
public Object insert(@RequestBody DssConfigRelease dssConfigRelease) {
boolean result = false;
try{
String s = IdUtil.randomUUID();
dssConfigRelease.setId(s);
dssConfigRelease.setInsertTime(new Date());
result = this.defaultDAO.insert(dssConfigRelease);
}catch (Exception e){
e.printStackTrace();
throw new BaseException("新增失败",500);
}
return super.jsonObjectResult(result, "新增成功");
}
@ApiOperation(value = "修改发布状态为停止")
@RequestMapping(value = "/update1.do",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@OperationLogDetail(operationType="updateStatus1",operationName="修改发布状态为停止")
public Object update1(@RequestBody DssConfigRelease dssConfigRelease) {
boolean result = false;
try{
String id = dssConfigRelease.getId();
iDssConfigReleaseService.update1(id);
result = true;
}catch (Exception e){
e.printStackTrace();
throw new BaseException("状态修改失败",500);
}
return super.jsonObjectResult(result, "状态修改成功");
}
@ApiOperation(value = "修改发布状态为失效")
@RequestMapping(value = "/update2.do",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@OperationLogDetail(operationType="updateStatus2",operationName="修改发布状态为失效")
public Object update2(@RequestBody DssConfigRelease dssConfigRelease) {
boolean result = false;
try{
String id = dssConfigRelease.getId();
iDssConfigReleaseService.update2(id);
result = true;
}catch (Exception e){
e.printStackTrace();
throw new BaseException("状态修改失败",500);
}
return super.jsonObjectResult(result, "状态修改成功");
}
@ApiOperation(value = "修改数据")
@RequestMapping(value = "/updateData.do",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@OperationLogDetail(operationType="updateData")
public Object updateData(@RequestBody DssConfigRelease dssConfigRelease) {
boolean result = false;
try{
result = this.defaultDAO.updateById(dssConfigRelease);
}catch (Exception e){
e.printStackTrace();
throw new BaseException("修改失败",500);
}
return super.jsonObjectResult(result, "修改成功");
}
}
数据库日志表中记录状态: