在Grails 4中捕获请求主体内容以进行日志记录

问题描述 投票:0回答:1

使用Grails 4构建新的API,我希望可以选择记录完整的请求(标​​头,方法,内容等)。我可以在Interceptor中看到该请求,但是内容只能被读取一次(使用HttpServletRequest.getInputStream()),因此在Interceptor中对其进行读取会阻止该内容在Controller中可用。

关于堆栈溢出,对此已有一些类似的问题,可以通过使用Grails过滤器解决此需求。

根据Grails的文档Filters are now considered deprecated (as of v3.0), and Interceptors should instead be used,我不想走这条路的一个原因是。不幸的是,我无法找到与Interceptor合作的解决方案。我自己尝试了几种解决方案,其中包括将请求包装在HttpServletRequestWrapper中以缓存正文内容,并在尝试使其与Interceptor一起使用时遇到了与其他问题相同的问题。

[我已经看到使用Java Servlet过滤器的建议,与Grails过滤器有什么不同,或者是否也应避免使用,这并不明显。

grails
1个回答
0
投票

添加的PoC项目:https://github.com/majkelo/grails4requestinterceptor

基本上添加了一个拦截器PROJECT/grails-app/controllers/testrequest/RequestModificatorInterceptor.groovy(对所有请求进行修改):

package testrequest


class RequestModificatorInterceptor {

    RequestModificatorInterceptor() {
        match(controller: "*", action: "*")
    }

    boolean before() {
        println "INSIDE INTERCEPTOR; BEFORE"
        println  params
        println request.properties
        params.qwe = 3
        true
    }

    boolean after() {
        true
    }

    void afterView() {
    // no-op
    }
}

和测试控制器PROJECT/grails-app/controllers/testrequest/TestController.groovy

package testrequest

import grails.converters.JSON

class TestController {

    def index() {
        println "INSIDE CONTROLLER"
        println params
        params.asd = 4
        render params as JSON
    }
}

它是拦截器中的读/修改请求,并且在控制器中:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.