一,注解描述
// 作用位置,参数 方法
@Target({ElementType.PARAMETER, ElementType.METHOD})
// 作用范围 运行时
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
/**
* 模块
*/
public String title() default "";
/**
* 模块
*/
public String operType() default "";
/**
* 功能
*/
public BusinessType businessType() default BusinessType.OTHER;
/**
* 操作人类别
*/
public OperatorType operatorType() default OperatorType.MANAGE;
/**
* 是否保存请求的参数
*/
public boolean isSaveRequestData() default true;
/**
* 是否保存响应的参数
*/
public boolean isSaveResponseData() default true;
}
1,功能类型
/**
* 业务操作类型
*/
public enum BusinessType {
/**
* 其它
*/
OTHER,
/**
* 新增
*/
INSERT,
/**
* 修改
*/
UPDATE,
/**
* 删除
*/
DELETE,
/**
* 授权
*/
ASSGIN,
/**
* 导出
*/
EXPORT,
/**
* 导入
*/
IMPORT,
/**
* 强退
*/
FORCE,
/**
* 更新状态
*/
STATUS,
/**
* 清空数据
*/
CLEAN,
}
2,操作人类型
/**
* 操作人类型
*/
public enum OperatorType {
/**
* 其它
*/
OTHER,
/**
* 后台用户
*/
MANAGE,
/**
* 手机端用户
*/
MOBILE
}
二,日志切点
/**
* 日志切点
*
* @author jkwl
* @date 2024-03-07
*/
@Aspect
@Component
public class LogAspect {
private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
@Autowired
private OperLogService operLogService;
@Autowired
private UserInfoService userInfoService;
/**
* 处理完请求后执行
*
* @param joinPoint 切点
*/
@AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
handleLog(joinPoint, controllerLog, null, jsonResult);
}
/**
* 处理完请求后执行
*
* @param joinPoint 切点
*/
@AfterThrowing(pointcut = "@annotation(controllerLog)", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
handleLog(joinPoint, controllerLog, e, null);
}
}
/**
* 新增操作日志数据
*
* @param joinPoint 切点
* @param controllerLog Log日志注解
* @param e 异常
* @param jsonResult 返回值
*/
protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
try {
// 获取request请求
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
assert attributes != null;
HttpServletRequest request = attributes.getRequest();
// *========数据库日志=========*//
OperLog operLog = new OperLog();
// 状态
operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
// 请求的地址
operLog.setOperIp(IpUtil.getIpAddress(request));
// 请求URL
operLog.setOperUrl(request.getRequestURI());
// 操作人员
UserDetail user = userInfoService.getUserInfo(request);
operLog.setOperName(user.getName());
// 异常情况
if (e != null) {
operLog.setStatus(BusinessStatus.FAIL.ordinal());
operLog.setErrorMsg(e.getMessage());
}
// 设置方法名称
// 获取类名
String className = joinPoint.getTarget().getClass().getName();
// 获取方法名
String methodName = joinPoint.getSignature().getName();
// 设置类名 方法名
operLog.setMethod(className + "." + methodName + "()");
// 设置请求方式
operLog.setRequestMethod(request.getMethod());
// 处理设置注解上的参数
getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);
// 设置时间
operLog.setOperTime(LocalDateTime.now());
// 保存数据库
operLogService.save(operLog);
} catch (Exception exp) {
// 记录本地异常日志
log.error("==前置通知异常==");
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
*
* @param joinPoint 切点
* @param log 日志注解
* @param operLog 操作日志对象
* @param jsonResult 返回值
* @throws Exception 异常
*/
public void getControllerMethodDescription(JoinPoint joinPoint, Log log, OperLog operLog, Object jsonResult) throws Exception {
// 设置action动作
operLog.setBusinessType(log.businessType().name());
// 设置标题
operLog.setTitle(log.title());
// 设置操作类型
operLog.setOperType(log.operType());
// 设置操作人类别
operLog.setOperatorType(log.operatorType().name());
// 是否需要保存request,参数和值
if (log.isSaveRequestData()) {
// 获取参数的信息,传入到数据库中。
setRequestValue(joinPoint, operLog);
}
// 是否需要保存response,参数和值
if (log.isSaveResponseData() && !StringUtils.isEmpty(jsonResult)) {
ErrorInfo errorInfo = JSON.parseObject(JSON.toJSONString(jsonResult), ErrorInfo.class);
// 运单
if (DataSourceEnum.ORDER.getName().equals(log.title())) {
Order order = JSONObject.parseObject(errorInfo.getData().toString(), Order.class);
operLog.setVehicleNo(order.getVehicleNo());
// 运单装卸货确认
if ("装卸货确认".equals(log.operType())) {
operLog.setOperType(order.getType() == 1 ? "卸货确认" : "装货确认");
}
}
// 车辆
if (DataSourceEnum.VEHICLE.getName().equals(log.title())) {
Vehicle vehicle = JSONObject.parseObject(errorInfo.getData().toString(), Vehicle.class);
operLog.setVehicleNo(vehicle.getVehicleNo());
// 车辆拉黑或拉白
if ("拉黑或拉白".equals(log.operType())) {
operLog.setOperType(vehicle.getIsLocked() == 1 ? "拉黑" : "拉白");
}
}
String jsonString = JSON.toJSONString(jsonResult);
operLog.setJsonResult(jsonString);
}
}
/**
* 获取请求的参数,放到log中
*
* @param joinPoint 切点
* @param operLog 操作日志
* @throws Exception 异常
*/
private void setRequestValue(JoinPoint joinPoint, OperLog operLog) throws Exception {
// 获取请求方法
String requestMethod = operLog.getRequestMethod();
// 新增或修改时
if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
String params = argsArrayToString(joinPoint.getArgs());
// 设置请求参数
operLog.setOperParam(params);
}
}
/**
* 参数拼装
*/
private String argsArrayToString(Object[] paramsArray) {
String params = "";
if (paramsArray != null && paramsArray.length > 0) {
for (Object o : paramsArray) {
if (!StringUtils.isEmpty(o) && !isFilterObject(o)) {
try {
Object jsonObj = JSON.toJSON(o);
params += jsonObj.toString() + " ";
} catch (Exception e) {
}
}
}
}
return params.trim();
}
/**
* 判断是否需要过滤的对象。
*
* @param o 对象信息。
* @return 如果是需要过滤的对象,则返回true;否则返回false。
*/
@SuppressWarnings("rawtypes")
public boolean isFilterObject(final Object o) {
Class<?> clazz = o.getClass();
if (clazz.isArray()) {
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
} else if (Collection.class.isAssignableFrom(clazz)) {
Collection collection = (Collection) o;
for (Object value : collection) {
return value instanceof MultipartFile;
}
} else if (Map.class.isAssignableFrom(clazz)) {
Map map = (Map) o;
for (Object value : map.entrySet()) {
Map.Entry entry = (Map.Entry) value;
return entry.getValue() instanceof MultipartFile;
}
}
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
|| o instanceof BindingResult;
}
例:
@Log(title = "运单", operType = "修改", businessType = BusinessType.UPDATE)
@PostMapping("/updateOrder")
public ErrorInfo updateOrder(HttpServletRequest request, OrderDto orderDto) {
return orderService.updateOrder(userInfo, orderDto);
}