首页 > 解决方案 > Netty LoggingHandler 到文本文件

问题描述

所以让这个小服务器启动并运行,在控制台中我可以看到很多关于网络的使用完整信息,但是,我不确定如何将 LoggingHandler 写入某种文本文件。有人试过吗?或者甚至是可能的?

public void run() {
        System.out.println("UDP Server is starting.");
        try{
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(nioEventLoopGroup)
                    .channel(NioDatagramChannel.class)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) {
                            channel.pipeline().addLast("UDP LOGS",new LoggingHandler(LogLevel.INFO));
                            channel.pipeline().addLast(new StringEncoder(), new StringDecoder());
                            channel.pipeline().addLast(
                                    new UdpServerHandler(viewModel));
                        }
                    });
            channelFuture = bootstrap.bind(port).sync();

        }
        catch (InterruptedException e) {
            System.err.println("UDP listener was interrupted and shutted down");
            e.getCause();
        }
    }

标签: javaloggingnettyhandler

解决方案


日志处理程序使用内置的日志框架来记录其消息,因此您还可以使用以下内容更改其日志记录目标:

    Logger log = Logger.getLogger(LoggingHandler.class.getName());
    log.setUseParentHandlers(false);
    log.addHandler(new FileHandler());

虽然 aFileHandler是记录文件的快速解决方案,但实际上使用起来相当烦人,因为它从系统属性而不是构造函数接受其日志记录属性(如目标文件)。

所以这意味着你必须编写自己的处理程序来以你想要的方式记录它们:

    Writer writer = Files.newBufferedWriter(FileSystems.getDefault().getPath("test.log"));
    log.addHandler(new Handler() {

        @Override
        public void close() throws SecurityException {
            synchronized (this) {
                try {
                    writer.close();
                } catch (IOException ex) {
                    // TODO: better error handling
                    ex.printStackTrace();
                }
            }
        }

        @Override
        public void flush() {
            synchronized (this) {
                try {
                    writer.flush();
                } catch (IOException ex) {
                    // TODO: better error handling
                    ex.printStackTrace();
                }
            }
        }

        @Override
        public void publish(LogRecord record) {
            // TODO: Format the logrecord better
            String formatted = record.getLevel() + ": " + record.getMessage() + "\n";
            synchronized (this) {
                try {
                    writer.write(formatted);
                } catch (IOException ex) {
                    // TODO: better error handling
                    ex.printStackTrace();
                }
            }
        }

    });

推荐阅读