|
| 1 | +package io.opentelemetry.instrumentation.spring.resources; |
| 2 | + |
| 3 | +import static java.util.logging.Level.FINE; |
| 4 | + |
| 5 | +import com.google.auto.service.AutoService; |
| 6 | +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; |
| 7 | +import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; |
| 8 | +import io.opentelemetry.sdk.resources.Resource; |
| 9 | +import io.opentelemetry.semconv.ResourceAttributes; |
| 10 | +import java.io.IOException; |
| 11 | +import java.io.InputStream; |
| 12 | +import java.util.Optional; |
| 13 | +import java.util.Properties; |
| 14 | +import java.util.logging.Logger; |
| 15 | +import io.opentelemetry.instrumentation.spring.resources.SpringBootServiceNameDetector.SystemHelper; |
| 16 | + |
| 17 | +@AutoService(ResourceProvider.class) |
| 18 | +public class SpringBootServiceVersionDetector implements ResourceProvider { |
| 19 | + |
| 20 | + private static final Logger logger = |
| 21 | + Logger.getLogger(SpringBootServiceVersionDetector.class.getName()); |
| 22 | + |
| 23 | + private final SystemHelper system; |
| 24 | + |
| 25 | + public SpringBootServiceVersionDetector() { |
| 26 | + this.system = new SystemHelper(); |
| 27 | + } |
| 28 | + |
| 29 | + // Exists for testing |
| 30 | + public SpringBootServiceVersionDetector(SystemHelper system){ |
| 31 | + this.system = system; |
| 32 | + } |
| 33 | + |
| 34 | + @Override |
| 35 | + public Resource createResource(ConfigProperties config) { |
| 36 | + return getServiceVersionFromBuildInfo() |
| 37 | + .map(version -> { |
| 38 | + logger.log(FINE, "Auto-detected Spring Boot service version: {0}", version); |
| 39 | + return Resource.builder().put(ResourceAttributes.SERVICE_VERSION, version).build(); |
| 40 | + }) |
| 41 | + .orElseGet(Resource::empty); |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | + private Optional<String> getServiceVersionFromBuildInfo(){ |
| 46 | + try(InputStream in = system.openClasspathResource("build-info.properties", "META-INF")){ |
| 47 | + return getServiceVersionPropertyFromStream(in); |
| 48 | + }catch (Exception e){ |
| 49 | + return Optional.empty(); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + private static Optional<String> getServiceVersionPropertyFromStream(InputStream in){ |
| 54 | + Properties properties = new Properties(); |
| 55 | + try { |
| 56 | + // Note: load() uses ISO 8859-1 encoding, same as spring uses by default for property files |
| 57 | + properties.load(in); |
| 58 | + return Optional.ofNullable(properties.getProperty("build.version")); |
| 59 | + } catch (IOException e) { |
| 60 | + return Optional.empty(); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments