【问题标题】:How do I setup baggage fields in Spring Cloud Sleuth for a Command Line Runner?如何在 Spring Cloud Sleuth 中为命令行运行程序设置行李字段?
【发布时间】:2021-10-29 20:36:51
【问题描述】:

我已在 Spring Boot 微服务中成功使用 Spring Cloud Sleuth,并且正在记录字段并通过 http 标头适当地发送。

我现在需要在 Spring Boot 命令行运行程序应用程序中集成用于日志记录和标头传播的相同过程,但看起来没有自动设置跟踪和跨度,因为它不在 Http 请求的中间(因为它是一个命令行应用程序)。我在日志中看不到这些字段(在日志配置中使用相同的 %X 格式)。

我查看了文档,但找不到此特定用例的任何示例。这可以在命令行运行器应用程序中实现吗?

【问题讨论】:

    标签: spring spring-boot command-line spring-cloud-sleuth


    【解决方案1】:

    要添加行李,您需要有一个跨度。当调用控制器时,Spring Cloud Sleuth 和 Spring Boot 会为您创建一个跨度。如果你想使用 CLI 应用程序做同样的事情,你需要自己创建 span。

    你有两个选择。

    Using API calls:

    Span span = this.tracer.nextSpan().name("mySpan");
    // do some work
    span.end(); // best to put it in finally to make sure span is always ended
    

    或者你can use annotations:

    @NewSpan
    public void doWork() {
    }
    

    如果你使用注解,请记住AOP proxies limitations。特别是自我调用(使用this 的调用)将不起作用。

    @SpringBootApplication
    public class ConsoleApplication 
      implements CommandLineRunner {
    
        @Override
        public void run(String... args) {
            doWork(); //this is the same as this.doWork();
        }
    
        @NewSpan
        public void doWork() {
        }
    }
    

    这不会起作用,因为doWork 不是通过 AOP 代理调用的。确保您注释了由 Spring 管理的组件,然后使用注入的实例。

    @SpringBootApplication
    public class ConsoleApplication 
      implements CommandLineRunner {
    
        @Autowired
        private MyService myService;
    
        @Override
        public void run(String... args) {
            myService.doWork();
        }
    
    }
    
    @Component
    class MyService {
    
        @NewSpan
        public void doWork() {
        }
    
    }
    

    在这种情况下,myService 不是MyService 的实例,而是一个检测代理。

    【讨论】:

    • 您好,感谢您的跟进!手动跟踪器设置实际上让我成功了,但看起来我无法记录任何内容,因为我在使用 Log4J2 时期望默认模板正常工作(每个 github.com/spring-cloud/spring-cloud-sleuth/issues/2008)所以更改我的格式得到了跟踪和跨度ID。不幸的是,当我通过跟踪器添加行李字段时,它们不会像请求上下文中的行李一样添加到后续的 WebClient(一个 bean)调用中。范围装饰器为日志做了它。 stackoverflow.com/a/66554834/16800757
    猜你喜欢
    • 2021-07-28
    • 2022-06-17
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 2016-12-29
    • 2020-05-09
    相关资源
    最近更新 更多