Jaroslaw Pawlak
Jaroslaw Pawlak

Reputation: 5578

Implementing custom logging for Dropwizard resources

I have a dropwizard application with multiple resources. I need to implement some custom logging which should be the same for all resources and should contain things like URL, response time, response size and some data extracted from the request header. Generally, I would like to be able to specify what exactly I want there and in what format. I don't want to have to add code to any of the resources (because there is 50+ of them).

I did some searching and found a few interesting articles but I don't know how to implement it - a few things I tried didn't work:

I considered using aspect oriented programming, as all resources return Response, but AspectJ requires Spring which I don't want to bring into the project only for that reason.

I have also found InstrumentedHandler in Dropwizard's metrics, with this article it looks like exactly something that I need, but I cannot find any example how to plug it to the application.

Do you have any suggestions how to implement this logging?

Upvotes: 2

Views: 2306

Answers (1)

Jaroslaw Pawlak
Jaroslaw Pawlak

Reputation: 5578

This has done the trick for me:

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;
    }

}

And in the application's run method:

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

Upvotes: 1

Related Questions