com.codahale.metrics.SharedMetricRegistries Java Examples

The following examples show how to use com.codahale.metrics.SharedMetricRegistries. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavaxElMetricStrategy.java    From metrics-aspectj with Apache License 2.0 6 votes vote down vote up
@Override
public MetricRegistry resolveMetricRegistry(String registry) {
    Matcher matcher = EL_PATTERN.matcher(registry);
    if (matcher.matches()) {
        Object evaluation = processor.eval(matcher.group(1));
        if (evaluation instanceof String)
            return SharedMetricRegistries.getOrCreate((String) evaluation);
        else if (evaluation instanceof MetricRegistry)
            return (MetricRegistry) evaluation;
        else
            throw new IllegalStateException("Unable to resolve metrics registry from expression [" + registry + "]");
    } else if (!matcher.find()) {
        return SharedMetricRegistries.getOrCreate(registry);
    } else {
        return SharedMetricRegistries.getOrCreate(evaluateCompositeExpression(matcher));
    }
}
 
Example #2
Source File: MeteredMethodWithExceptionsTest.java    From metrics-aspectj with Apache License 2.0 6 votes vote down vote up
@Test
public void callExceptionMeteredMethodOnceWithThrowingInstanceOfExpectedException() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));

    final RuntimeException exception = new IllegalStateException("message");
    Runnable runnableThatThrowsIllegalStateException = new Runnable() {
        @Override
        public void run() {
            throw exception;
        }
    };

    // Call the metered method and assert it's been marked and that the original exception has been rethrown
    try {
        instance.exceptionMeteredMethod(runnableThatThrowsIllegalStateException);
    } catch (RuntimeException cause) {
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(0L)));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(1L)));
        assertSame("Exception thrown is incorrect", cause, exception);
        return;
    }

    fail("No exception has been re-thrown!");
}
 
Example #3
Source File: GaugeMethodWithVisibilityModifiersTest.java    From metrics-aspectj with Apache License 2.0 6 votes vote down vote up
@Test
public void callGaugesAfterSetterCalls() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Gauges are not registered correctly", registry.getGauges().keySet(), is(equalTo(absoluteMetricNames())));

    long value = Math.round(Math.random() * Long.MAX_VALUE);
    // Call the setter methods
    instance.setPublicGauge(value);
    instance.setPackagePrivateGauge(value);
    instance.setProtectedGauge(value);
    method("setPrivateGauge").withParameterTypes(long.class).in(instance).invoke(value);

    // And assert the gauges are up-to-date
    assertThat("Gauge values are incorrect", registry.getGauges().values(), everyItem(Matchers.<Gauge>hasProperty("value", equalTo(value))));
}
 
Example #4
Source File: MeteredStaticMethodWithExceptionsTest.java    From metrics-aspectj with Apache License 2.0 6 votes vote down vote up
@Test
public void callExceptionMeteredStaticMethodsOnceWithoutThrowing() {
    Runnable runnableThatDoesNoThrowExceptions = new Runnable() {
        @Override
        public void run() {
        }
    };

    // Call the metered methods and assert they haven't been marked
    MeteredStaticMethodWithExceptions.illegalArgumentExceptionMeteredStaticMethod(runnableThatDoesNoThrowExceptions);
    MeteredStaticMethodWithExceptions.exceptionMeteredStaticMethod(runnableThatDoesNoThrowExceptions);

    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
    assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(METER_COUNTS[0].get())));
    assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(METER_COUNTS[1].get())));
}
 
Example #5
Source File: MeteredStaticMethodWithExceptionsTest.java    From metrics-aspectj with Apache License 2.0 6 votes vote down vote up
@Test
public void callExceptionMeteredStaticMethodOnceWithThrowingExpectedException() {
    final RuntimeException exception = new IllegalArgumentException("message");
    Runnable runnableThatThrowsIllegalArgumentException = new Runnable() {
        @Override
        public void run() {
            throw exception;
        }
    };

    // Call the metered method and assert it's been marked and that the original exception has been rethrown
    try {
        MeteredStaticMethodWithExceptions.illegalArgumentExceptionMeteredStaticMethod(runnableThatThrowsIllegalArgumentException);
    } catch (RuntimeException cause) {
        assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
        MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
        assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(METER_COUNTS[0].incrementAndGet())));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(METER_COUNTS[1].get())));
        assertSame("Exception thrown is incorrect", cause, exception);
        return;
    }

    fail("No exception has been re-thrown!");
}
 
Example #6
Source File: MeteredMethodWithExceptionsTest.java    From metrics-aspectj with Apache License 2.0 6 votes vote down vote up
@Test
public void callExceptionMeteredMethodOnceWithThrowingNonExpectedException() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));

    final RuntimeException exception = new IllegalStateException("message");
    Runnable runnableThatThrowsIllegalStateException = new Runnable() {
        @Override
        public void run() {
            throw exception;
        }
    };

    // Call the metered method and assert it hasn't been marked and that the original exception has been rethrown
    try {
        instance.illegalArgumentExceptionMeteredMethod(runnableThatThrowsIllegalStateException);
    } catch (RuntimeException cause) {
        assertThat("Meter counts are incorrect", registry.getMeters().values(), everyItem(Matchers.<Meter>hasProperty("count", equalTo(0L))));
        assertSame("Exception thrown is incorrect", cause, exception);
        return;
    }

    fail("No exception has been re-thrown!");
}
 
Example #7
Source File: MeteredMethodWithExceptionsTest.java    From metrics-aspectj with Apache License 2.0 6 votes vote down vote up
@Test
public void callExceptionMeteredMethodOnceWithThrowingExpectedException() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));

    final RuntimeException exception = new IllegalArgumentException("message");
    Runnable runnableThatThrowsIllegalArgumentException = new Runnable() {
        @Override
        public void run() {
            throw exception;
        }
    };

    // Call the metered method and assert it's been marked and that the original exception has been rethrown
    try {
        instance.illegalArgumentExceptionMeteredMethod(runnableThatThrowsIllegalArgumentException);
    } catch (RuntimeException cause) {
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(1L)));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(0L)));
        assertSame("Exception thrown is incorrect", cause, exception);
        return;
    }

    fail("No exception has been re-thrown!");
}
 
Example #8
Source File: SolrMetricManager.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Remove a named registry.
 *
 * @param registry name of the registry to remove
 */
public void removeRegistry(String registry) {
  // close any reporters for this registry first
  closeReporters(registry, null);
  // make sure we use a name with prefix
  registry = enforcePrefix(registry);
  if (isSharedRegistry(registry)) {
    SharedMetricRegistries.remove(registry);
  } else {
    swapLock.lock();
    try {
      registries.remove(registry);
    } finally {
      swapLock.unlock();
    }
  }
}
 
Example #9
Source File: MeteredMethodWithExceptionsTest.java    From metrics-aspectj with Apache License 2.0 6 votes vote down vote up
@Test
public void callExceptionMeteredMethodsOnceWithoutThrowing() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));

    Runnable runnableThatDoesNoThrowExceptions = new Runnable() {
        @Override
        public void run() {
        }
    };

    // Call the metered methods and assert they haven't been marked
    instance.illegalArgumentExceptionMeteredMethod(runnableThatDoesNoThrowExceptions);
    instance.exceptionMeteredMethod(runnableThatDoesNoThrowExceptions);
    assertThat("Meter counts are incorrect", registry.getMeters().values(), everyItem(Matchers.<Meter>hasProperty("count", equalTo(0L))));
}
 
Example #10
Source File: DropwizardReporterTest.java    From kafka-dropwizard-reporter with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricChange() throws Exception {
    Metrics metrics = new Metrics();
    DropwizardReporter reporter = new DropwizardReporter();
    reporter.configure(new HashMap<String, Object>());
    metrics.addReporter(reporter);
    Sensor sensor = metrics.sensor("kafka.requests");
    sensor.add(new MetricName("pack.bean1.avg", "grp1"), new Avg());

    Map<String, Gauge> gauges = SharedMetricRegistries.getOrCreate("default").getGauges();
    String expectedName = "org.apache.kafka.common.metrics.grp1.pack.bean1.avg";
    Assert.assertEquals(1, gauges.size());
    Assert.assertEquals(expectedName, gauges.keySet().toArray()[0]);

    sensor.record(2.1);
    sensor.record(2.2);
    sensor.record(2.6);
    Assert.assertEquals(2.3, (Double)gauges.get(expectedName).getValue(), 0.001);
}
 
Example #11
Source File: DriverTest.java    From metrics-sql with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnectionLife() throws SQLException {
    // Act
    Connection connection = DriverManager.getConnection(URL + ";metrics_registry=life", H2DbUtil.USERNAME, H2DbUtil.PASSWORD);
    Statement statement = connection.createStatement();
    H2DbUtil.close(statement, connection);
    // Assert
    assertNotNull(connection);
    assertTrue(Proxy.isProxyClass(connection.getClass()));
    MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate("life");
    Timer lifeTimer = metricRegistry.timer("java.sql.Connection");
    assertNotNull(lifeTimer);
    assertThat(lifeTimer.getCount(), equalTo(1L));
    Timer getTimer = metricRegistry.timer("java.sql.Connection.get");
    assertNotNull(getTimer);
    assertThat(getTimer.getCount(), equalTo(1L));
}
 
Example #12
Source File: EventSchedulerService.java    From flux with Apache License 2.0 6 votes vote down vote up
@Inject
public EventSchedulerService(EventSchedulerDao eventSchedulerDao, EventSchedulerRegistry eventSchedulerRegistry,
                             @Named("eventScheduler.batchRead.intervalms") Integer batchReadInterval,
                             @Named("eventScheduler.batchRead.batchSize") Integer batchSize,
                             ObjectMapper objectMapper) {
    this.eventSchedulerDao = eventSchedulerDao;
    this.eventSchedulerRegistry = eventSchedulerRegistry;
    this.batchReadInterval = batchReadInterval;
    this.batchSize = batchSize;
    this.objectMapper = objectMapper;

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    // remove the task from scheduler on cancel
    executor.setRemoveOnCancelPolicy(true);
    scheduledExecutorService =
            new InstrumentedScheduledExecutorService(Executors.unconfigurableScheduledExecutorService(executor),
                    SharedMetricRegistries.getOrCreate(METRIC_REGISTRY_NAME), scheduledExectorSvcName);
}
 
Example #13
Source File: MultipleMetricsStaticMethodTest.java    From metrics-aspectj with Apache License 2.0 6 votes vote down vote up
@Test
public void callMetricsStaticMethodsOnce() {
    // Call the monitored method and assert all the metrics have been created and marked
    MultipleMetricsStaticMethod.metricsMethod();

    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);

    assertThat("Metrics are not registered correctly", registry.getMetrics().keySet(), is(equalTo(absoluteMetricNames())));

    // Make sure that the metrics have been called
    assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName("exception")).getCount(), is(equalTo(0L)));
    assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName("meter")).getCount(), is(equalTo(1L)));
    assertThat("Timer count is incorrect", registry.getTimers().get(absoluteMetricName("timer")).getCount(), is(equalTo(1L)));
    assertThat("Gauge value is incorrect", registry.getGauges().get(absoluteMetricName("gauge")).getValue(), hasToString((equalTo("value"))));
}
 
Example #14
Source File: Metrics4CapabilityTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void addMetricsCapability() {
  final MetricRegistry registry = SharedMetricRegistries.getOrCreate("unit_test");

  final SimpleSource source = Feign.builder()
      .client(new MockClient()
          .ok(HttpMethod.GET, "/get", "1234567890abcde"))
      .addCapability(new Metrics4Capability(registry))
      .target(new MockTarget<>(Metrics4CapabilityTest.SimpleSource.class));

  source.get("0x3456789");

  assertThat(registry.getMetrics(), aMapWithSize(6));

  registry.getMetrics().keySet().forEach(metricName -> assertThat(
      "Expect all metric names to include client name:" + metricName,
      metricName,
      containsString("feign.metrics4.Metrics4CapabilityTest$SimpleSource")));
  registry.getMetrics().keySet().forEach(metricName -> assertThat(
      "Expect all metric names to include method name:" + metricName,
      metricName,
      containsString("get")));
}
 
Example #15
Source File: CursorStore.java    From notification with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor
 *
 * @param client Riak client
 * @param timeout Riak server-side timeout
 * @param requestTimeout Riak client-side timeout
 */
public CursorStore(
    final RiakClient client, final Duration timeout, final Duration requestTimeout) {

  final MetricRegistry registry = SharedMetricRegistries.getOrCreate("default");
  this.fetchTimer = registry.timer(MetricRegistry.name(CursorStore.class, "fetch"));
  this.storeTimer = registry.timer(MetricRegistry.name(CursorStore.class, "store"));
  this.deleteTimer = registry.timer(MetricRegistry.name(CursorStore.class, "delete"));

  this.client = Objects.requireNonNull(client, "client == null");

  this.timeout =
      Optional.ofNullable(timeout)
          .map(t -> Math.toIntExact(t.toMilliseconds()))
          .orElse(DEFAULT_TIMEOUT_MS);
  this.requestTimeout = Objects.requireNonNull(requestTimeout, "requestTimeout == null");
}
 
Example #16
Source File: NotificationStore.java    From notification with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor
 *
 * @param client Riak client
 * @param idGenerator ID Generator
 * @param cursors Cursor data store
 * @param ruleStore Rule data store
 * @param timeout Riak server-side timeout
 * @param requestTimeout Riak client-side timeout
 */
public NotificationStore(
    final RiakClient client,
    final IdGenerator idGenerator,
    final CursorStore cursors,
    final RuleStore ruleStore,
    final Duration timeout,
    final Duration requestTimeout) {

  final MetricRegistry registry = SharedMetricRegistries.getOrCreate("default");
  this.fetchTimer = registry.timer(MetricRegistry.name(NotificationStore.class, "fetch"));
  this.updateTimer = registry.timer(MetricRegistry.name(NotificationStore.class, "store"));
  this.deleteTimer = registry.timer(MetricRegistry.name(NotificationStore.class, "delete"));

  this.client = Objects.requireNonNull(client, "client == null");
  this.idGenerator = Objects.requireNonNull(idGenerator, "idGenerator == null");
  this.cursors = Objects.requireNonNull(cursors, "cursors == null");
  this.ruleStore = Objects.requireNonNull(ruleStore, "ruleStore == null");

  this.timeout =
      Optional.ofNullable(timeout)
          .map(t -> Math.toIntExact(t.toMilliseconds()))
          .orElse(DEFAULT_TIMEOUT_MS);
  this.requestTimeout = Objects.requireNonNull(requestTimeout, "requestTimeout == null");
}
 
Example #17
Source File: MeteredStaticMethodWithExceptionsTest.java    From metrics-aspectj with Apache License 2.0 6 votes vote down vote up
@Test
public void callExceptionMeteredStaticMethodOnceWithThrowingNonExpectedException() {
    final RuntimeException exception = new IllegalStateException("message");
    Runnable runnableThatThrowsIllegalStateException = new Runnable() {
        @Override
        public void run() {
            throw exception;
        }
    };

    // Call the metered method and assert it hasn't been marked and that the original exception has been rethrown
    try {
        MeteredStaticMethodWithExceptions.illegalArgumentExceptionMeteredStaticMethod(runnableThatThrowsIllegalStateException);
    } catch (RuntimeException cause) {
        assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
        MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
        assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(METER_COUNTS[0].get())));
        assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(METER_COUNTS[1].get())));
        assertSame("Exception thrown is incorrect", cause, exception);
        return;
    }

    fail("No exception has been re-thrown!");
}
 
Example #18
Source File: TimedStaticMethodWithNameFromElExpressionTest.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@Test
public void callCompositeExpressionTimedStaticMethodOnce() {
    // Call the timed static method and assert it's been timed once
    TimedStaticMethodWithNameFromElExpression.compositeExpressionStaticTimedMethod();

    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);

    assertThat("Timer is not registered correctly", registry.getTimers(), hasKey(TIMER_NAME));
    Timer timer = registry.getTimers().get(TIMER_NAME);

    assertThat("Timer count is incorrect", timer.getCount(), is(equalTo(TIMER_COUNT.incrementAndGet())));
}
 
Example #19
Source File: InheritedTimedMethodWithVisibilityModifiersTest.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@Test
public void callTimedMethodsOnce() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Timers are not registered correctly", registry.getTimers().keySet(), is(equalTo(absoluteMetricNames())));

    // Call the timed methods and assert they've all been timed once
    instance.publicTimedMethod();
    instance.protectedTimedMethod();
    instance.packagePrivateTimedMethod();
    method("privateTimedMethod").in(instance).invoke();
    assertThat("Timer counts are incorrect", registry.getTimers().values(), everyItem(Matchers.<Timer>hasProperty("count", equalTo(1L))));
}
 
Example #20
Source File: TimedStaticMethodWithNameFromElExpressionTest.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@Test
public void callExpressionTimedStaticMethodOnce() {
    // Call the timed static method and assert it's been timed once
    TimedStaticMethodWithNameFromElExpression.expressionStaticTimedMethod();

    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);

    assertThat("Timer is not registered correctly", registry.getTimers(), hasKey(TIMER_NAME));
    Timer timer = registry.getTimers().get(TIMER_NAME);

    assertThat("Timer count is incorrect", timer.getCount(), is(equalTo(TIMER_COUNT.incrementAndGet())));
}
 
Example #21
Source File: InheritedTimedMethodWithVisibilityModifiersTest.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@Test
public void timedMethodsNotCalledYet() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Timers are not registered correctly", registry.getTimers().keySet(), is(equalTo(absoluteMetricNames())));

    // Make sure that all the timers haven't been called yet
    assertThat("Timer counts are incorrect", registry.getTimers().values(), everyItem(Matchers.<Timer>hasProperty("count", equalTo(0L))));
}
 
Example #22
Source File: MultipleMetricsMethodTest.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@Test
public void metricsMethodNotCalledYet() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Metrics are not registered correctly", registry.getMetrics().keySet(), is(equalTo(absoluteMetricNames())));

    // Make sure that the metrics haven't been called yet
    assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName("exception")).getCount(), is(equalTo(0L)));
    assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName("meter")).getCount(), is(equalTo(0L)));
    assertThat("Timer count is incorrect", registry.getTimers().get(absoluteMetricName("timer")).getCount(), is(equalTo(0L)));
}
 
Example #23
Source File: Driver.java    From metrics-sql with Apache License 2.0 5 votes vote down vote up
private MetricRegistry getMetricRegistry(DriverUrl driverUrl) {
    String registryName = driverUrl.getRegistryName();
    MetricRegistry registry;
    if (registryName == null) {
        registry = SharedMetricRegistries.tryGetDefault();
        if (registry == null) {
            registry = SharedMetricRegistries.getOrCreate("default");
        }
    } else {
        registry = SharedMetricRegistries.getOrCreate(registryName);
    }
    return registry;
}
 
Example #24
Source File: PropertyFilteringMessageBodyWriter.java    From jackson-jaxrs-propertyfiltering with Apache License 2.0 5 votes vote down vote up
protected MetricRegistry getMetricRegistry() {
  MetricRegistry registry = (MetricRegistry) servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY);

  if (registry == null) {
    registry = SharedMetricRegistries.getOrCreate("com.hubspot");
  }

  return registry;
}
 
Example #25
Source File: MeteredStaticMethodWithRegistryFromStringTest.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@Test
public void callMeteredStaticMethodOnce() {
    // Call the metered method and assert it's been marked
    MeteredStaticMethodWithRegistryFromString.singleMeteredStaticMethod();

    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Timer is not registered correctly", registry.getMeters(), hasKey(METER_NAME));
    Meter meter = registry.getMeters().get(METER_NAME);
    assertThat("Meter count is incorrect", meter.getCount(), is(equalTo(1L)));
}
 
Example #26
Source File: TimedStaticMethodWithVisibilityModifiersTest.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@Test
public void callTimedStaticMethodsOnce() {
    // Call the timed methods and assert they've all been timed once
    TimedStaticMethodWithVisibilityModifiers.publicTimedStaticMethod();
    TimedStaticMethodWithVisibilityModifiers.protectedTimedStaticMethod();
    TimedStaticMethodWithVisibilityModifiers.packagePrivateTimedStaticMethod();
    staticMethod("privateTimedStaticMethod").in(TimedStaticMethodWithVisibilityModifiers.class).invoke();

    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);

    assertThat("Timers are not registered correctly", registry.getTimers().keySet(), is(equalTo(absoluteMetricNames())));

    assertThat("Timer counts are incorrect", registry.getTimers().values(), everyItem(Matchers.<Timer>hasProperty("count", equalTo(1L))));
}
 
Example #27
Source File: TimedMethodWithRegistryFromSharedMetricRegistriesTest.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@Test
public void timedMethodNotCalledYet() {
    assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
    MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
    assertThat("Timer is not registered correctly", registry.getTimers(), hasKey(TIMER_NAME));
    Timer timer = registry.getTimers().get(TIMER_NAME);

    // Make sure that the timer hasn't been called yet
    assertThat("Timer count is incorrect", timer.getCount(), is(equalTo(0L)));
}
 
Example #28
Source File: MetricsExamples.java    From vertx-dropwizard-metrics with Apache License 2.0 5 votes vote down vote up
public void getRegistry() {
  VertxOptions options = new VertxOptions().setMetricsOptions(
      new DropwizardMetricsOptions().setEnabled(true).setRegistryName("my-registry")
  );
  Vertx vertx = Vertx.vertx(options);
  // Get the registry
  MetricRegistry registry = SharedMetricRegistries.getOrCreate("my-registry");
  // Do whatever you need with the registry
}
 
Example #29
Source File: RuleStore.java    From notification with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param client Riak client
 * @param cacheTimeout Rule cache refresh timeout
 * @param timeout Riak server-side timeout
 * @param requestTimeout Riak client-side timeout
 */
public RuleStore(
    final RiakClient client,
    final Duration cacheTimeout,
    final Duration timeout,
    final Duration requestTimeout) {

  final MetricRegistry registry = SharedMetricRegistries.getOrCreate("default");
  this.fetchTimer = registry.timer(MetricRegistry.name(RuleStore.class, "fetch"));
  this.storeTimer = registry.timer(MetricRegistry.name(RuleStore.class, "store"));
  this.deleteTimer = registry.timer(MetricRegistry.name(RuleStore.class, "delete"));
  this.cacheMisses = registry.meter(MetricRegistry.name(RuleStore.class, "cache-misses"));

  this.client = Objects.requireNonNull(client, "client == null");

  this.timeout =
      Optional.ofNullable(timeout)
          .map(t -> Math.toIntExact(t.toMilliseconds()))
          .orElse(DEFAULT_TIMEOUT_MS);
  this.requestTimeout = Objects.requireNonNull(requestTimeout, "requestTimeout == null");

  // set up a cache for the rules
  this.cache =
      CacheBuilder.newBuilder()
          .refreshAfterWrite(cacheTimeout.getQuantity(), cacheTimeout.getUnit())
          .build(
              new CacheLoader<String, Map<String, Rule>>() {
                @Override
                public Map<String, Rule> load(String key) throws NotificationStoreException {
                  cacheMisses.mark();

                  // all rules are stored under a common key, so we don't need to reference it
                  return fetch().orElse(Collections.emptyMap());
                }
              });
}
 
Example #30
Source File: DriverPropertiesTest.java    From metrics-sql with Apache License 2.0 5 votes vote down vote up
@Test
public void testProxyFactory() throws SQLException {
    // When
    Connection connection = DriverManager.getConnection(DriverTest.URL + ";metrics_registry=proxy;metrics_proxy_factory=cglib", H2DbUtil.USERNAME, H2DbUtil.PASSWORD);
    // Then
    assertNotNull(SharedMetricRegistries.getOrCreate("proxy").getTimers().get("java.sql.Connection"));
    assertThat(connection.getClass().getName().toLowerCase(), containsString("cglib"));
}