EssentialFilter播放框架java(记录时间)

时间:2013-10-11 10:36:55

标签: java logging playframework playframework-2.1

我试图创建一个时间记录器过滤器来监视我的请求在使用java进入游戏框架2的时间,但是过滤器的java端的文档很弱。

有人能指出我如何实现这个目标吗?

scala指南位于 http://www.playframework.com/documentation/2.1.3/ScalaHttpFilters

1 个答案:

答案 0 :(得分:8)

所以你会从这样开始过滤:

public class TimeLoggingFilter implements EssentialFilter {

    public EssentialAction apply(final EssentialAction next) {

        return new TimeLoggingAction() {

            @Override
            public EssentialAction apply() {
                return next.apply();
            }

            @Override
            public Iteratee<byte[], SimpleResult> apply(final RequestHeader rh) {
                final long startTime = System.currentTimeMillis();

                return next.apply(rh).map(new AbstractFunction1<SimpleResult, SimpleResult>() {

                    @Override
                    public SimpleResult apply(SimpleResult v1) {
                        long time = logTime(rh, startTime);
                        List<Tuple2<String, String>> list = new ArrayList<Tuple2<String, String>>();
                        Tuple2<String, String> t =
                                new Tuple2<String, String>("Request-Time",
                                        String.valueOf(time));
                        list.add(t);
                        Seq<Tuple2<String, String>> seq = Scala.toSeq(list);
                        return v1.withHeaders(seq);
                    }

                    @Override
                    public <A> Function1<SimpleResult, A> andThen(Function1<SimpleResult, A> g) {
                        return g;
                    }

                    @Override
                    public <A> Function1<A, SimpleResult> compose(Function1<A, SimpleResult> g) {
                        return g;
                    }

                }, Execution.defaultExecutionContext());
            }


            private long logTime(RequestHeader request, long startTime) {
                long endTime = System.currentTimeMillis();
                long requestTime = endTime - startTime;
                Logger.info(request.uri() + " from " + request.remoteAddress() + " took " + requestTime + " ms");

                return requestTime;
            }
        };
    }

    public abstract class TimeLoggingAction extends
            AbstractFunction1<RequestHeader, Iteratee<byte[], SimpleResult>>
            implements EssentialAction {}
}

然后将其连接到Global.java

public <T extends EssentialFilter> Class<T>[] filters() {
        return new Class[] { TimeLoggingFilter.class  };
    }

我今天正在寻找一个类似的例子,并没有找到任何东西 - 但这似乎有效。