|
1 | 1 | package com.beowulfe.hap.impl.http.impl; |
2 | 2 |
|
3 | 3 | import io.netty.buffer.ByteBuf; |
| 4 | +import io.netty.channel.ChannelDuplexHandler; |
4 | 5 | import io.netty.channel.ChannelHandlerContext; |
5 | | -import io.netty.channel.ChannelInboundHandlerAdapter; |
| 6 | +import io.netty.channel.ChannelPromise; |
6 | 7 |
|
7 | | -import java.io.File; |
8 | | -import java.io.FileOutputStream; |
| 8 | +import java.io.ByteArrayOutputStream; |
9 | 9 | import java.io.IOException; |
10 | 10 |
|
11 | | -public class LoggingHandler extends ChannelInboundHandlerAdapter { |
12 | | - |
13 | | - private final FileOutputStream fos; |
| 11 | +import org.apache.commons.io.HexDump; |
| 12 | +import org.slf4j.Logger; |
| 13 | +import org.slf4j.LoggerFactory; |
| 14 | + |
| 15 | +public class LoggingHandler extends ChannelDuplexHandler { |
14 | 16 |
|
15 | | - public LoggingHandler() throws IOException { |
16 | | - File file = File.createTempFile("hap", "log"); |
17 | | - fos = new FileOutputStream(file); |
18 | | - System.out.println("Logging to "+file.getCanonicalPath()); |
19 | | - } |
| 17 | + private final static Logger logger = LoggerFactory.getLogger(NettyHomekitHttpService.class); |
20 | 18 |
|
21 | 19 | @Override |
22 | 20 | public void channelRead(ChannelHandlerContext ctx, Object msg) |
23 | 21 | throws Exception { |
24 | | - if (msg instanceof ByteBuf) { |
25 | | - ByteBuf buf = (ByteBuf) msg; |
26 | | - buf.getBytes(0, fos, buf.readableBytes()); |
27 | | - fos.flush(); |
| 22 | + if (logger.isTraceEnabled()) { |
| 23 | + if (msg instanceof ByteBuf) { |
| 24 | + logBytes("READ", (ByteBuf) msg, ctx); |
| 25 | + } |
28 | 26 | } |
29 | 27 | super.channelRead(ctx, msg); |
30 | 28 | } |
31 | 29 |
|
32 | 30 | @Override |
33 | | - public void channelInactive(ChannelHandlerContext ctx) throws Exception { |
34 | | - fos.close(); |
| 31 | + public void write(ChannelHandlerContext ctx, Object msg, |
| 32 | + ChannelPromise promise) throws Exception { |
| 33 | + if (logger.isTraceEnabled()) { |
| 34 | + if (msg instanceof ByteBuf) { |
| 35 | + logBytes("WRITE", (ByteBuf) msg, ctx); |
| 36 | + } |
| 37 | + } |
| 38 | + super.write(ctx, msg, promise); |
| 39 | + } |
| 40 | + |
| 41 | + private void logBytes(String type, ByteBuf buf, ChannelHandlerContext ctx) throws IOException { |
| 42 | + try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { |
| 43 | + byte[] bytes = new byte[buf.readableBytes()]; |
| 44 | + buf.getBytes(0, bytes, 0, bytes.length); |
| 45 | + HexDump.dump(bytes, 0, stream, 0); |
| 46 | + stream.flush(); |
| 47 | + logger.trace(String.format("%s %s [%s]:\n%s\n", type, buf, ctx.channel().remoteAddress().toString(), |
| 48 | + stream.toString())); |
| 49 | + } |
35 | 50 | } |
36 | 51 | } |
0 commit comments