Spring 流式响应的侦探日志记录

Spring sleuth logging for streaming response

我有一个休息 api 它接收一个 id 并流出一个文本文件。它是一个 Spring 引导项目,它具有 Spring Sleuth 依赖项。

对于 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?

我不知道你用的是哪个版本的 Sleuth 所以我来写伪代码

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();
        }

};