第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

Spring Boot - 如何在一個(gè)地方記錄所有具有異常的請(qǐng)求和響應(yīng)?

Spring Boot - 如何在一個(gè)地方記錄所有具有異常的請(qǐng)求和響應(yīng)?

萬(wàn)千封印 2019-08-30 15:38:40
我正在用彈簧靴做休息api。我需要使用輸入?yún)?shù)(使用方法,例如GET,POST等),請(qǐng)求路徑,查詢字符串,此請(qǐng)求的相應(yīng)類方法,以及此操作的響應(yīng)(成功和錯(cuò)誤)來(lái)記錄所有請(qǐng)求。舉個(gè)例子:成功要求:http://example.com/api/users/1日志應(yīng)該看起來(lái)像這樣:{   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: "user123@example.com"         }   },   exceptions: []       }或者請(qǐng)求錯(cuò)誤:http://example.com/api/users/9999日志應(yīng)該是這樣的:    {       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: ...................           ]           }我希望請(qǐng)求/響應(yīng)成為單個(gè)實(shí)體,在成功和錯(cuò)誤情況下都包含與此實(shí)體相關(guān)的自定義信息。在春天實(shí)現(xiàn)這一目標(biāo)的最佳做法是什么,可能是過(guò)濾器?如果是的話,你能提供具體的例子嗎?(我已經(jīng)使用了@ControllerAdvice和@ExceptionHandler,但正如我所提到的,我需要在單個(gè)位置(和單個(gè)日志)處理所有成功和錯(cuò)誤請(qǐng)求)。
查看完整描述

3 回答

?
MMMHUHU

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊

javax.servlet.Filter如果沒(méi)有要求記錄已執(zhí)行的java方法,則可以使用。


但是有了這個(gè)要求,你必須訪問(wèn)存儲(chǔ)在其中handlerMapping的信息DispatcherServlet。也就是說(shuō),您可以覆蓋DispatcherServlet以完成請(qǐng)求/響應(yīng)對(duì)的記錄。


以下是一個(gè)可以進(jìn)一步增強(qiáng)和滿足您需求的想法示例。


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 - 包含有關(guān)請(qǐng)求處理程序的信息。


然后,您可以將此調(diào)度程序注冊(cè)如下:


    @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


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


查看完整回答
反對(duì) 回復(fù) 2019-08-30
?
拉莫斯之舞

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊

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

此外,此應(yīng)用程序?qū)⒃诤翁庍\(yùn)行?你會(huì)使用PaaS嗎?例如,主機(jī)提供商Heroku提供請(qǐng)求記錄作為其服務(wù)的一部分,您無(wú)需進(jìn)行任何編碼。


查看完整回答
反對(duì) 回復(fù) 2019-08-30
?
UYOU

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個(gè)贊

Spring已經(jīng)提供了一個(gè)完成這項(xiàng)工作的過(guò)濾器。將以下bean添加到您的配置中


@Bean

public CommonsRequestLoggingFilter requestLoggingFilter() {

    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();

    loggingFilter.setIncludeClientInfo(true);

    loggingFilter.setIncludeQueryString(true);

    loggingFilter.setIncludePayload(true);

    return loggingFilter;

}

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


查看完整回答
反對(duì) 回復(fù) 2019-08-30
  • 3 回答
  • 0 關(guān)注
  • 1262 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)