日志标签
@ControllerLog
@PostMapping(value = "/getLog")
@ResponseBody
@ApiOperation("查询日志")
@ControllerLog(description = "查询日志", logLevel = 6)
public ResponseResult getLogList(@RequestBody Map<String, String> request) {
return logService.getLogList(request);
}
主体代码
import java.lang.annotation.*;
/**
* 配置日志注解
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ControllerLog {
// 操作描述
String description() default "";
// 日志级别 默认级别为信息
int logLevel() default 6;
}
/**
* 日志切面
*/
@Aspect
@Component
public class LogAspect {
@Autowired
private AppOperateLogMapper appOperateLogMapper;
/**
* 切点
*/
@Pointcut("@annotation(com.jump.jhm.log.ControllerLog)")
public void controllerAspect() {
}
@Around("controllerAspect()")
public Object doBefore(ProceedingJoinPoint joinPoint) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
OperateLog operateLog = new OperateLog();
// 获取方法签名
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
// 获取目标方法
Method method = signature.getMethod();
Object obj = null;// 调用执行目标方法
try {
operateLog.setId(UUID.randomUUID().toString());
ControllerLog controllerLog = method.getAnnotation(ControllerLog.class);
// 获取描述
String description = controllerLog.description();
operateLog.setContent(description);
// 日志级别
int logLevel = controllerLog.logLevel();
operateLog.setLevel(String.valueOf(logLevel));
operateLog.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
operateLog.setUserName(System.getProperty("user.name"));
obj = joinPoint.proceed();
if (obj instanceof ResponseResult) {
ResponseResult responseResult = (ResponseResult) obj;
// 根据返回状态码进行日志记录
if (responseResult.getCode() == 200) {
// 操作成功
operateLog.setState("1");
} else {
// 操作失败
operateLog.setState("0");
}
}
// 插库
appOperateLogMapper.insertLog(operateLog);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return obj;
}
}