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    *   https://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.ObjectUtil;
23  import io.netty.util.internal.logging.InternalLogLevel;
24  import io.netty.util.internal.logging.InternalLogger;
25  import io.netty.util.internal.logging.InternalLoggerFactory;
26  
27  /**
28   * Logs SPDY frames for debugging purposes.
29   */
30  public class SpdyFrameLogger extends ChannelDuplexHandler {
31  
32      private enum Direction {
33          INBOUND, OUTBOUND
34      }
35  
36      protected final InternalLogger logger;
37      private final InternalLogLevel level;
38  
39      public SpdyFrameLogger(InternalLogLevel level) {
40          this.level = ObjectUtil.checkNotNull(level, "level");
41          this.logger = InternalLoggerFactory.getInstance(getClass());
42      }
43  
44      @Override
45      public void channelRead(ChannelHandlerContext ctx, Object msg) {
46          if (acceptMessage(msg)) {
47              log((SpdyFrame) msg, Direction.INBOUND);
48          }
49          ctx.fireChannelRead(msg);
50      }
51  
52      @Override
53      public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
54          if (acceptMessage(msg)) {
55              log((SpdyFrame) msg, Direction.OUTBOUND);
56          }
57          ctx.write(msg, promise);
58      }
59  
60      private static boolean acceptMessage(Object msg) {
61          return msg instanceof SpdyFrame;
62      }
63  
64      private void log(SpdyFrame msg, Direction d) {
65          if (logger.isEnabled(level)) {
66              StringBuilder b = new StringBuilder(200)
67                  .append("\n----------------")
68                  .append(d.name())
69                  .append("--------------------\n")
70                  .append(msg)
71                  .append("\n------------------------------------");
72  
73              logger.log(level, b.toString());
74          }
75      }
76  }