View Javadoc

1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.example.spdy.client;
17  
18  import io.netty.channel.ChannelDuplexHandler;
19  import io.netty.channel.ChannelHandlerContext;
20  import io.netty.channel.ChannelPromise;
21  import io.netty.handler.codec.spdy.SpdyFrame;
22  import io.netty.util.internal.logging.InternalLogLevel;
23  import io.netty.util.internal.logging.InternalLogger;
24  import io.netty.util.internal.logging.InternalLoggerFactory;
25  
26  /**
27   * Logs SPDY frames for debugging purposes.
28   */
29  public class SpdyFrameLogger extends ChannelDuplexHandler {
30  
31      private enum Direction {
32          INBOUND, OUTBOUND
33      }
34  
35      protected final InternalLogger logger;
36      private final InternalLogLevel level;
37  
38      public SpdyFrameLogger(InternalLogLevel level) {
39          if (level == null) {
40              throw new NullPointerException("level");
41          }
42  
43          logger = InternalLoggerFactory.getInstance(getClass());
44          this.level = level;
45      }
46  
47      @Override
48      public void channelRead(ChannelHandlerContext ctx, Object msg) {
49          if (acceptMessage(msg)) {
50              log((SpdyFrame) msg, Direction.INBOUND);
51          }
52          ctx.fireChannelRead(msg);
53      }
54  
55      @Override
56      public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
57          if (acceptMessage(msg)) {
58              log((SpdyFrame) msg, Direction.OUTBOUND);
59          }
60          ctx.write(msg, promise);
61      }
62  
63      private static boolean acceptMessage(Object msg) {
64          return msg instanceof SpdyFrame;
65      }
66  
67      private void log(SpdyFrame msg, Direction d) {
68          if (logger.isEnabled(level)) {
69              StringBuilder b = new StringBuilder(200)
70                  .append("\n----------------")
71                  .append(d.name())
72                  .append("--------------------\n")
73                  .append(msg)
74                  .append("\n------------------------------------");
75  
76              logger.log(level, b.toString());
77          }
78      }
79  }