22
33import io .netty .buffer .ByteBuf ;
44import io .netty .channel .*;
5- import java .io .ByteArrayOutputStream ;
65import java .io .IOException ;
7- import java .nio .charset .StandardCharsets ;
8- import org .apache .commons .io .HexDump ;
96import org .slf4j .Logger ;
107import org .slf4j .LoggerFactory ;
118
129public class LoggingHandler extends ChannelDuplexHandler {
1310
14- private static final Logger logger = LoggerFactory .getLogger (NettyHomekitHttpService .class );
11+ private static final Logger logger = LoggerFactory .getLogger (LoggingHandler .class );
12+ private static final char [] HEX_ARRAY = "0123456789ABCDEF" .toCharArray ();
1513
1614 @ Override
1715 public void channelRead (ChannelHandlerContext ctx , Object msg ) throws Exception {
@@ -32,19 +30,27 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
3230
3331 private void logBytes (String type , ByteBuf buf , ChannelHandlerContext ctx ) throws IOException {
3432 if (buf .readableBytes () > 0 ) {
35- try (ByteArrayOutputStream stream = new ByteArrayOutputStream ()) {
36- byte [] bytes = new byte [buf .readableBytes ()];
37- buf .getBytes (0 , bytes , 0 , bytes .length );
38- HexDump .dump (bytes , 0 , stream , 0 );
39- stream .flush ();
40- logger .trace (
41- String .format (
42- "%s %s [%s]:%n%s%n" ,
43- type ,
44- buf ,
45- ctx .channel ().remoteAddress ().toString (),
46- stream .toString (StandardCharsets .UTF_8 .name ())));
47- }
33+ byte [] bytes = new byte [buf .readableBytes ()];
34+ buf .getBytes (0 , bytes , 0 , bytes .length );
35+ logger .trace (
36+ String .format (
37+ "%s %s [%s]:%n%s%n" ,
38+ type , buf , ctx .channel ().remoteAddress ().toString (), bytesToHex (bytes )));
4839 }
4940 }
41+
42+ /*
43+ This method is licensed under CC-BY-SA and published on Stackoverflow
44+ https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java
45+ from the answer by Melquiades https://stackoverflow.com/users/2964945/melquiades
46+ */
47+ private String bytesToHex (byte [] bytes ) {
48+ char [] hexChars = new char [bytes .length * 2 ];
49+ for (int j = 0 ; j < bytes .length ; j ++) {
50+ int v = bytes [j ] & 0xFF ;
51+ hexChars [j * 2 ] = HEX_ARRAY [v >>> 4 ];
52+ hexChars [j * 2 + 1 ] = HEX_ARRAY [v & 0x0F ];
53+ }
54+ return new String (hexChars );
55+ }
5056}
0 commit comments