Unable to get logback-spring.xml property file usi

2019-02-23 09:01发布

问题:

I'm using Discovery first bootstrap feature and Consul as a Discovery Server, url to Config Server is located during start-up and I was able to get application.properties. I need also to get logback-spring.xml configuration from Config server and I don't know how.

What should I specify in logging.config={???}logback-spring.xml property to not hardcode url to Config Server?

Before Consul integration I was using url formed according to Serving Plain text documentation with hardcoded Config server url in properties and it was working fine, but now we want to avoid this.

From what I debugged there is no usage of Discovery client during reinitializing logging system in PropertySourceBootstrapConfiguration.

回答1:

I used Customizing Bootstrap Configuration to resolve my issue in a 'custom' way because I didn't find the solution in the documentation and source code.

Example: Add new file src/main/resources/META-INF/spring.factories and add there custom bootstrap configuration: org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator

In CustomPropertySourceLocator create property that will point to config server url (looked up via discovery)

@Configuration
public class CustomPropertySourceLocator implements PropertySourceLocator {

  private final String configServiceName;
  private final DiscoveryClient discoveryClient;

  public CustomPropertySourceLocator(
      @Value("${spring.cloud.config.discovery.service-id}") String configServiceName,
      DiscoveryClient discoveryClient){
    this.configServiceName = configServiceName;
    this.discoveryClient = discoveryClient;
  }

  @Override
  public PropertySource<?> locate(Environment environment) {
    List<ServiceInstance> instances = this.discoveryClient.getInstances(this.configServiceName);
    ServiceInstance serviceInstance = instances.get(0);

    return new MapPropertySource("customProperty",
      Collections.singletonMap("configserver.discovered.uri", serviceInstance.getUri()));
  }
}

In code above we created custom property source that will have one property configserver.discovered.uri. We can use this property in our code (using @Value) or in other property files (even if they are located in the config-server storage).

logging.config=${configserver.discovered.uri}/<path to the text file>/logback-spring.xml where <path to text file> should be formed according to the Serving Plain Text Documentation and the way how you configured your config-server.