Add otel-agent-vs-micrometer module: OpenTelemetry Java agent 2.34.0 vs Micrometer Tracing on Spring Boot 4.2.0, same app instrumented both ways, with real transcripts

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7h4ZNF4BDUpJk3Zou
This commit is contained in:
Claude
2026-11-29 02:59:07 +05:30
parent cbcfb05e35
commit 658bc52e2b
31 changed files with 1435 additions and 0 deletions
+81
View File
@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.ankurm</groupId>
<artifactId>otel-agent-vs-micrometer</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>orders-app</artifactId>
<properties>
<!-- "plain" = no tracing dependency at all (used with the agent, or as the baseline).
-Pmicrometer switches the variant name and adds the Boot 4 OpenTelemetry starter. -->
<variant>plain</variant>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-restclient</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>micrometer</id>
<properties>
<variant>micrometer</variant>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-opentelemetry</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<!-- use together with -Pmicrometer: adds the third-party JDBC observation library -->
<id>jdbc</id>
<properties>
<variant>micrometer-jdbc</variant>
</properties>
<dependencies>
<dependency>
<groupId>net.ttddyy.observation</groupId>
<artifactId>datasource-micrometer-spring-boot</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
</profile>
</profiles>
<build>
<finalName>orders-${variant}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,55 @@
package com.ankurm.otelcmp;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.support.ContextPropagatingTaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
/**
* Hands work to another thread, which is where tracing context goes missing.
* audit.executor=raw a plain java.util.concurrent pool
* audit.executor=spring a ThreadPoolTaskExecutor with Spring's ContextPropagatingTaskDecorator
*/
@Service
public class AuditService {
private final OrderRepository orders;
private final ObservationRegistry registry;
private final Executor executor;
public AuditService(OrderRepository orders, ObservationRegistry registry,
@Value("${audit.executor:raw}") String mode) {
this.orders = orders;
this.registry = registry;
if (mode.equals("spring")) {
ThreadPoolTaskExecutor t = new ThreadPoolTaskExecutor();
t.setCorePoolSize(2);
t.setThreadNamePrefix("audit-");
t.setTaskDecorator(new ContextPropagatingTaskDecorator());
t.initialize();
this.executor = t;
} else {
ExecutorService e = Executors.newFixedThreadPool(2, r -> {
Thread th = new Thread(r, "audit-raw");
th.setDaemon(true);
return th;
});
this.executor = e;
}
}
public void auditAndWait(long orderId) throws Exception {
java.util.concurrent.CompletableFuture.runAsync(() -> write(orderId), executor).get(10, TimeUnit.SECONDS);
}
// Public so the agent's methods.include setting can name it, and so a CGLIB-free direct call works.
public void write(long orderId) {
Observation.createNotStarted("audit.write", registry).observe(() -> orders.audit(orderId, "viewed"));
}
}
@@ -0,0 +1,22 @@
package com.ankurm.otelcmp;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
/** Calls this same application's /inventory endpoint, so one request produces a client span and a second server span. */
@Component
public class InventoryClient {
private final RestClient client;
// The auto-configured RestClient.Builder is the one Spring Boot attaches observation (and so
// trace propagation headers) to. RestClient.create() would not be instrumented.
public InventoryClient(RestClient.Builder builder, @Value("${server.port:8080}") int port) {
this.client = builder.baseUrl("http://localhost:" + port).build();
}
public int stock(String sku) {
return client.get().uri("/inventory/{sku}", sku).retrieve().body(Integer.class);
}
}
@@ -0,0 +1,29 @@
package com.ankurm.otelcmp;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Repository;
@Repository
public class OrderRepository {
public record Order(long id, String sku, int quantity, long unitPriceCents) {}
private final JdbcClient jdbc;
public OrderRepository(JdbcClient jdbc) {
this.jdbc = jdbc;
}
public Order find(long id) {
return jdbc.sql("select id, sku, quantity, unit_price_cents from orders where id = :id")
.param("id", id)
.query((rs, n) -> new Order(rs.getLong("id"), rs.getString("sku"),
rs.getInt("quantity"), rs.getLong("unit_price_cents")))
.single();
}
public void audit(long id, String note) {
jdbc.sql("insert into audit_log(order_id, note) values (:id, :note)")
.param("id", id).param("note", note).update();
}
}
@@ -0,0 +1,17 @@
package com.ankurm.otelcmp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* One application, built twice. The "plain" build has no tracing dependency at all; the
* "micrometer" build adds spring-boot-starter-opentelemetry. Nothing in this source tree knows
* which one it is running as, apart from {@link PricingService} and {@link AuditService}, which
* use the Micrometer Observation API (a no-op without a handler registered).
*/
@SpringBootApplication
public class OrdersApplication {
public static void main(String[] args) {
SpringApplication.run(OrdersApplication.class, args);
}
}
@@ -0,0 +1,51 @@
package com.ankurm.otelcmp;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrdersController {
private final OrderRepository orders;
private final InventoryClient inventory;
private final PricingService pricing;
private final AuditService audit;
public OrdersController(OrderRepository orders, InventoryClient inventory,
PricingService pricing, AuditService audit) {
this.orders = orders;
this.inventory = inventory;
this.pricing = pricing;
this.audit = audit;
}
/** One SQL query, one outgoing HTTP call, one business computation. */
@GetMapping("/orders/{id}")
public Map<String, Object> order(@PathVariable long id) {
var order = orders.find(id);
int stock = inventory.stock(order.sku());
return Map.of("id", order.id(), "sku", order.sku(), "totalCents", pricing.price(order), "stock", stock);
}
/** Same, plus a hand-off to another thread that also writes to the database. */
@GetMapping("/orders/{id}/audited")
public Map<String, Object> audited(@PathVariable long id) throws Exception {
var body = order(id);
audit.auditAndWait(id);
return body;
}
/** The downstream service (served by this same JVM). */
@GetMapping("/inventory/{sku}")
public int stock(@PathVariable String sku) {
return sku.length() * 10;
}
/** No database, no outgoing call: used to measure instrumentation cost per request. */
@GetMapping("/ping")
public String ping() {
return "pong";
}
}
@@ -0,0 +1,29 @@
package com.ankurm.otelcmp;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
import org.springframework.stereotype.Service;
/**
* A business operation we want a span for.
*
* In-code: the Observation below becomes a span when Micrometer Tracing is on the classpath.
* Zero-code: the agent is told about this method with
* -Dotel.instrumentation.methods.include=com.ankurm.otelcmp.PricingService[price]
* and this class needs no change. Under the agent the Observation is a harmless no-op.
*/
@Service
public class PricingService {
private final ObservationRegistry registry;
public PricingService(ObservationRegistry registry) {
this.registry = registry;
}
public long price(OrderRepository.Order order) {
return Observation.createNotStarted("pricing.compute", registry)
.lowCardinalityKeyValue("pricing.sku", order.sku())
.observe(() -> order.quantity() * order.unitPriceCents());
}
}
@@ -0,0 +1,7 @@
spring.application.name=orders
server.port=${PORT:8080}
spring.sql.init.mode=always
spring.sql.init.schema-locations=classpath:schema.sql
spring.sql.init.data-locations=classpath:data.sql
spring.datasource.url=jdbc:h2:mem:orders;DB_CLOSE_DELAY=-1
management.endpoints.web.exposure.include=health,metrics,info
@@ -0,0 +1 @@
merge into orders (id, sku, quantity, unit_price_cents) key (id) values (1, 'KEYBOARD', 2, 4999);
@@ -0,0 +1,2 @@
create table if not exists orders (id bigint primary key, sku varchar(20), quantity int, unit_price_cents bigint);
create table if not exists audit_log (id bigint auto_increment primary key, order_id bigint, note varchar(50));