aop记录登录日志

前往原站点查看

2023-06-17 20:25:27

    在网站或者各种软件系统中,多多少少会有一些日志需要我们来记录,从而查看当前系统的运行状态。

    对于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() 方法来获取本次连接请求的上下文。



上一篇: 短链接的实现
下一篇: 私人git远程仓库搭建(windows)