溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

AOP與Filter攔截請(qǐng)求打印日志的示例分析

發(fā)布時(shí)間:2021-07-26 14:10:41 來源:億速云 閱讀:160 作者:小新 欄目:編程語(yǔ)言

小編給大家分享一下AOP與Filter攔截請(qǐng)求打印日志的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

1 . Http請(qǐng)求攔截器(Filter) : 從HttpServletRequest獲取基本的請(qǐng)求信息

import name.ealen.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by EalenXie on 2018/9/7 15:56.
 * Http請(qǐng)求攔截器,日志打印請(qǐng)求基本相關(guān)信息
 */
@Configuration
public class FilterConfiguration {

  private static final Logger log = LoggerFactory.getLogger(FilterConfig.class);

  @Bean
  @Order(Integer.MIN_VALUE)
  @Qualifier("filterRegistration")
  public FilterRegistrationBean filterRegistration() {
    FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
    registration.setFilter(controllerFilter());
    registration.addUrlPatterns("/*");
    return registration;
  }

  private Filter controllerFilter() {
    return new Filter() {
      @Override
      public void init(FilterConfig filterConfig) {
        log.info("ControllerFilter init Success");
      }

      @Override
      public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestId = request.getHeader("Request-Id");
        if (requestId == null) requestId = request.getRequestedSessionId();
        System.out.println();
        log.info("Http Request Request-Id : " + requestId);
        log.info("Http Request Information : {\"URI\":\"" + request.getRequestURL() +
            "\",\"RequestMethod\":\"" + request.getMethod() +
            "\",\"ClientIp\":\"" + HttpUtil.getIpAddress(request) +
            "\",\"Content-Type\":\"" + request.getContentType() +
            "\"}");
        chain.doFilter(request, response);
      }

      @Override
      public void destroy() {
        log.info("ControllerFilter destroy");
      }
    };
  }
}

2 . Controller的攔截AOP : 獲取 請(qǐng)求的對(duì)象,請(qǐng)求參數(shù),返回?cái)?shù)據(jù),請(qǐng)求返回狀態(tài),內(nèi)部方法耗時(shí)。

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by EalenXie on 2018/9/7 14:19.
 * AOP打印日志 : 請(qǐng)求的對(duì)象,請(qǐng)求參數(shù),返回?cái)?shù)據(jù),請(qǐng)求狀態(tài),內(nèi)部方法耗時(shí)
 */
@Aspect
@Component
public class ControllerInterceptor {

  private static final Logger log = LoggerFactory.getLogger(ControllerInterceptor.class);
  @Resource
  private Environment environment;

  @Around(value = "execution (* name.ealen.web.*.*(..))")
  public Object processApiFacade(ProceedingJoinPoint pjp) {
    String appName;
    try {
      appName = environment.getProperty("spring.application.name").toUpperCase();
    } catch (Exception e) {
      appName = "UNNAMED";
    }
    long startTime = System.currentTimeMillis();
    String name = pjp.getTarget().getClass().getSimpleName();
    String method = pjp.getSignature().getName();
    Object result = null;
    HttpStatus status = null;
    try {
      result = pjp.proceed();
      log.info("RequestTarget : " + appName + "." + name + "." + method);
      log.info("RequestParam : " + JSON.toJSON(pjp.getArgs()));
      if (result instanceof ResponseEntity) {
        status = ((ResponseEntity) result).getStatusCode();
      } else {
        status = HttpStatus.OK;
      }
    } catch (Throwable throwable) {
      status = HttpStatus.INTERNAL_SERVER_ERROR;
      result = new ResponseEntity<>("{\"Internal Server Error\" : \"" + throwable.getMessage() + "\"}", status);
      throwable.printStackTrace();
    } finally {
      log.info("ResponseEntity : {" + "\"HttpStatus\":\"" + status.toString() + "\"" + ",\"ResponseBody\": " + JSON.toJSON(result) + "}");
      log.info("Internal Method Cost Time: {}ms", System.currentTimeMillis() - startTime);
    }
    return result;
  }
}

3 . 提供一個(gè)簡(jiǎn)單的restfull接口 :

package name.ealen.web;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by EalenXie on 2018/9/7 14:24.
 */
@RestController
public class SayHelloController {

  @RequestMapping("/sayHello")
  public String sayHello() {
    return "hello world";
  }

  @RequestMapping("/say")
  public ResponseEntity<?> say(@RequestBody Object o) {
    return new ResponseEntity<>(o, HttpStatus.OK);
  }

}

4 . 使用Postman進(jìn)行基本測(cè)試 :

AOP與Filter攔截請(qǐng)求打印日志的示例分析

5 . 控制臺(tái)可以看到基本效果 :

AOP與Filter攔截請(qǐng)求打印日志的示例分析

以上是“AOP與Filter攔截請(qǐng)求打印日志的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI