正在通过slf4j使用日志记录,我的项目已经用Log4j2设置。通常,我通过包装在RestTemplate周围的定制客户端进行集成,使用特定的日志逻辑记录http请求和响应,并以特定的标准化格式(通过xml定义)。
问题是,现在我无意中发现了一个可以实际使用SDK的集成,但问题是我的日志记录与Google客户端不太容易兼容。我已经浏览过不同的网站,寻找良好的实践,但不幸的是,我没有发现任何有形的。
如何为Google客户端设置Log4j2文件附录,以标准格式输出请求和响应日志?感谢良好的实践和指向新知识的要点。
发布于 2021-12-23 07:53:14
一种选择是向该类添加一个日志处理程序:com.google.api.client.http.HttpTransport,文档中概述了类似的方法,并从日志记录中提取请求和响应数据。这种方法的问题是数据是文本格式的,因为它毕竟是日志记录,需要再次解析。
我认为在这种情况下最安全和最灵活的方法是利用库提供的请求和拦截器功能。因此,我们可以在请求之前和之后添加自己的日志逻辑。这样,所有请求和响应数据都是可用的。
下面是一些示例代码:
import com.google.api.client.http.*;
import com.google.api.client.http.javanet.NetHttpTransport;
import java.io.IOException;
public class MyLogger {
static class MyInitializer implements HttpResponseInterceptor, HttpRequestInitializer, HttpExecuteInterceptor {
@Override
public void interceptResponse(HttpResponse response) throws IOException {
// perform response logging here
var request = response.getRequest();
System.out.println(
"RESPONSE: " + request.getRequestMethod() + " " + request.getUrl() + " " + response.getStatusCode()
);
}
@Override
public void initialize(HttpRequest request) throws IOException {
request.setResponseInterceptor(this);
request.setInterceptor(this);
}
@Override
public void intercept(HttpRequest request) throws IOException {
// perform request logging here
System.out.println("REQUEST: " + request.getRequestMethod() + " " + request.getUrl());
}
}
public static void main(String[] args) throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(new MyInitializer());
var request = requestFactory.buildGetRequest(new GenericUrl("http://example.com"));
request.execute();
}
}https://stackoverflow.com/questions/70348230
复制相似问题