实施用于Dropwizard资源的自定义日志记录



我有一个带有多个资源的Dropwizard应用程序。我需要实现一些自定义日志记录,这些日志记录应该对所有资源都相同,并且应该包含诸如url,响应时间,响应大小以及从请求标头中提取的一些数据。通常,我希望能够以什么格式指定我想要什么。我不想在任何资源中添加代码(因为其中有50多个)。

我进行了一些搜索,发现了一些有趣的文章,但我不知道该如何实施 - 我尝试过的一些事情不起作用:

  • drop-wizard请求响应记录
  • https://docs.codehaus.org/display/jetty/logging requests
  • http://jersey.576304.n2.nabble.com/logging-http-body-of-request-td7580414.html

我考虑使用面向方面的编程,因为所有资源都返回Response,但是AspectJ需要Spring,我不想仅出于此原因将其带入项目。

我还在Dropwizard的指标中找到了InstrumentedHandler,这本文看起来完全是我需要的东西,但是我找不到任何示例如何将其插入应用程序。

您是否有任何建议如何实施此记录?

这为我带来了技巧:

import com.sun.jersey.api.container.filter.LoggingFilter;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponse;
public class LogFilter extends LoggingFilter implements ContainerRequestFilter {
    private final ThreadLocal<Long> startTime = new ThreadLocal<>();
    @Override
    public ContainerRequest filter(ContainerRequest containerRequest) {
        // gets called when the request comes in
        startTime.set(System.currentTimeMillis());
        return containerRequest;
    }
    @Override
    public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
        // gets called when the response is about to be returned
        // do the logging here
        return response;
    }
}

以及应用程序的运行方法:

@Override
public void run(MyConfiguration configuration, Environment environment) {
    LogFilter logFilter = new LogFilter();
    environment.jersey().getResourceConfig().getContainerRequestFilters().add(logFilter);
    environment.jersey().getResourceConfig().getContainerResponseFilters().add(logFilter);
}

最新更新