因此,这台小型服务器已经启动并运行,并且在控制台中可以看到很多有关网络的完整使用信息,但是,我不确定如何将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();
}
}
答案 0 :(得分:0)
日志记录处理程序使用内置日志记录框架记录其消息,因此您还可以使用以下方法更改其记录目标:
Logger log = Logger.getLogger(LoggingHandler.class.getName());
log.setUseParentHandlers(false);
log.addHandler(new FileHandler());
尽管FileHandler
是一种记录日志文件的快速解决方案,但实际上它很烦人使用,原因是它从系统属性而不是构造函数中接受其记录属性(如目标文件)
因此,这意味着您必须编写自己的Handler才能以要记录的方式记录事物:
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();
}
}
}
});