可以通过自定义注解和 Spring AOP 来实现记录日志的功能。

首先,定义一个自定义注解,用于标记需要记录日志的方法:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
    String value() default '';
}

然后,在需要记录日志的方法上添加该注解:

@Service
public class UserServiceImpl implements UserService {
    
    @Log('查询用户信息')
    @Override
    public User getUserById(Long id) {
        // 查询用户信息
    }
    
    // ...
}

接下来,定义一个切面类,用于在方法执行前后记录日志:

@Aspect
@Component
public class LogAspect {
    
    @Autowired
    private HttpServletRequest request;
    
    @Around('@annotation(com.example.demo.annotation.Log)')
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法上的注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Log logAnnotation = signature.getMethod().getAnnotation(Log.class);
        String logInfo = logAnnotation.value();
        
        // 记录日志
        String ip = request.getRemoteAddr();
        String method = joinPoint.getTarget().getClass().getName() + '.' + signature.getName();
        String params = Arrays.toString(joinPoint.getArgs());
        String logMsg = String.format('IP:%s, Method:%s, Params:%s, LogInfo:%s', ip, method, params, logInfo);
        System.out.println(logMsg);
        
        // 执行方法
        Object result = joinPoint.proceed();
        
        return result;
    }
}

在切面类中,通过 @Around 注解指定切点为使用 @Log 注解的方法,然后在方法执行前后记录日志。

最后,启动应用程序,调用需要记录日志的方法,即可在控制台中看到日志输出。

需要注意的是,为了获取用户的 IP 地址,需要在 Spring Boot 中配置 Tomcat 的 RemoteIpValve。在 application.properties 中添加以下配置:

server.tomcat.remote-ip-header=x-forwarded-for
server.tomcat.protocol-header=x-forwarded-proto

这样,就可以通过 request.getRemoteAddr() 获取用户的 IP 地址了。

Spring AOP 自定义注解实现日志记录功能

原文地址: https://www.cveoy.top/t/topic/kRY1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录