1
votes

I have some spring service that can submit some AWS batch job. This is simple spring batch job that invoke requst to external service. And i want to propagate traceId that generated in my service by including "org.springframework.cloud:spring-cloud-starter-sleuth" lib into classpath , to this job and add "TraceRestTemplateInterceptor" interceptor to external request initilaized with this traceId.

How can i do that? How can i initilaze interceptor which will put existing traceId from application parameter, environment, properties? Or may be need to create some configuration beans?

UPDATE:

Simplified example:

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
   Logger logger = LoggerFactory.getLogger(DemoApplication.class);

   public static void main(String[] args) {
       SpringApplication.run(DemoApplication.class, args);
   }

   @Bean
   public RestTemplate restTemplate() {
     return new RestTemplate();
   }

   //@Autowired
   //RestTemplate restTemplate;

   @Override
   public void run(String... args) {
       logger.info("Hello, world!");
       //restTemplate.getForObject("some_url", String.class);
   }
}

File application.properties:

 x-b3-traceId=98519d97ce87553d

File build.gradle:

 dependencies {
    implementation('org.springframework.cloud:spring-cloud-starter-sleuth')
 }

Output:

INFO [-,,,] 15048 --- [           main] com.example.demo.DemoApplication         : Hello, world!

First of all, I want to see here traceId which initilized in application.properties. Secondly, when uncomment resttemplate clause, this traceId propagated into request.

Is it possible?

3

3 Answers

1
votes

Resolved this issue only by manually putting into request HEADER key "X-B3-TRACEID" with corresponding value, which is inserted by external application as system property when submits target spring boot application. And manually inserting this key in MDC. Example, this snipet from spring boot application that must get traceId and propagate:

@Bean
public void setTraceIdToMDC(@Value("${x.b3.traceid}") String traceId) {
  MDC.put("x-b3-traceId", traceId);
}

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

@Bean
public CommandLineRunner commandLineRunnerer(RestTemplate restTemplate, @Value("${x.b3.traceid}") String traceId) {
    return args -> {
        MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        header.add("X-B3-TRACEID", traceId);

        HttpEntity httpEntity = new HttpEntity(header);

        logger.info("Execute some request"); //<-- prints expected traceId
        restTemplate.exchange("some_url", HttpMethod.GET, httpEntity, String.class);
    };
}
1
votes

You can get the bean:

@Autowired private Tracer tracer;

And get the traceId with

tracer.getCurrentSpan().traceIdString();

0
votes

Just add the dependency to the classpath and set rest template as a bean. That's enough.