我想通过 api 端点/logs for dropwizard 流式传输日志。
这比我想象的要难。Dropwizard将通过config.yml读取配置,并将这些信息保密。而且我不知道在哪里可以找到记录所有内容的记录器?我错过了什么吗?
有没有其他方法可以做到这一点?
这是一个流式处理示例,您也可以在此处阅读:
在泽西岛流输出上调用 flush(( 不起作用
和
在泽西岛中使用流输出作为响应实体的示例
代码:
public class StreamingTest extends io.dropwizard.Application<Configuration> {
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
environment.jersey().property(ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, 0);
environment.jersey().register(Streamer.class);
}
public static void main(String[] args) throws Exception {
new StreamingTest().run("server", "/home/artur/dev/repo/sandbox/src/main/resources/config/test.yaml");
}
@Path("/log")
public static class Streamer {
@GET
@Produces("application/octet-stream")
public Response test() {
return Response.ok(new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
while (true) {
output.write("Test n".getBytes());
output.flush();
try {
Thread.sleep(1000); // simulate waiting for stream
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).build();
}
}
}
哪个做你想要的。
几点 线路evironment.jersey().property(ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, 0);
很重要。它告诉服务器在将输出返回给调用方之前不要缓冲输出。
此外,您需要通过调用 output.flush();
来显式清除输出
但是,这似乎是运送日志的错误方式。你有没有研究过即logstash?还是基于网络的追加器,将日志直接流式传输到您需要它们的位置?
希望有帮助,
--阿图尔