目的:
在项目中,经常要使用日志管理系统来记录操作日志,在spring AOP的典型实际应用中就有日志管理的应用场景,在这篇老帖中给出简单的实现方案(代码有不妥的地方,老手勿喷,指出后我会虚心学习)
实践:
1.准备自定义注解
/**
* @Description:
* @Author: the_pure
* @CreateDate: 2021/11/18 10:05
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
/**
* 模块名
* @return
*/
String model();
/**
* 访问的接口名
* @return
*/
String method();
}
2.定义AOP切面
/**
* @Description: 日志切面
* @Author: the_pure
* @CreateDate: 2021/11/18 10:09
*/
@Aspect
@Component
public class LogHandler {
@Autowired
private ILogService iLogService;
ThreadLocal<Long> time = new ThreadLocal<>();
/**
* 日志注解作为切入点
*/
@Pointcut("@annotation(cn.zk.annatation.Log)")
public void pointcut() {
}
/**
* 环绕通知
*
* @return
*/
@Around("pointcut()&&@annotation(log)")
public Object around(ProceedingJoinPoint joinPoint, Log log) {
Map<String,Object> obj = null;
LogInfo logInfo = null;
try {
// 获取运行前时间
time.set(System.currentTimeMillis());
// 执行方法
obj = (Map<String,Object>)joinPoint.proceed();
// 获取运行时间
Long spendTime = System.currentTimeMillis() - time.get();
// 记录日志
logInfo = LogInfo.builder()
.model(log.model())
.method(log.method())
.spendTime(spendTime)
.build();
if(obj.get("success").equals(true)){
logInfo.setType(0);// 0 表示正常操作
} else {
logInfo.setType(1);// 1 表示错误操作
}
} catch (Throwable e) {
// 记录日志
logInfo = LogInfo.builder()
.type(1)
.model(log.model())
.method(log.method())
.build();
e.printStackTrace();
} finally {
iLogService.save(logInfo);
time.remove();
return obj;
}
}
}
3.使用将注解使用在需要做日志记录的接口上
/**
* @Description:
* @Author: the_pure
* @CreateDate: 2021/11/18 09:54
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService iUserService;
@Log(model = "用户模块",method ="用户新增")
@PostMapping
public Map<String,Object> add(@RequestBody User user) {
HashMap<String, Object> map = new HashMap<>();
try {
iUserService.add(user);
map.put("success",true);
} catch (Exception e) {
e.printStackTrace();
map.put("success",false);
} finally {
return map;
}
}
@DeleteMapping
@Log(model = "用户模块",method ="用户删除")
public Map<String,Object> remove(@RequestBody Long userId) {
HashMap<String, Object> map = new HashMap<>();
try {
iUserService.remove(userId);
map.put("success",true);
} catch (Exception e) {
e.printStackTrace();
map.put("success",false);
} finally {
return map;
}
}
}
4.其他辅助内容
UserServiceImpl
LogServiceImpl
验证:
测试新增用户接口(模拟异常操作)
测试删除用户接口(正常操作)