user3761024
user3761024

Reputation: 49

How to add request filters in Play framework?

I would like to show in my logs, the time that could takes every request or action..

I added this class to my controller but nothing happen in my log!!!! what should i do to show request time in my log please ?

thank you in advance. Reference of Class

import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import javax.inject.Inject;
import akka.stream.Materializer;
import play.Logger;
import play.mvc.*;

public class LoggingFilter extends Filter {

    @Inject
    public LoggingFilter(Materializer mat) {
        super(mat);
    }

    @Override
    public CompletionStage<Result> apply(
            Function<Http.RequestHeader, CompletionStage<Result>> nextFilter,
            Http.RequestHeader requestHeader) {
        long startTime = System.currentTimeMillis();
        return nextFilter.apply(requestHeader).thenApply(result -> {
            long endTime = System.currentTimeMillis();
            long requestTime = endTime - startTime;

            Logger.info("{} {} took {}ms and returned {}",
                requestHeader.method(), requestHeader.uri(), requestTime, result.status());

            return result.withHeader("Request-Time", "" + requestTime);
        });
    }
}

Upvotes: 2

Views: 5284

Answers (1)

Steve Chaloner
Steve Chaloner

Reputation: 8202

You need to define your filter chain - see this section of documentation for the official guide.

import filters.LoggingFilter;
import play.http.DefaultHttpFilters;
import javax.inject.Inject;

public class Filters extends DefaultHttpFilters {
  @Inject
  public Filters(LoggingFilter logging) {
    super(logging);
  }
}

If your Filters class is in the root package, you don't need to change anything in your application.conf. For the standard Play package structure, the root package is at the same level as controllers and views, and the Filters class itself will not have package as the first line of the source file.

+- controllers
| \ App.java
+- filters
| \ LoggingFilter.java
- Filters.java

If you have it somewhere else, say, com.example.filters, you need to declare it in application.conf.

play.http.filters=com.example.Filters

Upvotes: 3

Related Questions