1、日志操作类型枚举
package com.xx.xxx.enums;
/**
* @description: 日志操作类型
* @author: fangzhao
* @create: 2020/3/24 13:09
* @update: 2020/3/24 13:09
*/
public enum LogOperateType {
/**
* 描述:日志操作类型定义
* @author fangzhao at 2020/4/7 16:55
*/
QUERY(1, "查询"),ADD(2, "新增"), MODIFY(3, "修改"),DELETE(4, "删除"),
UPLOAD(5, "上传"), DOWNLOAD(6, "下载"), IMPORT(7, "导入"), EXPORT(8, "导出"),
OTHER(9,"其它操作");
private final int code;
private final String msg;
LogOperateType(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
/**
* 枚举类型转换,由于构造函数获取了枚举的子类enums,让遍历更加高效快捷
* @param code 数据库中存储的自定义code属性
* @return code对应的枚举类
*/
public static LogOperateType locateEnum(int code) {
for(LogOperateType status : LogOperateType.values()) {
if(status.getCode() == code) {
return status;
}
}
throw new IllegalArgumentException("未知的枚举类型:" + code);
}
}
2、日志操作注解
package com.xx.xxx.aspects;
import com.xx.xxx.enums.LogOperateType;
import java.lang.annotation.*;
/**
* @description: 日志操作注解
* @author: fangzhao
* @create: 2020/3/24 13:09
* @update: 2020/3/24 13:09
*/
@Documented // 定义注解的保留策略
@Inherited // 说明子类可以继承父类中的该注解
@Retention(RetentionPolicy.RUNTIME) // 定义注解的保留策略
@Target(ElementType.METHOD) // 定义注解的作用目标
public @interface LogOperate {
String value() default "";
LogOperateType type() default LogOperateType.QUERY;
}
3、日志操作切面
package com.xx.xxx.aspects;
import com.xx.xxx.enums.LogOperateType;
import com.xx.xxx.tools.GsonUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* @description: 日志操作切面
* @author: fangzhao
* @create: 2020/3/24 13:09
* @update: 2020/3/24 13:09
*/
@Aspect
@Component
public class LogOperateAspect {
private static final Logger logger = LoggerFactory.getLogger(LogOperateAspect.class);
/**
* 描述:日志操作
*
* @param
* @return void
* @author fangzhao at 2020/4/7 16:52
*/
@Pointcut("@annotation(com.xx.xxx.aspects.LogOperate)")
public void logOperateAnnotation() {}
/**
* 描述:环绕通知
*
* @param joinPoint
* @return java.lang.Object
* @author fangzhao at 2020/4/7 16:54
*/
@Around("logOperateAnnotation()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
long beginTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LogOperate logOperate = method.getAnnotation(LogOperate.class);
String value = "";
String msg = "";
if (null != logOperate) {
// 注解上的描述
value = logOperate.value();
LogOperateType logOperateType = logOperate.type();
msg = logOperateType.getMsg();
}
// 请求的类名、方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
// 请求的参数
Object[] args = joinPoint.getArgs();
List<Object> list = new ArrayList<>();
String json = null;
if (null != args && 0 < args.length) {
for (Object arg : args) {
if (arg instanceof HttpServletResponse || arg instanceof HttpServletRequest) {
} else {
list.add(arg);
}
}
}
try {
json = GsonUtil.toJsonString(list);
} catch (Exception e) {
logger.error("JSON 转换异常:{}", e.getMessage());
}
logger.info("请求开始,对象:{},执行操作:{}, 类型:{}, 参数:{}", className + "-" + methodName, value, msg, json);
Object proceed = joinPoint.proceed();
long endTime = System.currentTimeMillis();
if (logger.isDebugEnabled()) {
logger.debug("请求结束,{},耗时: {} 最大内存: {}m 已分配内存: {}m 已分配内存中的剩余空间: {}m 最大可用内存: {}m",
proceed,
(endTime - beginTime),
Runtime.getRuntime().maxMemory() / 1024 / 1024,
Runtime.getRuntime().totalMemory() / 1024 / 1024,
Runtime.getRuntime().freeMemory() / 1024 / 1024,
(Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory()) / 1024 / 1024);
}
return proceed;
}
}
4、使用,在需要打印日志的方法上增加注解信息 LogOperate
@LogOperate(value = "新增数据标准信息", type = LogOperateType.ADD)
@PostMapping
public RetResult<String> add(@RequestBody @Validated DataStandardVo vo) {
if (null == vo) {
return RetResponse.makeRsp(CommonEnum.REQUEST_ENTITY_NOT_NULL);
}
if (StringUtils.isNotBlank(vo.getDataMark()) && !vo.getDataMark().startsWith(DataStandardConstants.DATA_STANDARD_PRE)) {
return RetResponse.makeErrRsp(MessageFormat.format("标准编码必须以{0}开头!", DataStandardConstants.DATA_STANDARD_PRE));
}
DataStandardEntity entity = new DataStandardEntity();
BeanUtils.copyProperties(vo, entity);
entity.setCreator(LoginUtil.getUsername(request));
entity.setCreateTime(LocalDateTime.now());
List<DataStandardAttrVo> extendInfos = vo.getExtendInfos();
entity.setExtendInfo(GsonUtil.toJsonString(extendInfos));
return dataStandardService.add(entity);
}
5、查看日志
20-11-26.15:46:50.741 [http-nio-30040-exec-5] INFO LogOperateAspect - 请求开始,对象:com.xx.xxx.controller.DataStandardController-add,执行操作:新增数据标准信息, 类型:新增, 参数:[{"id":null,"chineseName":"数据标准测试1126001","englishName":"test0930004","shortName":"71","standardDir":"","dataMark":"DS0930004","standardCode":"","codeId":8888,"extendInfos":[],"dirId":68,"status":1,"modifyTime":"2020-11-26 15:46:50"}]