Always include Collection tag in MongoDB observations.

Use default "none" collection name when command doesn't define a collection.

Signed-off-by: michaldo <michaldo@github.io>
Closes: #4994
This commit is contained in:
michaldo
2025-06-04 23:32:49 +02:00
committed by Mark Paluch
parent 2a82550952
commit bcbdc71edb
2 changed files with 18 additions and 0 deletions

View File

@@ -15,6 +15,7 @@
*/
package org.springframework.data.mongodb.observability;
import io.micrometer.common.KeyValue;
import io.micrometer.common.KeyValues;
import org.springframework.data.mongodb.observability.MongoObservation.LowCardinalityCommandKeyNames;
@@ -63,6 +64,8 @@ class DefaultMongoHandlerObservationConvention implements MongoHandlerObservatio
if (!ObjectUtils.isEmpty(context.getCollectionName())) {
keyValues = keyValues
.and(LowCardinalityCommandKeyNames.MONGODB_COLLECTION.withValue(context.getCollectionName()));
} else {
keyValues = keyValues.and(LowCardinalityCommandKeyNames.MONGODB_COLLECTION.withValue(KeyValue.NONE_VALUE));
}
if(context.getCommandStartedEvent() == null) {

View File

@@ -20,6 +20,7 @@ import static org.mockito.Mockito.*;
import io.micrometer.common.KeyValues;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.observation.DefaultMeterObservationHandler;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.micrometer.observation.Observation;
@@ -98,6 +99,20 @@ class MongoObservationCommandListenerTests {
assertThat(meterRegistry).hasMeterWithName("spring.data.mongodb.command.active");
}
@Test
void commandStartedShouldIncludeCollectionIfMissing() {
// when
listener.commandStarted(new CommandStartedEvent(new MapRequestContext(), 0, 0, null, "some name", "hello", null));
// then
// although command 'hello' is collection-less, metric must have tag "db.mongodb.collection"
assertThat(meterRegistry).hasMeterWithNameAndTags(
"spring.data.mongodb.command.active",
Tags.of("db.mongodb.collection", "none"));
}
@Test
void successfullyCompletedCommandShouldCreateTimerWhenParentSampleInRequestContext() {