用于流式响应的Spring sleuth日志记录
我有一个RESTAPI,它接收一个id并输出一个文本文件。它是一个Spring引导项目,具有Spring Sleuth依赖项 所有日志都具有StreamingResponseBody回调中日志的正确跟踪ID execpt 这是我控制器中的代码:用于流式响应的Spring sleuth日志记录,spring,spring-cloud-sleuth,Spring,Spring Cloud Sleuth,我有一个RESTAPI,它接收一个id并输出一个文本文件。它是一个Spring引导项目,具有Spring Sleuth依赖项 所有日志都具有StreamingResponseBody回调中日志的正确跟踪ID execpt 这是我控制器中的代码: private static Logger logger = LoggerFactory.getLogger(TestController.class); @RequestMapping(value = "/file", method = Reque
private static Logger logger = LoggerFactory.getLogger(TestController.class);
@RequestMapping(value = "/file", method = RequestMethod.POST)
public ResponseEntity<StreamingResponseBody> file (@RequestParam("id") Long id) {
logger.info("handling /file");
StreamingResponseBody out = stream -> {
streamFile(id, stream);
logger.info("finished handling /file");
};
logger.info("Starting to stream file");
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=\"test.txt\"")
.contentType(MediaType.TEXT_PLAIN)
.body(out);
}
public void streamFile(Long id, OutputStream out) {
logger.info("Starting to write to output stream");
try {
// Retrieve data from database based on id
// and stream it out as it becomes available
// Using a hardcoded value here just as an example
String file = "foo";
out.write(file.getBytes());
} catch (IOException e) {
logger.error("Failed to write to output stream");
}
logger.info("Finished writing to output stream");
}
如何在streamFile方法中记录跟踪ID?我不知道您使用的是哪个版本的Sleuth,因此我将编写伪代码
StreamingResponseBody out = stream -> {
streamFile(id, stream);
logger.info("finished handling /file");
};
可能是
1.3.x
2.0.x
StreamingResponseBody out = stream -> {
streamFile(id, stream);
logger.info("finished handling /file");
};
final Span span = tracer.getCurrentSpan();
StreamingResponseBody out = stream -> {
Span continuedSpan = tracer.continueSpan(span)
streamFile(id, stream);
logger.info("finished handling /file");
tracer.closeSpan(continuedSpan);
};
final Span span = tracer.currentSpan();
StreamingResponseBody out = stream -> {
try (SpanInScope ws = tracer.withSpanInScope(span)) {
streamFile(id, stream);
logger.info("finished handling /file");
} finally {
span.finish();
}
};