aop记录登录日志
2023-06-17 20:25:27 浏览: 899次
AI评分:88
原因:文章内容准确且实用,清晰介绍了Spring AOP记录登录日志的原理和实现,包括@Pointcut和@Before的使用、JoinPoint的信息获取,并结合RequestContextHolder获取IP地址。代码示例简洁有效,展示了完整的日志记录流程。但未涉及异常处理或数据库异步优化,可能在实战中需补充细节以提升健壮性。
在网站或者各种软件系统中,多多少少会有一些日志需要我们来记录,从而查看当前系统的运行状态。
对于springboot框架而言,可以采用aop面向切面编程的方式,在不改变原本业务的基础上来增加这个日志记录功能。以下为一个记录登录数据日志的aop代码,通过该代码,可以将用户登录ip、登录方法、登录信息、登录时间计入mysql数据库。@Pointcut设定了切入点,可以对目标方法进行而外扩展,通过@Before注解,实现在执行指定函数之前运行一些代码。JointPoint连接点记录了本次代理的函数的所有信息,包含函数本身元数据与形参值。
@Aspect
@Component
public class LoginAspect {
@Autowired
private LogService logService;
@Pointcut("execution(* top.dreamcenter.dreamcenter.controller.AdminController.check(..))")
public void pointFn(){}
@Before("pointFn()")
public void loginLog(JoinPoint joinPoint) {
MyLog myLog = new MyLog();
Object[] args = joinPoint.getArgs();
List<Object> list = Arrays.asList(args);
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes != null){
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
myLog.setType(LogType.LOGIN.toString());
myLog.setAddr(request.getRemoteAddr());
myLog.setRaw(list.toString());
logService.insert(myLog);
}
}
}
如果想要获取用户的ip等信息,需要借助 RequestContextHolder.getRequestAttributes() 方法来获取本次连接请求的上下文。
#springboot
- 上一篇:私人git远程仓库搭建(windows)
- 下一篇:短链接的实现