我有一个休息api,它接收一个id并流出一个文本文件。它是一个具有Spring Sleuth依赖性的Spring启动项目。
对于StreamingResponseBody的回调中的所有日志都有正确的跟踪ID execpt
这是我在控制器中的代码:
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");
}
这些是生成的日志:
2018-03-07 01:01:12.786 INFO [Test app,ca713bc7ad45ffdc,ca713bc7ad45ffdc,false] 6476 --- [nio-2000-exec-8] c.i.r.controller.TestController : handling /file
2018-03-07 01:01:12.788 INFO [Test app,ca713bc7ad45ffdc,ca713bc7ad45ffdc,false] 6476 --- [nio-2000-exec-8] c.i.r.controller.TestController : Starting to stream file
2018-03-07 01:01:12.881 INFO [Test app,,,] 6476 --- [ MvcAsync1] c.i.r.controller.TestController : Starting to write to output stream
2018-03-07 01:01:12.881 INFO [Test app,,,] 6476 --- [ MvcAsync1] c.i.r.controller.TestController : Finished writing to output stream
2018-03-07 01:01:12.881 INFO [Test app,,,] 6476 --- [ MvcAsync1] c.i.r.controller.TestController : finished handling /file
如何在streamFile方法中记录跟踪ID?
答案 0 :(得分:1)
我不知道你正在使用哪个版本的侦探,所以我会写伪代码
StreamingResponseBody out = stream -> {
streamFile(id, stream);
logger.info("finished handling /file");
};
可能是
1.3.x的
final Span span = tracer.getCurrentSpan();
StreamingResponseBody out = stream -> {
Span continuedSpan = tracer.continueSpan(span)
streamFile(id, stream);
logger.info("finished handling /file");
tracer.closeSpan(continuedSpan);
};
2.0.x的
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();
}
};