MetricsInstrumentationInterceptor implements MongoInterceptor { @VisibleForTesting void addMetrics(long startTime, HttpServerExchange exchange) { if (configuration.gatheringAboveOrEqualToLevel(ROOT)) { var request = MongoRequest.of(exchange); long endTime = System.currentTimeMillis(); long duration = endTime - startTime; addDefaultMetrics(metrics.registry(), duration, exchange); if (isFilledAndNotMetrics(request.getDBName()) && configuration.gatheringAboveOrEqualToLevel(DATABASE)) { final MetricRegistry dbRegistry = metrics.registry(request.getDBName()); addDefaultMetrics(dbRegistry, duration, exchange); if (isFilledAndNotMetrics(request.getCollectionName()) && configuration.gatheringAboveOrEqualToLevel(COLLECTION)) { final MetricRegistry collectionRegistry = metrics.registry(request.getDBName(), request.getCollectionName()); addDefaultMetrics(collectionRegistry, duration, exchange); } } } }  @Override void handle(MongoRequest request, MongoResponse response); @Override boolean resolve(MongoRequest request, MongoResponse response);  }
@Test @SuppressWarnings("deprecation") public void testAddMetrics() throws Exception { MongoServiceConfiguration config = mock(MongoServiceConfiguration.class); when(config.gatheringAboveOrEqualToLevel(MongoServiceConfiguration.METRICS_GATHERING_LEVEL.ROOT)).thenReturn(true); when(config.gatheringAboveOrEqualToLevel(MongoServiceConfiguration.METRICS_GATHERING_LEVEL.DATABASE)).thenReturn(true); when(config.gatheringAboveOrEqualToLevel(MongoServiceConfiguration.METRICS_GATHERING_LEVEL.COLLECTION)).thenReturn(true); MetricRegistry registry = new MetricRegistry(); MetricRegistry registryDb = new MetricRegistry(); MetricRegistry registryColl = new MetricRegistry(); SharedMetricRegistryProxy proxy = new SharedMetricRegistryProxy() { @Override public MetricRegistry registry() { return registry; } @Override public MetricRegistry registry(String dbName) { return registryDb; } @Override public MetricRegistry registry(String dbName, String collectionName) { return registryColl; } }; MetricsInstrumentationInterceptor mih = new MetricsInstrumentationInterceptor(); mih.configuration = config; mih.metrics = proxy; HttpServerExchange httpServerExchange = mock(HttpServerExchange.class); when(httpServerExchange.getStatusCode()).thenReturn(200); when(httpServerExchange.getRequestMethod()).thenReturn(Methods.GET); when(httpServerExchange.getRequestPath()).thenReturn("/foo/bar"); var request = MongoRequest.init(httpServerExchange, "foo", "bar"); when(httpServerExchange.getAttachment(anyObject())).thenReturn(request); mih.addMetrics(0, httpServerExchange); mih.addMetrics(0, httpServerExchange); assertEquals(3, registry.getTimers().size()); assertEquals(3, registryDb.getTimers().size()); assertEquals(3, registryColl.getTimers().size()); }