1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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 }