如何启用netty的内部日志记录?

时间:2018-03-12 17:52:00

标签: debugging logging netty

我尝试在我的项目中启用netty-logging。互联网上有很多例子 - 但最后它们并不适合我。

InternalLoggerFactory.setDefaultFactory(JdkLoggerFactory.INSTANCE);

p.addLast("logger", new LoggingHandler(LogLevel.DEBUG));

应该做的伎俩...

public final class EchoServer {
static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));

public static void main(String[] args) throws Exception {
    InternalLoggerFactory.setDefaultFactory(JdkLoggerFactory.INSTANCE);
    // Configure SSL.
    final SslContext sslCtx;
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100)
            .childHandler(new ChannelInitializer < SocketChannel > () {
                @Override
                public void initChannel(SocketChannel ch)
                throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    if (sslCtx != null) {
                        p.addLast(sslCtx.newHandler(ch.alloc()));
                    }
                    p.addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(getClass().getClassLoader())));
                    p.addLast(new ObjectEncoder());
                    p.addLast("logger", new LoggingHandler(LogLevel.DEBUG));
                    p.addLast(new EchoServerHandler());
                }
            });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        System.out.println("EchoServer listening at " + EchoServer.PORT);

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
  }
}

有没有人知道如何让它发挥作用?

2 个答案:

答案 0 :(得分:1)

为我解决了。如果您使用JdkLoggerFactory,请记住使用了jre \ lib \之外的logging.properties。 JUL的默认值是:

# Default global logging level.
# This specifies which kinds of events are logged across
# all loggers.  For any given facility this global level
# can be overriden by a facility specific level
# Note that the ConsoleHandler also has a separate level
# setting to limit messages printed to the console.
.level= INFO

我们生成了自己的属性文件,以便我们可以动态设置级别。

答案 1 :(得分:1)

您可以使用LoggingHandler来获取Netty的日志:

b.group(bossGroup, workerGroup)
 .channel(NioServerSocketChannel.class)
 .handler(new LoggingHandler(LogLevel.INFO))
 ...