如何使用 Dropwizard 1.0.2 中的 LoggingFeature 打印服务器响应?如何使用、打印服务器、Dropwizard、LoggingFeature

2023-09-06 11:19:36 作者:你我终年不遇

以下代码导致 JSON 服务器响应在 Dropwizard 0.9.2 和 1.0.2 中打印:

The following code results in JSON server responses being printed in Dropwizard 0.9.2 and 1.0.2:

return ClientBuilder
        .newBuilder()
        .build()
        .register(new LoggingFilter(Logger.getLogger(LoggingFilter.class.getName()), true))

例如:

Oct 21, 2016 7:57:42 AM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * Client response received on thread main
1 < 401
1 < Connection: keep-alive
1 < Content-Length: 49
1 < Content-Type: text/plain
1 < Date: Fri, 21 Oct 2016 07:57:42 GMT
1 < Server: […]
1 < WWW-Authenticate: Basic realm="[…]"
Credentials are required to access this resource.

javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized

但是,LoggingFilter 在 1.0.2 中已弃用,建议改用 LoggingFeature.在 LoggingFeature 文档中它说默认的详细程度是 LoggingFeature.Verbosity.PAYLOAD_TEXT,所以我期待以下代码仍能在 Dropwizard 1.0.2 中打印 JSON 服务器响应:

However, LoggingFilter is deprecated in 1.0.2, and it's recommended to use LoggingFeature instead. In the documentation of LoggingFeature it says that the default verbosity is LoggingFeature.Verbosity.PAYLOAD_TEXT, so I was expecting the following code to still print JSON server responses in Dropwizard 1.0.2:

return ClientBuilder
        .newBuilder()
        .build()
        .register(new LoggingFeature(Logger.getLogger(getClass().getName())))

日志只包含以下内容:

javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized

推荐答案

这就是诀窍:

new LoggingFeature(Logger.getLogger(getClass().getName()), Level.OFF, LoggingFeature.Verbosity.PAYLOAD_TEXT, 8192)

我猜客户端中的日志记录功能类似于过滤器,而不是预期的包含.

I'm guessing the logging feature in the client acts like a filter, rather than as an include as expected.