跟踪 Spring boot 中处理请求过程中生成的日志

问题描述 投票:0回答:1

在我的 Spring 应用程序中,如果

debug
请求参数设置为
true
,我希望将处理应用程序时生成的日志作为响应的一部分返回。如何捕获特定于该请求的日志?

我有唯一的请求 ID,如果有帮助的话,也会记录这些 ID。

java spring spring-boot
1个回答
0
投票

在 Spring 中,使用 JUnit5,您可以使用扩展捕获输出并随后检查它。假设您有一个生成日志输出的标准 Spring 组件:

package bin.scratchpad;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class OutputCapture {

    public void produceOutput() {
        log.info("this is the output to be captured.");
    }
}

我选择了 Slf4j,但它也适用于其他记录器。现在,您可以在

OutputCaptureExtension
的帮助下捕获测试中的输出(请参阅此处 文档):

package bin.scratchpad;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;

@SpringBootTest
@ExtendWith(OutputCaptureExtension.class)
class OutputCaptureTest {

    @Autowired
    OutputCapture underTest;

    @Test
    void testOutputCapture(CapturedOutput output) {

        underTest.produceOutput();

        assertThat(output.getOut()).contains("this is the output to be captured.");
    }

}

这是一个集成测试,但它在单元测试中也同样有效。

output
对象提供对不同输出流
System.out
System.err
(或两者的组合)的访问。

可能值得注意的是,此方法测试输出,它不测试发送到记录器的数据。

© www.soinside.com 2019 - 2024. All rights reserved.