一、前言
本文主要介绍通过Aop记录用户操作日志,这也是目前比较常用的用法,由于水平有限,所以可能存在错漏之处,望指正。
二、实战
1、设计用户操作日志表: sys_oper_log
对应实体类为SysOperLog.java
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysOperLog implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
@ApiModelProperty("主键Id")
private Integer id;
@ApiModelProperty("模块标题")
private String title;
@ApiModelProperty("参数")
private String optParam;
@ApiModelProperty("业务类型(0其它 1新增 2修改 3删除)")
private Integer businessType;
@ApiModelProperty("路径名称")
private String uri;
@ApiModelProperty("操作状态(0正常 1异常)")
private Integer status;
@ApiModelProperty("错误消息")
private String errorMsg;
@ApiModelProperty("操作时间")
private Date operTime;
}
2、引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
3、自定义用户操作日志注解
MyLog.java
import java.lang.annotation.*;
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyLog {
String title() default "";
String optParam() default "";
BusinessType businessType() default BusinessType.OTHER;
}
BusinessType.java — 操作类型枚举类
public enum BusinessType {
OTHER,
SELECT,
INSERT,
UPDATE,
DELETE,
}
4、自定义用户操作日志切面
LogAspect.java
import com.alibaba.fastjson.JSONObject;
import iot.sixiang.license.entity.SysOperLog;
import iot.sixiang.license.handler.IotLicenseException;
import iot.sixiang.license.jwt.UserUtils;
import iot.sixiang.license.service.SysOperLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Aspect
@Component
@Slf4j
public class LogAspect {
@Autowired
private SysOperLogService sysOperLogService;
@Pointcut("@annotation(xxx.xxx.xxx.MyLog)")
public void logPointCut() {
log.info("------>配置织入点");
}
@AfterReturning(pointcut = "logPointCut()")
public void doAfterReturning(JoinPoint joinPoint) {
handleLog(joinPoint, null);
}
@AfterThrowing(value = "logPointCut()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
handleLog(joinPoint, e);
}
private void handleLog(final JoinPoint joinPoint, final Exception e) {
MyLog controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null) {
return;
}
SysOperLog operLog = new SysOperLog();
operLog.setStatus(0);
operLog.setOperTime(new Date());
if (e != null) {
operLog.setStatus(1);
operLog.setErrorMsg(StringUtils.substring(((IotLicenseException) e).getMsg(), 0, 2000));
}
String uri = UserUtils.getUri();
operLog.setUri(uri);
getControllerMethodDescription(joinPoint, controllerLog, operLog);
sysOperLogService.addOperlog(operLog.getTitle(), operLog.getBusinessType(), operLog.getUri(), operLog.getStatus(), operLog.getOptParam(), operLog.getErrorMsg(), operLog.getOperTime());
}
private MyLog getAnnotationLog(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null) {
return method.getAnnotation(MyLog.class);
}
return null;
}
private void getControllerMethodDescription(JoinPoint joinPoint, MyLog myLog, SysOperLog operLog) {
operLog.setBusinessType(myLog.businessType().ordinal());
operLog.setTitle(myLog.title());
String optParam = getAnnotationValue(joinPoint, myLog.optParam());
operLog.setOptParam(optParam);
}
private String getAnnotationValue(JoinPoint joinPoint, String name) {
String paramName = name;
Map<String, Object> params = getParams(joinPoint);
if (paramName.matches("^#\\{\\D*\\}")) {
paramName = paramName.replace("#{", "").replace("}", "");
if (paramName.contains(".")) {
String[] split = paramName.split("\\.");
Object object = getValue(params, split[0]);
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(object);
Object o = jsonObject.get(split[1]);
return String.valueOf(o);
} else {
StringBuilder str = new StringBuilder();
String[] paraNames = paramName.split(",");
for (String paraName : paraNames) {
String val = String.valueOf(getValue(params, paraName));
str.append(paraName).append("=").append(val).append(",");
}
if (str.toString().endsWith(",")) {
String substring = str.substring(0, str.length() - 1);
return substring;
} else {
return str.toString();
}
}
}
return name;
}
public Map<String, Object> getParams(JoinPoint joinPoint) {
Map<String, Object> params = new HashMap<>(8);
Object[] args = joinPoint.getArgs();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String[] names = signature.getParameterNames();
for (int i = 0; i < args.length; i++) {
params.put(names[i], args[i]);
}
return params;
}
private Object getValue(Map<String, Object> map, String paramName) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals(paramName)) {
return entry.getValue();
}
}
return null;
}
}
5、MyLog注解的使用
@GetMapping("login")
@MyLog(title = "登录", optParam = "#{userName},#{password}", businessType = BusinessType.OTHER)
public DataResult login(@RequestParam("userName") String userName, @RequestParam("password") String password) {
...
}
6、最终效果
三、总结
用户操作日志是AOP最常见的一种业务场景,这里只是简单记录了少量信息,如果需要更详细的信息,就需要读者自行去组装和改造。
|