java - 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();
}
}
解决方案
日志处理程序使用内置的日志框架来记录其消息,因此您还可以使用以下内容更改其日志记录目标:
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();
}
}
}
});
推荐阅读
- android - 我想在 viewpager 中搜索和创建 listview 怎么可能
- java - Java Web,会话正在自动设置
- ruby-on-rails-5 - 单选按钮变成星星不起作用
- node.js - 如何在 MongoDB 中查找包含特定字符串的集合?
- android - 如何设置微调器的样式
- reactjs - 如何在我的项目中使用 cp-react-tree-table?
- java - 如何为将来的版本控制您的发布/订阅主题名称建模
- java - 如何初始化结果变量?
- python - 对于一列中的关键字(字符串)和另一列中的值(浮点数),我想计算每个值的单位范围内的 ok 关键字的数量
- php - 我找到了一个链接,但我不知道那是什么