tags, double value) {
+ // Remember the latest value of this series. The observable gauge callback reports it on every
+ // collection, so a series is not lost while it stays idle.
+ Attributes attributes = getOrCreateAttributes(tags);
+ gaugeValues.put(new SeriesKey(name, attributes), value);
+
+ Meter meter = getMeter();
+ if (meter == null) {
+ logger.warn("OpenTelemetry meter not available yet, skipping gauge registration for '{}'",
+ name);
+ return;
+ }
+ // Register the observable gauge if not already registered. Its callback reports the cached
+ // values on every collection, so no further action is needed when the gauge already exists.
+ gaugeMap.computeIfAbsent(name, key -> {
+ ObservableDoubleGauge gauge =
+ meter.gaugeBuilder(key).setDescription("Apollo gauge metrics").setUnit(GAUGE_UNIT)
+ .buildWithCallback(measurement -> reportGaugeValues(measurement, key));
+ // A null gauge is not expected from the OpenTelemetry API, but be defensive so that a
+ // failure here does not break the metrics collection.
+ return gauge != null ? gauge : NOOP_OBSERVABLE_GAUGE;
+ });
+
+ if (logger.isDebugEnabled()) {
+ logger.debug("Updated OpenTelemetry gauge '{}' with value: {}, tags: {}", name, value, tags);
+ }
+ }
+
+ /**
+ * Reports every cached gauge value of the given metric to the SDK. Invoked on each collection by
+ * the SDK, which keeps idle series alive.
+ */
+ private void reportGaugeValues(ObservableDoubleMeasurement measurement, String metricName) {
+ gaugeValues.forEach((series, value) -> {
+ if (!series.name.equals(metricName)) {
+ return;
+ }
+ measurement.record(value, series.attributes);
+ });
+ }
+
+ @Override
+ public String response() {
+ // Return simple status information since we're only using API layer
+ int counterCount = counterMap != null ? counterMap.size() : 0;
+ int gaugeCount = gaugeMap != null ? gaugeMap.size() : 0;
+
+ String meterStatus = getMeter() != null ? METER_NAME : "not initialized";
+ return String.format(
+ "OpenTelemetry metrics exporter status - Counters: %d, Gauges: %d, Meter: %s", counterCount,
+ gaugeCount, meterStatus);
+ }
+
+ /**
+ * Resolves the meter from the currently registered global OpenTelemetry instance.
+ *
+ * {@link GlobalOpenTelemetry#getOrNoop()} is used on purpose: unlike {@link
+ * GlobalOpenTelemetry#get()} it does not claim the global slot, so an application that registers
+ * its OpenTelemetry SDK later is not affected by this exporter having been initialized first.
+ * The global is re-resolved on every call so that the exporter picks up the SDK once it is
+ * registered.
+ *
+ * @return the meter, or {@code null} when no OpenTelemetry SDK is registered yet
+ */
+ private Meter getMeter() {
+ OpenTelemetry openTelemetry = GlobalOpenTelemetry.getOrNoop();
+ if (openTelemetry == OpenTelemetry.noop()) {
+ return null;
+ }
+ MeterProvider meterProvider = openTelemetry.getMeterProvider();
+ if (meterProvider == null) {
+ return null;
+ }
+ return meterProvider.meterBuilder(METER_NAME).build();
+ }
+
+ private Attributes getOrCreateAttributes(Map tags) {
+ if (tags == null || tags.isEmpty()) {
+ return Attributes.empty();
+ }
+ AttributesBuilder builder = Attributes.builder();
+ tags.forEach(builder::put);
+ return builder.build();
+ }
+
+ /**
+ * Identifies a gauge series by its metric name and attribute set.
+ */
+ private static final class SeriesKey {
+
+ private final String name;
+ private final Attributes attributes;
+
+ private SeriesKey(String name, Attributes attributes) {
+ this.name = name;
+ this.attributes = attributes;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (!(o instanceof SeriesKey)) {
+ return false;
+ }
+ SeriesKey other = (SeriesKey) o;
+ return name.equals(other.name) && attributes.equals(other.attributes);
+ }
+
+ @Override
+ public int hashCode() {
+ return 31 * name.hashCode() + attributes.hashCode();
+ }
+ }
+}
diff --git a/apollo-plugin/apollo-plugin-client-opentelemetry/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter b/apollo-plugin/apollo-plugin-client-opentelemetry/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter
new file mode 100644
index 00000000..8e064550
--- /dev/null
+++ b/apollo-plugin/apollo-plugin-client-opentelemetry/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter
@@ -0,0 +1 @@
+com.ctrip.framework.apollo.monitor.internal.exporter.impl.OpenTelemetryApolloClientMetricsExporter
\ No newline at end of file
diff --git a/apollo-plugin/apollo-plugin-client-opentelemetry/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/OpenTelemetryApolloClientMetricsExporterIntegrationTest.java b/apollo-plugin/apollo-plugin-client-opentelemetry/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/OpenTelemetryApolloClientMetricsExporterIntegrationTest.java
new file mode 100644
index 00000000..0196715d
--- /dev/null
+++ b/apollo-plugin/apollo-plugin-client-opentelemetry/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/OpenTelemetryApolloClientMetricsExporterIntegrationTest.java
@@ -0,0 +1,239 @@
+/*
+ * Copyright 2022 Apollo Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package com.ctrip.framework.apollo.monitor.internal.exporter.impl;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import io.opentelemetry.api.GlobalOpenTelemetry;
+import io.opentelemetry.sdk.OpenTelemetrySdk;
+import io.opentelemetry.sdk.metrics.SdkMeterProvider;
+import io.opentelemetry.sdk.metrics.data.MetricData;
+import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader;
+import java.util.HashMap;
+import java.util.Map;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Integration tests using a real OpenTelemetry SDK to verify exported metric values.
+ */
+public class OpenTelemetryApolloClientMetricsExporterIntegrationTest {
+
+ private SdkMeterProvider meterProvider;
+ private InMemoryMetricReader reader;
+ private OpenTelemetryApolloClientMetricsExporter exporter;
+
+ @Before
+ public void setUp() {
+ reader = InMemoryMetricReader.create();
+ meterProvider = SdkMeterProvider.builder().registerMetricReader(reader).build();
+ OpenTelemetrySdk sdk = OpenTelemetrySdk.builder().setMeterProvider(meterProvider).build();
+ GlobalOpenTelemetry.set(sdk);
+
+ exporter = new OpenTelemetryApolloClientMetricsExporter();
+ exporter.doInit();
+ }
+
+ @After
+ public void tearDown() {
+ GlobalOpenTelemetry.resetForTest();
+ meterProvider.close();
+ }
+
+ private double latestGaugeValue(String metricName, String tagValue) {
+ for (MetricData md : reader.collectAllMetrics()) {
+ if (!metricName.equals(md.getName())) {
+ continue;
+ }
+ return md.getDoubleGaugeData().getPoints().stream()
+ .filter(p -> tagValue.equals(p.getAttributes()
+ .get(io.opentelemetry.api.common.AttributeKey.stringKey("thread_pool_name"))))
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("No gauge point found for metric '" + metricName
+ + "' with tag value '" + tagValue + "', all metrics: " + reader.collectAllMetrics()))
+ .getValue();
+ }
+ throw new AssertionError("Metric not found: " + metricName);
+ }
+
+ private double latestCounterValue(String metricName) {
+ for (MetricData md : reader.collectAllMetrics()) {
+ if (metricName.equals(md.getName())) {
+ return md.getDoubleSumData().getPoints().stream().findFirst()
+ .orElseThrow(() -> new AssertionError("No counter point for " + metricName)).getValue();
+ }
+ }
+ throw new AssertionError("Metric not found: " + metricName);
+ }
+
+ @Test
+ public void gaugeShouldReflectLatestValueAfterUpdates() {
+ Map tags = new HashMap<>();
+ tags.put("thread_pool_name", "ConfigService");
+
+ exporter.registerOrUpdateGaugeSample("apollo_client_thread_pool_queue_size", tags, 5.0);
+ // force collection so subsequent update is a new delta
+ reader.collectAllMetrics();
+ exporter.registerOrUpdateGaugeSample("apollo_client_thread_pool_queue_size", tags, 10.0);
+ reader.collectAllMetrics();
+ exporter.registerOrUpdateGaugeSample("apollo_client_thread_pool_queue_size", tags, 3.0);
+
+ assertEquals(3.0, latestGaugeValue("apollo_client_thread_pool_queue_size", "ConfigService"),
+ 0.0001);
+ }
+
+ @Test
+ public void gaugeWithDifferentTagsShouldRecordSeparateSeries() {
+ Map tags1 = new HashMap<>();
+ tags1.put("thread_pool_name", "ConfigService");
+ Map tags2 = new HashMap<>();
+ tags2.put("thread_pool_name", "RemoteConfigLongPollService");
+
+ exporter.registerOrUpdateGaugeSample("apollo_client_thread_pool_active_task_count", tags1, 1.0);
+ exporter.registerOrUpdateGaugeSample("apollo_client_thread_pool_active_task_count", tags2, 7.0);
+
+ assertEquals(1.0,
+ latestGaugeValue("apollo_client_thread_pool_active_task_count", "ConfigService"), 0.0001);
+ assertEquals(7.0, latestGaugeValue("apollo_client_thread_pool_active_task_count",
+ "RemoteConfigLongPollService"), 0.0001);
+ }
+
+ @Test
+ public void counterShouldAccumulateAcrossUpdates() {
+ Map tags = new HashMap<>();
+ tags.put("namespace", "application");
+
+ reader.collectAllMetrics();
+ exporter.registerOrUpdateCounterSample("apollo_client_exception_num", tags, 2.0);
+ reader.collectAllMetrics();
+ exporter.registerOrUpdateCounterSample("apollo_client_exception_num", tags, 3.0);
+
+ assertEquals(5.0, latestCounterValue("apollo_client_exception_num"), 0.0001);
+ }
+
+ /**
+ * Regression test: a gauge series must survive a collection cycle in which no new event happened.
+ *
+ * A synchronous gauge only produces a point when it is set, so with a delta-preferred metric
+ * reader the series disappears from the second collection onwards. Observable gauges are asked
+ * for their value on every collection, so the last known value keeps being reported.
+ */
+ @Test
+ public void gaugeShouldStillBeReportedWhenNoNewEventHappened() {
+ InMemoryMetricReader deltaReader = InMemoryMetricReader.createDelta();
+ SdkMeterProvider deltaProvider =
+ SdkMeterProvider.builder().registerMetricReader(deltaReader).build();
+ OpenTelemetrySdk deltaSdk = OpenTelemetrySdk.builder().setMeterProvider(deltaProvider).build();
+
+ GlobalOpenTelemetry.resetForTest();
+ GlobalOpenTelemetry.set(deltaSdk);
+ try {
+ OpenTelemetryApolloClientMetricsExporter deltaExporter =
+ new OpenTelemetryApolloClientMetricsExporter();
+ deltaExporter.doInit();
+
+ Map tags = new HashMap<>();
+ tags.put("namespace", "application");
+ deltaExporter.registerOrUpdateGaugeSample("apollo_client_namespace_item_num", tags, 12.0);
+
+ // First collection happens right after the event and must contain the gauge.
+ assertEquals("first collection should report the gauge", 1,
+ gaugePointCount(deltaReader, "apollo_client_namespace_item_num"));
+ // No further event happens: the idle collection must still report the last known value.
+ assertEquals("idle collection should still report the gauge", 1,
+ gaugePointCount(deltaReader, "apollo_client_namespace_item_num"));
+
+ assertEquals(12.0, gaugeValue(deltaReader, "apollo_client_namespace_item_num"), 0.0001);
+ } finally {
+ GlobalOpenTelemetry.resetForTest();
+ deltaProvider.close();
+ }
+ }
+
+ /**
+ * Regression test: initializing the exporter before the application registers its OpenTelemetry
+ * SDK must not prevent the SDK from being registered afterwards, and metrics must be exported
+ * once the SDK is available.
+ */
+ @Test
+ public void sdkCanBeRegisteredAfterExporterIsInitialized() {
+ GlobalOpenTelemetry.resetForTest();
+
+ // Apollo starts first: the exporter initializes while no SDK is registered.
+ OpenTelemetryApolloClientMetricsExporter earlyExporter =
+ new OpenTelemetryApolloClientMetricsExporter();
+ earlyExporter.doInit();
+
+ // The application registers its SDK afterwards. This must not fail.
+ SdkMeterProvider lateProvider = SdkMeterProvider.builder().build();
+ OpenTelemetrySdk.builder().setMeterProvider(lateProvider).buildAndRegisterGlobal();
+
+ Map tags = new HashMap<>();
+ tags.put("namespace", "application");
+ earlyExporter.registerOrUpdateCounterSample("apollo_client_exception_num", tags, 4.0);
+
+ assertTrue("exporter should report a meter once the SDK is registered",
+ earlyExporter.response().contains("Meter: apollo-client"));
+ }
+
+ @Test
+ public void exporterShouldNotClaimTheGlobalOpenTelemetrySlot() {
+ GlobalOpenTelemetry.resetForTest();
+
+ // Apollo starts first and the exporter resolves the global.
+ OpenTelemetryApolloClientMetricsExporter earlyExporter =
+ new OpenTelemetryApolloClientMetricsExporter();
+ earlyExporter.doInit();
+ earlyExporter.registerOrUpdateGaugeSample("apollo_client_namespace_item_num", new HashMap<>(),
+ 1.0);
+
+ // The global must still be unset so the application can register its SDK.
+ assertFalse("exporter must not claim the global OpenTelemetry slot",
+ GlobalOpenTelemetry.isSet());
+ }
+
+ private int gaugePointCount(InMemoryMetricReader metricReader, String metricName) {
+ int count = 0;
+ for (MetricData md : metricReader.collectAllMetrics()) {
+ if (metricName.equals(md.getName())) {
+ count += md.getDoubleGaugeData().getPoints().size();
+ }
+ }
+ return count;
+ }
+
+ private double gaugeValue(InMemoryMetricReader metricReader, String metricName) {
+ for (MetricData md : metricReader.collectAllMetrics()) {
+ if (metricName.equals(md.getName())) {
+ return md.getDoubleGaugeData().getPoints().stream().findFirst()
+ .orElseThrow(() -> new AssertionError("No gauge point for " + metricName)).getValue();
+ }
+ }
+ throw new AssertionError("Metric not found: " + metricName);
+ }
+
+ @Test
+ public void exporterShouldReportStatus() {
+ String response = exporter.response();
+ assertNotNull(response);
+ assertTrue(response.contains("OpenTelemetry metrics exporter status"));
+ }
+}
diff --git a/apollo-plugin/apollo-plugin-client-opentelemetry/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/OpenTelemetryApolloClientMetricsExporterTest.java b/apollo-plugin/apollo-plugin-client-opentelemetry/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/OpenTelemetryApolloClientMetricsExporterTest.java
new file mode 100644
index 00000000..bc11c6c9
--- /dev/null
+++ b/apollo-plugin/apollo-plugin-client-opentelemetry/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/OpenTelemetryApolloClientMetricsExporterTest.java
@@ -0,0 +1,234 @@
+/*
+ * Copyright 2022 Apollo Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package com.ctrip.framework.apollo.monitor.internal.exporter.impl;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import io.opentelemetry.api.GlobalOpenTelemetry;
+import io.opentelemetry.api.OpenTelemetry;
+import io.opentelemetry.api.metrics.Meter;
+import io.opentelemetry.api.metrics.MeterProvider;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.MockedStatic;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class OpenTelemetryApolloClientMetricsExporterTest {
+
+ private OpenTelemetryApolloClientMetricsExporter exporter;
+ private MockedStatic globalOpenTelemetryMock;
+ private OpenTelemetry openTelemetry;
+ private MeterProvider meterProvider;
+ private io.opentelemetry.api.metrics.MeterBuilder meterBuilder;
+ private Meter meter;
+
+ @Before
+ public void setUp() {
+ // Mock GlobalOpenTelemetry
+ globalOpenTelemetryMock = mockStatic(GlobalOpenTelemetry.class);
+ openTelemetry = mock(OpenTelemetry.class);
+ meterProvider = mock(MeterProvider.class);
+ meterBuilder = mock(io.opentelemetry.api.metrics.MeterBuilder.class);
+ meter = mock(Meter.class);
+
+ when(GlobalOpenTelemetry.getOrNoop()).thenReturn(openTelemetry);
+ when(openTelemetry.getMeterProvider()).thenReturn(meterProvider);
+ when(meterProvider.meterBuilder("apollo-client")).thenReturn(meterBuilder);
+ when(meterBuilder.build()).thenReturn(meter);
+
+ exporter = new OpenTelemetryApolloClientMetricsExporter();
+ exporter.doInit();
+ }
+
+ @After
+ public void tearDown() {
+ if (globalOpenTelemetryMock != null) {
+ globalOpenTelemetryMock.close();
+ }
+ }
+
+ @Test
+ public void testIsSupport() {
+ assertTrue(exporter.isSupport("opentelemetry"));
+ assertFalse(exporter.isSupport("prometheus"));
+ assertFalse(exporter.isSupport("other"));
+ }
+
+ @Test
+ public void testDoInitDoesNotClaimGlobalSlot() {
+ // The exporter must never call GlobalOpenTelemetry.get(), which claims the global slot and
+ // registers a no-op global as a side effect.
+ verify(meterProvider, org.mockito.Mockito.never()).meterBuilder(anyString());
+ }
+
+ @Test
+ public void testRegisterOrUpdateCounterSample() {
+ String name = "test_counter";
+ Map tags = new HashMap<>();
+ tags.put("namespace", "application");
+ tags.put("cluster", "default");
+
+ // Mock counter builder
+ io.opentelemetry.api.metrics.LongCounterBuilder counterBuilder =
+ mock(io.opentelemetry.api.metrics.LongCounterBuilder.class);
+ io.opentelemetry.api.metrics.DoubleCounterBuilder doubleCounterBuilder =
+ mock(io.opentelemetry.api.metrics.DoubleCounterBuilder.class);
+ io.opentelemetry.api.metrics.DoubleCounter counter =
+ mock(io.opentelemetry.api.metrics.DoubleCounter.class);
+
+ when(meter.counterBuilder(name)).thenReturn(counterBuilder);
+ when(counterBuilder.setDescription("Apollo counter metrics")).thenReturn(counterBuilder);
+ when(counterBuilder.setUnit("1")).thenReturn(counterBuilder);
+ when(counterBuilder.ofDoubles()).thenReturn(doubleCounterBuilder);
+ when(doubleCounterBuilder.build()).thenReturn(counter);
+
+ // This will create the counter on first call
+ exporter.registerOrUpdateCounterSample(name, tags, 1.0);
+
+ // Verify counter was created and value recorded
+ verify(meter).counterBuilder(name);
+ verify(counter).add(eq(1.0), any());
+ }
+
+ @Test
+ public void testRegisterOrUpdateGaugeSample() {
+ String name = "test_gauge";
+ Map tags = new HashMap<>();
+ tags.put("namespace", "application");
+ tags.put("cluster", "default");
+
+ // Mock observable gauge builder. The returned ObservableDoubleGauge cannot be mocked, but the
+ // exporter only stores it, so a null return value is enough for this unit test.
+ io.opentelemetry.api.metrics.DoubleGaugeBuilder gaugeBuilder =
+ mock(io.opentelemetry.api.metrics.DoubleGaugeBuilder.class);
+
+ when(meter.gaugeBuilder(name)).thenReturn(gaugeBuilder);
+ when(gaugeBuilder.setDescription("Apollo gauge metrics")).thenReturn(gaugeBuilder);
+ when(gaugeBuilder.setUnit("1")).thenReturn(gaugeBuilder);
+ when(gaugeBuilder.buildWithCallback(any())).thenReturn(null);
+
+ // This will create the observable gauge on first call
+ exporter.registerOrUpdateGaugeSample(name, tags, 3.14);
+
+ // Verify the observable gauge was created
+ verify(meter).gaugeBuilder(name);
+ verify(gaugeBuilder).buildWithCallback(any());
+ }
+
+ @Test
+ public void testResponse() {
+ String response = exporter.response();
+ assertTrue(response.contains("OpenTelemetry metrics exporter status"));
+ assertTrue(response.contains("Counters: 0"));
+ assertTrue(response.contains("Gauges: 0"));
+ assertTrue(response.contains("Meter: apollo-client"));
+ }
+
+ @Test
+ public void testResponseWithMetrics() {
+ // Register some metrics first
+ Map tags = new HashMap<>();
+ tags.put("test", "value");
+
+ // Mock counter creation
+ io.opentelemetry.api.metrics.LongCounterBuilder counterBuilder =
+ mock(io.opentelemetry.api.metrics.LongCounterBuilder.class);
+ io.opentelemetry.api.metrics.DoubleCounterBuilder doubleCounterBuilder =
+ mock(io.opentelemetry.api.metrics.DoubleCounterBuilder.class);
+ io.opentelemetry.api.metrics.DoubleCounter counter =
+ mock(io.opentelemetry.api.metrics.DoubleCounter.class);
+ when(meter.counterBuilder("test_counter")).thenReturn(counterBuilder);
+ when(counterBuilder.setDescription(anyString())).thenReturn(counterBuilder);
+ when(counterBuilder.setUnit(anyString())).thenReturn(counterBuilder);
+ when(counterBuilder.ofDoubles()).thenReturn(doubleCounterBuilder);
+ when(doubleCounterBuilder.build()).thenReturn(counter);
+
+ // Mock observable gauge creation
+ io.opentelemetry.api.metrics.DoubleGaugeBuilder gaugeBuilder =
+ mock(io.opentelemetry.api.metrics.DoubleGaugeBuilder.class);
+ when(meter.gaugeBuilder("test_gauge")).thenReturn(gaugeBuilder);
+ when(gaugeBuilder.setDescription(anyString())).thenReturn(gaugeBuilder);
+ when(gaugeBuilder.setUnit(anyString())).thenReturn(gaugeBuilder);
+ when(gaugeBuilder.buildWithCallback(any())).thenReturn(null);
+
+ exporter.registerOrUpdateCounterSample("test_counter", tags, 1.0);
+ exporter.registerOrUpdateGaugeSample("test_gauge", tags, 2.0);
+
+ String response = exporter.response();
+ assertTrue(response.contains("Counters: 1"));
+ assertTrue(response.contains("Gauges: 1"));
+ }
+
+ @Test
+ public void testGaugeSampleIsSkippedWhenNoSdkRegistered() {
+ // No OpenTelemetry SDK registered: the exporter must not fail, it just skips the export.
+ globalOpenTelemetryMock.when(GlobalOpenTelemetry::getOrNoop).thenReturn(OpenTelemetry.noop());
+
+ Map tags = new HashMap<>();
+ tags.put("namespace", "application");
+ exporter.registerOrUpdateGaugeSample("test_gauge", tags, 1.0);
+ exporter.registerOrUpdateCounterSample("test_counter", tags, 1.0);
+
+ // The status must report that no meter is available.
+ assertTrue(exporter.response().contains("Meter: not initialized"));
+ }
+
+ @Test
+ public void testNullAndEmptyTagsAfterInitialization() {
+ // The exporter is initialized in setUp(), so these calls go through the real code path with
+ // null and empty attribute maps.
+ io.opentelemetry.api.metrics.DoubleGaugeBuilder gaugeBuilder =
+ mock(io.opentelemetry.api.metrics.DoubleGaugeBuilder.class);
+ when(meter.gaugeBuilder("test_gauge")).thenReturn(gaugeBuilder);
+ when(gaugeBuilder.setDescription(anyString())).thenReturn(gaugeBuilder);
+ when(gaugeBuilder.setUnit(anyString())).thenReturn(gaugeBuilder);
+ when(gaugeBuilder.buildWithCallback(any())).thenReturn(null);
+
+ io.opentelemetry.api.metrics.LongCounterBuilder counterBuilder =
+ mock(io.opentelemetry.api.metrics.LongCounterBuilder.class);
+ io.opentelemetry.api.metrics.DoubleCounterBuilder doubleCounterBuilder =
+ mock(io.opentelemetry.api.metrics.DoubleCounterBuilder.class);
+ io.opentelemetry.api.metrics.DoubleCounter counter =
+ mock(io.opentelemetry.api.metrics.DoubleCounter.class);
+ when(meter.counterBuilder("test_counter")).thenReturn(counterBuilder);
+ when(counterBuilder.setDescription(anyString())).thenReturn(counterBuilder);
+ when(counterBuilder.setUnit(anyString())).thenReturn(counterBuilder);
+ when(counterBuilder.ofDoubles()).thenReturn(doubleCounterBuilder);
+ when(doubleCounterBuilder.build()).thenReturn(counter);
+
+ exporter.registerOrUpdateCounterSample("test_counter", null, 1.0);
+ exporter.registerOrUpdateCounterSample("test_counter", new HashMap<>(), 1.0);
+ exporter.registerOrUpdateGaugeSample("test_gauge", null, 1.0);
+ exporter.registerOrUpdateGaugeSample("test_gauge", new HashMap<>(), 1.0);
+
+ verify(meter).counterBuilder("test_counter");
+ verify(meter).gaugeBuilder("test_gauge");
+ // The counter must have been recorded for both the null and the empty tag map.
+ verify(counter, org.mockito.Mockito.times(2)).add(eq(1.0), any());
+ }
+}
diff --git a/apollo-plugin/apollo-plugin-client-opentelemetry/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/SimpleOpenTelemetryApolloClientMetricsExporterTest.java b/apollo-plugin/apollo-plugin-client-opentelemetry/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/SimpleOpenTelemetryApolloClientMetricsExporterTest.java
new file mode 100644
index 00000000..d2b3d0e6
--- /dev/null
+++ b/apollo-plugin/apollo-plugin-client-opentelemetry/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/SimpleOpenTelemetryApolloClientMetricsExporterTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright 2022 Apollo Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package com.ctrip.framework.apollo.monitor.internal.exporter.impl;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class SimpleOpenTelemetryApolloClientMetricsExporterTest {
+
+ private OpenTelemetryApolloClientMetricsExporter exporter;
+
+ @Before
+ public void setUp() {
+ exporter = new OpenTelemetryApolloClientMetricsExporter();
+ // Note: We don't call doInit() because it requires GlobalOpenTelemetry
+ // In a real test environment, you would need to setup OpenTelemetry first
+ }
+
+ @Test
+ public void testIsSupport() {
+ assertTrue(exporter.isSupport("opentelemetry"));
+ assertFalse(exporter.isSupport("prometheus"));
+ assertFalse(exporter.isSupport("other"));
+ assertFalse(exporter.isSupport(null));
+ }
+
+ @Test
+ public void testResponseWithoutInit() {
+ // Even without init, response should return a status message
+ String response = exporter.response();
+ assertNotNull(response);
+ assertTrue(response.contains("OpenTelemetry metrics exporter status"));
+ }
+
+ @Test
+ public void testRegisterOrUpdateCounterSampleWithoutInit() {
+ // This should not throw exception even without init
+ String name = "test_counter";
+ Map tags = new HashMap<>();
+ tags.put("namespace", "application");
+
+ exporter.registerOrUpdateCounterSample(name, tags, 1.0);
+ }
+
+ @Test
+ public void testRegisterOrUpdateGaugeSampleWithoutInit() {
+ // This should not throw exception even without init
+ String name = "test_gauge";
+ Map tags = new HashMap<>();
+ tags.put("namespace", "application");
+
+ exporter.registerOrUpdateGaugeSample(name, tags, 3.14);
+ }
+
+ @Test
+ public void testEmptyTags() {
+ String name = "test_metric";
+ Map emptyTags = new HashMap<>();
+
+ exporter.registerOrUpdateCounterSample(name, emptyTags, 1.0);
+ exporter.registerOrUpdateGaugeSample(name, emptyTags, 2.0);
+ }
+
+ @Test
+ public void testNullTags() {
+ String name = "test_metric";
+
+ exporter.registerOrUpdateCounterSample(name, null, 1.0);
+ exporter.registerOrUpdateGaugeSample(name, null, 2.0);
+ }
+
+ @Test
+ public void testNullAndEmptyTagsAfterInitialization() {
+ // Exercise null and empty tags on an initialized exporter. doInit() does not need an
+ // OpenTelemetry SDK, it only prepares the internal maps, so the exporter can be initialized
+ // here as well.
+ exporter.doInit();
+
+ exporter.registerOrUpdateCounterSample("test_counter", null, 1.0);
+ exporter.registerOrUpdateCounterSample("test_counter", new HashMap<>(), 1.0);
+ exporter.registerOrUpdateGaugeSample("test_gauge", null, 1.0);
+ exporter.registerOrUpdateGaugeSample("test_gauge", new HashMap<>(), 1.0);
+
+ String response = exporter.response();
+ assertTrue(response.contains("OpenTelemetry metrics exporter status"));
+ }
+}
diff --git a/apollo-plugin/pom.xml b/apollo-plugin/pom.xml
index f0d1b00f..b97e09f4 100644
--- a/apollo-plugin/pom.xml
+++ b/apollo-plugin/pom.xml
@@ -32,6 +32,7 @@
apollo-plugin-log4j2
apollo-plugin-client-prometheus
+ apollo-plugin-client-opentelemetry