mfvanek / spring-boot-open-telemetry-demo

Spring Boot Open Telemetry Demo
Apache License 2.0
4 stars 4 forks source link

Configure OtlpGrpcSpanExporter bean #147

Closed mfvanek closed 3 months ago

mfvanek commented 3 months ago

Example

import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter;
import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder;
import java.util.Locale;
import org.springframework.boot.actuate.autoconfigure.tracing.otlp.OtlpProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;

@AutoConfiguration(beforeName = "org.springframework.boot.actuate.autoconfigure.tracing.otlp.OtlpAutoConfiguration")
@ConditionalOnProperty(name = {"management.tracing.enabled"}, matchIfMissing = true, havingValue = "true")
public class OtlpGrpcSpanExporterAutoconfiguration {

    // Waiting for https://github.com/spring-projects/spring-boot/pull/41213
    @Bean
    @ConditionalOnMissingBean(OtlpGrpcSpanExporter.class)
    @ConditionalOnProperty(prefix = "management.otlp.tracing", name = "endpoint")
    public OtlpGrpcSpanExporter otlpGrpcSpanExporter(OtlpProperties otlpProperties) {
        OtlpGrpcSpanExporterBuilder builder = OtlpGrpcSpanExporter.builder()
            .setEndpoint(otlpProperties.getEndpoint())
            .setTimeout(otlpProperties.getTimeout())
            .setCompression(String.valueOf(otlpProperties.getCompression()).toLowerCase(Locale.ROOT));
        otlpProperties.getHeaders().forEach(builder::addHeader);
        return builder.build();
    }
}

and tests

    @Test
    void grpcExporterCanBeCustomized() {
        new WebApplicationContextRunner()
            .withUserConfiguration(OtlpAutoConfiguration.class)
            .withUserConfiguration(OtlpGrpcSpanExporterAutoconfiguration.class)
            .withPropertyValues("management.tracing.enabled=true")
            .withPropertyValues("management.otlp.tracing.endpoint=http://custom-collector:4317")
            .withPropertyValues("management.otlp.tracing.timeout=2341ms")
            .withPropertyValues("management.otlp.tracing.compression=gzip")
            .run(context -> assertThat(context)
                .hasBean("topOtlpGrpcSpanExporter")
                .getBean("topOtlpGrpcSpanExporter")
                .hasToString("OtlpGrpcSpanExporter{exporterName=otlp, type=span, endpoint=http://custom-collector:4317, " +
                    "endpointPath=/opentelemetry.proto.collector.trace.v1.TraceService/Export, timeoutNanos=2341000000, compressionEnabled=true, " +
                    "headers=Headers{User-Agent=OBFUSCATED}}"));
    }