简体   繁体   中英

Spring Boot custom starter for logging and distributed tracing

I'm working on a custom spring boot starter, with the purpose of providing an auto configuration for all the spring boot applications that we have in our distributed system, so this way, every time a configuration needs to be changed, it can be done in one place, instead of going across all different applications applying the changes, instead just a version update of the dependency is sufficient.

Since the topics I want to cover are logging and distributed tracing, for now sticking to logback, but thinking of providing also log4j2 support in the future, the starter includes the following dependencies:

  • spring-boot-starter-web
  • spring-cloud-starter-sleuth

My first take on this was to include a logback.xml file in the src/main/resources folder of the autoconfigure module of the starter, and the applications consuming the starter get the configuration.

The problem i'm having is, when Sleuth is in the classpath, when the EnvironmentPostProcessor updates the level pattern with the [app name, traceId, spanId, exported] tuple, the app name that appears is bootstrap instead of the name defined with the spring.application.name in the application.yml file of the application using the starter, not sure why, could not find a clue on the reason :(

So, to solve this issue I did the following:

  • replaced in the pattern ${LOG_LEVEL_PATTERN:-%5p} with %5p , and add somewhere else in the pattern the tracing info with [%X{X-B3-TraceId:-},%X{X-B3-SpanId:-}]
  • use a filter, autowiring with @Value("${spring.application.name}") and then MDC#put the application name.

Then i realized, this approach would only work for HTTP requests, but nothing else, so that is not good enough, as the applications also make use of asynchronous communication with JMS / Spring Cloud Stream.

Then I thought of adding the application name to MDC including a ApplicationContextInitializer thinking that it would make it available for all the use cases (HTTP requests, messaging, etc). But sadly, the value was present for the logs during the startup of the application, and then was gone for the HTTP requests (haven't tried messaging yet, but the gut feeling is that it won't be present there either).

So the question is, since i'm kind of stuck and don't know where else to look, what would be the best approach/mechanism to achieve getting the value of spring.application.name into the MDC so it can appear in every log?

Thanks in advance!

It's enough to provide the name in bootstrap.yml . That way you'll see the spring application name in all the logs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM