亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Spring Boot - 如何在一個地方記錄所有具有異常的請求和響應?

Spring Boot - 如何在一個地方記錄所有具有異常的請求和響應?

萬千封印 2019-08-30 15:38:40
我正在用彈簧靴做休息api。我需要使用輸入參數(使用方法,例如GET,POST等),請求路徑,查詢字符串,此請求的相應類方法,以及此操作的響應(成功和錯誤)來記錄所有請求。舉個例子:成功要求:http://example.com/api/users/1日志應該看起來像這樣:{   HttpStatus: 200,   path: "api/users/1",   method: "GET",   clientIp: "0.0.0.0",   accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",   method: "UsersController.getUser",   arguments: {     id: 1    },   response: {      user: {        id: 1,        username: "user123",        email: "[email protected]"         }   },   exceptions: []       }或者請求錯誤:http://example.com/api/users/9999日志應該是這樣的:    {       HttpStatus: 404,       errorCode: 101,                        path: "api/users/9999",       method: "GET",       clientIp: "0.0.0.0",       accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",       method: "UsersController.getUser",       arguments: {         id: 9999        },       returns: {                   },       exceptions: [         {           exception: "UserNotFoundException",           message: "User with id 9999 not found",           exceptionId: "adhaskldjaso98d7324kjh989",           stacktrace: ...................           ]           }我希望請求/響應成為單個實體,在成功和錯誤情況下都包含與此實體相關的自定義信息。在春天實現這一目標的最佳做法是什么,可能是過濾器?如果是的話,你能提供具體的例子嗎?(我已經使用了@ControllerAdvice和@ExceptionHandler,但正如我所提到的,我需要在單個位置(和單個日志)處理所有成功和錯誤請求)。
查看完整描述

3 回答

?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

javax.servlet.Filter如果沒有要求記錄已執行的java方法,則可以使用。


但是有了這個要求,你必須訪問存儲在其中handlerMapping的信息DispatcherServlet。也就是說,您可以覆蓋DispatcherServlet以完成請求/響應對的記錄。


以下是一個可以進一步增強和滿足您需求的想法示例。


public class LoggableDispatcherServlet extends DispatcherServlet {


    private final Log logger = LogFactory.getLog(getClass());


    @Override

    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {

        if (!(request instanceof ContentCachingRequestWrapper)) {

            request = new ContentCachingRequestWrapper(request);

        }

        if (!(response instanceof ContentCachingResponseWrapper)) {

            response = new ContentCachingResponseWrapper(response);

        }

        HandlerExecutionChain handler = getHandler(request);


        try {

            super.doDispatch(request, response);

        } finally {

            log(request, response, handler);

            updateResponse(response);

        }

    }


    private void log(HttpServletRequest requestToCache, HttpServletResponse responseToCache, HandlerExecutionChain handler) {

        LogMessage log = new LogMessage();

        log.setHttpStatus(responseToCache.getStatus());

        log.setHttpMethod(requestToCache.getMethod());

        log.setPath(requestToCache.getRequestURI());

        log.setClientIp(requestToCache.getRemoteAddr());

        log.setJavaMethod(handler.toString());

        log.setResponse(getResponsePayload(responseToCache));

        logger.info(log);

    }


    private String getResponsePayload(HttpServletResponse response) {

        ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);

        if (wrapper != null) {


            byte[] buf = wrapper.getContentAsByteArray();

            if (buf.length > 0) {

                int length = Math.min(buf.length, 5120);

                try {

                    return new String(buf, 0, length, wrapper.getCharacterEncoding());

                }

                catch (UnsupportedEncodingException ex) {

                    // NOOP

                }

            }

        }

        return "[unknown]";

    }


    private void updateResponse(HttpServletResponse response) throws IOException {

        ContentCachingResponseWrapper responseWrapper =

            WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);

        responseWrapper.copyBodyToResponse();

    }


}

HandlerExecutionChain - 包含有關請求處理程序的信息。


然后,您可以將此調度程序注冊如下:


    @Bean

    public ServletRegistrationBean dispatcherRegistration() {

        return new ServletRegistrationBean(dispatcherServlet());

    }


    @Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)

    public DispatcherServlet dispatcherServlet() {

        return new LoggableDispatcherServlet();

    }

這是日志的樣本:


http http://localhost:8090/settings/test

i.g.m.s.s.LoggableDispatcherServlet      : LogMessage{httpStatus=500, path='/error', httpMethod='GET', clientIp='127.0.0.1', javaMethod='HandlerExecutionChain with handler [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)] and 3 interceptors', arguments=null, response='{"timestamp":1472475814077,"status":500,"error":"Internal Server Error","exception":"java.lang.RuntimeException","message":"org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.RuntimeException","path":"/settings/test"}'}


http http://localhost:8090/settings/params

i.g.m.s.s.LoggableDispatcherServlet      : LogMessage{httpStatus=200, path='/settings/httpParams', httpMethod='GET', clientIp='127.0.0.1', javaMethod='HandlerExecutionChain with handler [public x.y.z.DTO x.y.z.Controller.params()] and 3 interceptors', arguments=null, response='{}'}


http http://localhost:8090/123

i.g.m.s.s.LoggableDispatcherServlet      : LogMessage{httpStatus=404, path='/error', httpMethod='GET', clientIp='127.0.0.1', javaMethod='HandlerExecutionChain with handler [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)] and 3 interceptors', arguments=null, response='{"timestamp":1472475840592,"status":404,"error":"Not Found","message":"Not Found","path":"/123"}'}

UPDATE


如果出現錯誤,Spring會自動進行錯誤處理。因此,BasicErrorController#error顯示為請求處理程序。如果要保留原始請求處理程序,則可以在調用spring-webmvc-4.2.5.RELEASE-sources.jar!/org/springframework/web/servlet/DispatcherServlet.java:971之前覆蓋此行為#processDispatchResult,以緩存原始處理程序。


查看完整回答
反對 回復 2019-08-30
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

不要寫任何攔截器,濾波器,組件,方面等,這是一個非常常見的問題,已經解決了很多次。Spring Boot有一個名為Actuator的模塊,它提供開箱即用的HTTP請求記錄。有一個端點映射到/trace(SB1.x)或/actuator/httptrace(SB2.0 +),它將顯示最近100個HTTP請求。您可以自定義它以記錄每個請求,或寫入數據庫。要獲得所需的端點,您需要執行器springboot依賴項,并且還要“查找”您正在尋找的端點,并可能設置或禁用它的安全性。

此外,此應用程序將在何處運行?你會使用PaaS嗎?例如,主機提供商Heroku提供請求記錄作為其服務的一部分,您無需進行任何編碼。


查看完整回答
反對 回復 2019-08-30
?
UYOU

TA貢獻1878條經驗 獲得超4個贊

Spring已經提供了一個完成這項工作的過濾器。將以下bean添加到您的配置中


@Bean

public CommonsRequestLoggingFilter requestLoggingFilter() {

    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();

    loggingFilter.setIncludeClientInfo(true);

    loggingFilter.setIncludeQueryString(true);

    loggingFilter.setIncludePayload(true);

    return loggingFilter;

}

不要忘記將日志級別更改org.springframework.web.filter.CommonsRequestLoggingFilter為DEBUG。


查看完整回答
反對 回復 2019-08-30
  • 3 回答
  • 0 關注
  • 1252 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號