springboot请求url日志记录

@Order(5)
@Aspect
@Component
public class AnnotationInterceptor {

    private static Logger logger = LogManager.getLogger(AnnotationInterceptor.class.getName());

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) || @annotation(org.springframework.web.bind.annotation.GetMapping) || "
            + "@annotation(org.springframework.web.bind.annotation.PostMapping) || @annotation(org.springframework.web.bind.annotation.PutMapping) || @annotation(org.springframework.web.bind.annotation.DeleteMapping)")
    public void RequestMapping() {
    }

    @Around("RequestMapping()")
    public Object Interceptor(ProceedingJoinPoint joinPoint) throws Throwable {

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

//    String tok
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以通过Spring AOP实现这个功能。具体步骤如下: 1. 创建一个实体类,用于保存错误日志信息,包括用户信息、请求url、方法、参数、异常信息等。 2. 创建一个切面类,使用@Aspect注解标注,该切面类中定义一个@Before通知,用于捕获Controller中抛出的异常,并将异常信息和其他相关信息保存到数据库中。 3. 在切面类中通过@Pointcut注解指定切入点,即对哪些Controller中的方法进行切面处理。 4. 在切面类中使用@Autowired注解注入实体类对应的Repository,然后在@Before通知中调用Repository中的方法将错误信息保存到数据库中。 具体实现细节可以参考以下代码: ```java @Aspect @Component public class ErrorLogAspect { @Autowired private ErrorLogRepository errorLogRepository; @Pointcut("execution(* com.example.demo.controller..*.*(..))") public void logPointcut() {} @Before("logPointcut()") public void logError(JoinPoint joinPoint) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); ErrorLog errorLog = new ErrorLog(); errorLog.setUserId(request.getHeader("userId")); // 从请求头中获取用户信息 errorLog.setUrl(request.getRequestURI()); // 获取请求url errorLog.setMethod(joinPoint.getSignature().toShortString()); // 获取方法名 errorLog.setArgs(Arrays.toString(joinPoint.getArgs())); // 获取方法参数 errorLog.setExceptionMessage(getExceptionMessage(joinPoint)); // 获取异常信息 errorLogRepository.save(errorLog); // 保存错误日志到数据库 } private String getExceptionMessage(JoinPoint joinPoint) { Throwable ex = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(ExceptionHandler.class).value(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); return sw.toString(); } } ``` 其中,ErrorLog是保存错误日志信息的实体类,ErrorLogRepository是对应的Repository。在logError方法中,通过JoinPoint获取方法名、方法参数等信息,通过RequestContextHolder获取请求信息,最后将错误日志保存到数据库中。getExceptionMessage方法用于获取异常信息。在Controller中,要使用@ExceptionHandler注解来捕获异常,并将异常信息保存到数据库中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值