com.signalfx.codahale.reporter.MetricMetadata Java Examples

The following examples show how to use com.signalfx.codahale.reporter.MetricMetadata. 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: SignalFxEndpointMetricsHandler.java    From riposte with Apache License 2.0 6 votes vote down vote up
/**
 * The kitchen-sink constructor - creates a new instance for the given {@link MetricMetadata}, {@link
 * MetricRegistry}, {@link MetricBuilder}, and {@link MetricDimensionConfigurator}. This constructor allows maximum
 * flexibility in controlling how the endpoint timers behave and operate.
 *
 * @param signalFxReporterMetricMetadata The {@link SignalFxReporter#getMetricMetadata()} to use for metric
 * metadata. Cannot be null.
 * @param metricRegistry The {@link MetricRegistry} being used for the application that the endpoint timers should
 * be registered under. Cannot be null.
 * @param requestTimerBuilder The {@link MetricBuilder} responsible for creating the endpoint timer. It's
 * recommended that you use a {@link RollingWindowTimerBuilder} with a rolling window time value that matches the
 * frequency with which the {@link SignalFxReporter} reports its data back to SignalFx, but if you have a need for
 * something else you can control the {@link Timer} creation with this argument. Cannot be null.
 * @param customRequestTimerDimensionConfigurator A custom {@link MetricDimensionConfigurator} controlling the
 * metric name and dimensions for the {@link Timer} that tracks endpoint latency, or null if you want to use the
 * default {@link #DEFAULT_REQUEST_LATENCY_TIMER_DIMENSION_CONFIGURATOR}.
 */
public SignalFxEndpointMetricsHandler(MetricMetadata signalFxReporterMetricMetadata,
                                      MetricRegistry metricRegistry,
                                      MetricBuilder<Timer> requestTimerBuilder,
                                      MetricDimensionConfigurator<Timer> customRequestTimerDimensionConfigurator
) {
    if (signalFxReporterMetricMetadata == null)
        throw new IllegalArgumentException("signalFxReporterMetricMetadata cannot be null");

    if (metricRegistry == null)
        throw new IllegalArgumentException("metricRegistry cannot be null");

    if (requestTimerBuilder == null)
        throw new IllegalArgumentException("requestTimerBuilder cannot be null");

    if (customRequestTimerDimensionConfigurator == null)
        customRequestTimerDimensionConfigurator = DEFAULT_REQUEST_LATENCY_TIMER_DIMENSION_CONFIGURATOR;
    
    this.metricMetadata = signalFxReporterMetricMetadata;
    this.metricRegistry = metricRegistry;
    this.requestTimerBuilder = requestTimerBuilder;
    this.requestTimerDimensionConfigurator = customRequestTimerDimensionConfigurator;
}
 
Example #2
Source File: SignalFxAwareCodahaleMetricsCollector.java    From riposte with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance with the given values.
 *
 * @param metricRegistry The {@link MetricRegistry} to use when building metrics.
 * @param metricMetadata The SignalFx {@link MetricMetadata} to use to build metrics.
 * @param timerBuilder The timer builder for building new timers. It's recommended that this be a {@link
 * RollingWindowTimerBuilder} that matches the reporting frequency of your app's {@link SignalFxReporter}.
 * @param histogramBuilder The histogram builder for building new histograms. It's recommended that this be a {@link
 * RollingWindowHistogramBuilder} that matches the reporting frequency of your app's {@link SignalFxReporter}.
 */
@SuppressWarnings("ConstantConditions")
public SignalFxAwareCodahaleMetricsCollector(@NotNull MetricRegistry metricRegistry,
                                             @NotNull MetricMetadata metricMetadata,
                                             @NotNull MetricBuilder<Timer> timerBuilder,
                                             @NotNull MetricBuilder<Histogram> histogramBuilder) {
    super(metricRegistry);

    if (metricMetadata == null) {
        throw new IllegalArgumentException("metricMetadata cannot be null.");
    }
    if (timerBuilder == null) {
        throw new IllegalArgumentException("timerBuilder cannot be null.");
    }
    if (histogramBuilder == null) {
        throw new IllegalArgumentException("histogramBuilder cannot be null.");
    }

    this.metricMetadata = metricMetadata;
    this.timerBuilder = timerBuilder;
    this.histogramBuilder = histogramBuilder;
}
 
Example #3
Source File: SignalFxEndpointMetricsHandler.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Override
public MetricMetadata.BuilderTagger<T> setupMetricWithDimensions(
    MetricMetadata.BuilderTagger<T> rawBuilder,
    RequestInfo<?> requestInfo,
    ResponseInfo<?> responseInfo,
    HttpProcessingState httpState,
    int responseHttpStatusCode,
    int responseHttpStatusCodeXXValue,
    long elapsedTimeMillis,
    Endpoint<?> endpoint,
    String endpointClass,
    String method,
    String matchingPathTemplate
) {
    return rawBuilder
        .withMetricName(metricName)
        .withDimension(responseCodeDimensionKey, String.valueOf(responseHttpStatusCode))
        .withDimension(uriDimensionKey, matchingPathTemplate)
        .withDimension(methodDimensionKey, method)
        .withDimension(endpointClassKey, endpointClass);
}
 
Example #4
Source File: SignalFxEndpointMetricsHandler.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Override
public MetricMetadata.BuilderTagger<T> setupMetricWithDimensions(MetricMetadata.BuilderTagger<T> rawBuilder,
                                                                 RequestInfo<?> requestInfo,
                                                                 ResponseInfo<?> responseInfo,
                                                                 HttpProcessingState httpState,
                                                                 int responseHttpStatusCode,
                                                                 int responseHttpStatusCodeXXValue,
                                                                 long elapsedTimeMillis, Endpoint<?> endpoint,
                                                                 String endpointClass, String method,
                                                                 String matchingPathTemplate) {
    // Execute the first configurator.
    MetricMetadata.BuilderTagger<T> withFirstConfiguration = firstConfigurator.setupMetricWithDimensions(
        rawBuilder, requestInfo, responseInfo, httpState, responseHttpStatusCode, responseHttpStatusCodeXXValue,
        elapsedTimeMillis, endpoint, endpointClass, method, matchingPathTemplate
    );

    // Execute the second configurator with the result of the first.
    return secondConfigurator.setupMetricWithDimensions(
        withFirstConfiguration, requestInfo, responseInfo, httpState, responseHttpStatusCode,
        responseHttpStatusCodeXXValue, elapsedTimeMillis, endpoint, endpointClass, method, matchingPathTemplate
    );
}
 
Example #5
Source File: SignalFxAwareCodahaleMetricsCollectorTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "NULL_METRIC_REGISTRY",
    "NULL_METRIC_METADATA",
    "NULL_TIMER_BUILDER",
    "NULL_HISTORGRAM_BUILDER",
})
@Test
public void kitchen_sink_constructor_throws_IllegalArgumentException_when_passed_null_arguments(
    NullArgScenario scenario
) {
    // given
    MetricRegistry registry = scenario.metricRegistryIsNull ? null : metricRegistryMock;
    MetricMetadata metadata = scenario.metricMetadataIsNull ? null : metricMetadataMock;
    MetricBuilder<Timer> timerBuilder = scenario.timerBuilderIsNull ? null : timerBuilderMock;
    MetricBuilder<Histogram> histogramBuilder = scenario.histogramBuilderIsNull ? null : histogramBuilderMock;

    // when
    Throwable ex = catchThrowable(
        () -> new SignalFxAwareCodahaleMetricsCollector(registry, metadata, timerBuilder, histogramBuilder)
    );

    // then
    assertThat(ex)
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessage(scenario.expectedExceptionMessage);
}
 
Example #6
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
private Pair<Pair<SignalFxReporter, MetricMetadata>, Pair<Long, TimeUnit>> wireUpReporterFactoryMockForConstructor(
    SignalFxReporterFactory factoryMock, MetricRegistry expectedMetricRegistry
) {
    SignalFxReporter reporterMock = mock(SignalFxReporter.class);
    doReturn(reporterMock).when(factoryMock).getReporter(expectedMetricRegistry);

    MetricMetadata metricMetadataMock = wireUpReporterForConstructor(reporterMock);

    long reportingInterval = 42;
    TimeUnit reportingTimeUnit = TimeUnit.DAYS;

    doReturn(reportingInterval).when(factoryMock).getInterval();
    doReturn(reportingTimeUnit).when(factoryMock).getTimeUnit();

    return Pair.of(Pair.of(reporterMock, metricMetadataMock), Pair.of(reportingInterval, reportingTimeUnit));
}
 
Example #7
Source File: YammerExample.java    From signalfx-java with Apache License 2.0 6 votes vote down vote up
private static Metric getCumulativeCounter(MetricsRegistry metricsRegistry,
                                           MetricMetadata metricMetadata) {
    MetricName counterCallbackName = new MetricName(YammerExample.class, "yammer.test.cumulativeCounter");
    Metric cumulativeCounter = SfUtil.cumulativeCounter(
            metricsRegistry,
            counterCallbackName,
            metricMetadata,
            new Gauge<Long>() {

                private long i = 0;

                @Override
                public Long value() {
                    return i++;
                }

            });

    metricMetadata.forMetric(cumulativeCounter)
            .withSourceName(SIGNAL_FX)
            .withDimension(LIBRARY_VERSION, YAMMER);

    return cumulativeCounter;
}
 
Example #8
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void two_arg_constructor_sets_fields_as_expected() {
    // given
    SignalFxReporterFactory reporterFactoryMock = mock(SignalFxReporterFactory.class);
    Pair<Pair<SignalFxReporter, MetricMetadata>, Pair<Long, TimeUnit>> wiredUpMocksAndData =
        wireUpReporterFactoryMockForConstructor(reporterFactoryMock, metricRegistryMock);

    MetricMetadata expectedMetricMetadata = wiredUpMocksAndData.getLeft().getRight();
    long expectedReportingInterval = wiredUpMocksAndData.getRight().getLeft();
    TimeUnit expectedReportingTimeUnit = wiredUpMocksAndData.getRight().getRight();

    // when
    SignalFxEndpointMetricsHandler instance =
        new SignalFxEndpointMetricsHandler(reporterFactoryMock, metricRegistryMock);

    // then
    assertThat(instance.metricMetadata).isSameAs(expectedMetricMetadata);
    assertThat(instance.metricRegistry).isSameAs(metricRegistryMock);
    assertThat(instance.requestTimerBuilder).isInstanceOf(RollingWindowTimerBuilder.class);
    RollingWindowTimerBuilder rwtb = (RollingWindowTimerBuilder) instance.requestTimerBuilder;
    assertThat(rwtb.amount).isEqualTo(expectedReportingInterval);
    assertThat(rwtb.timeUnit).isEqualTo(expectedReportingTimeUnit);
    assertThat(instance.requestTimerDimensionConfigurator)
        .isSameAs(DEFAULT_REQUEST_LATENCY_TIMER_DIMENSION_CONFIGURATOR);
}
 
Example #9
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void three_arg_constructor_sets_fields_as_expected() {
    // given
    SignalFxReporter reporterMock = mock(SignalFxReporter.class);
    MetricMetadata expectedMetricMetadata = wireUpReporterForConstructor(reporterMock);

    Pair<Long, TimeUnit> reportingFrequency = Pair.of(42L, TimeUnit.DAYS);

    // when
    SignalFxEndpointMetricsHandler instance =
        new SignalFxEndpointMetricsHandler(reporterMock, reportingFrequency, metricRegistryMock);

    // then
    assertThat(instance.metricMetadata).isSameAs(expectedMetricMetadata);
    assertThat(instance.metricRegistry).isSameAs(metricRegistryMock);
    assertThat(instance.requestTimerBuilder).isInstanceOf(RollingWindowTimerBuilder.class);
    RollingWindowTimerBuilder rwtb = (RollingWindowTimerBuilder) instance.requestTimerBuilder;
    assertThat(rwtb.amount).isEqualTo(reportingFrequency.getLeft());
    assertThat(rwtb.timeUnit).isEqualTo(reportingFrequency.getRight());
    assertThat(instance.requestTimerDimensionConfigurator)
        .isSameAs(DEFAULT_REQUEST_LATENCY_TIMER_DIMENSION_CONFIGURATOR);
}
 
Example #10
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true   |   false   |   false   |   signalFxReporterMetricMetadata cannot be null",
    "false  |   true    |   false   |   metricRegistry cannot be null",
    "false  |   false   |   true    |   requestTimerBuilder cannot be null"
}, splitBy = "\\|")
@Test
public void kitchen_sink_constructor_fails_with_IllegalArgumentException_if_certain_args_are_null(
    boolean metadataIsNull, boolean registryIsNull, boolean timerBuilderIsNull, String expectedMessage
) {
    // given
    MetricMetadata metricMetadata = (metadataIsNull) ? null : metricMetadataMock;
    MetricRegistry registry = (registryIsNull) ? null : metricRegistryMock;
    MetricBuilder<Timer> timerBuilder = (timerBuilderIsNull) ? null : requestTimerBuilderMock;

    // when
    Throwable ex = catchThrowable(
        () -> new SignalFxEndpointMetricsHandler(metricMetadata, registry, timerBuilder, null)
    );

    // then
    assertThat(ex).isInstanceOf(IllegalArgumentException.class)
                  .hasMessage(expectedMessage);
}
 
Example #11
Source File: MetricMetadataTest.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveMissing() {
    MetricRegistry metricRegistry = new MetricRegistry();
    MetricMetadata metadata = new MetricMetadataImpl();
    Counter counter = metricRegistry.counter("counter");
    assertFalse(metadata.removeMetric(counter, metricRegistry));
}
 
Example #12
Source File: MetricMetadataTest.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveExisting() {
    MetricRegistry metricRegistry = new MetricRegistry();
    MetricMetadata metadata = new MetricMetadataImpl();
    Metric metric = metadata.forBuilder(SettableLongGauge.Builder.INSTANCE)
            .withMetricName("gauge").withDimension("host", "myhost")
            .withMetricType(MetricType.GAUGE).createOrGet(metricRegistry);
    assertFalse(metricRegistry.getMetrics().isEmpty());
    assertTrue(metadata.getMetricType(metric).isPresent());
    assertTrue(metadata.removeMetric(metric, metricRegistry));
    assertFalse(metadata.getMetricType(metric).isPresent());
    assertTrue(metricRegistry.getMetrics().isEmpty());
}
 
Example #13
Source File: SfxMetrics.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
private <T extends Metric> T getT(String metricName, MetricMetadata.BuilderTagger<T> tagger,
                                  Map<String, String> dimensions) {
    tagger.withMetricName(metricName);
    if (dimensions != null) {
        for (Map.Entry<String, String> entry : dimensions.entrySet()) {
            tagger.withDimension(entry.getKey(), entry.getValue());
        }
    }
    return tagger.createOrGet(metricRegistry);
}
 
Example #14
Source File: SfxMetrics.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
private <T extends Metric> T getT(String metricName, MetricMetadata.BuilderTagger<T> tagger,
                                  String[] dimensions) {
    Preconditions.checkArgument(dimensions.length % 2 == 0,
            "Dimensions parameter should have even number of elements");
    tagger.withMetricName(metricName);
    for (int i = 0; i < dimensions.length - 1; i += 2) {
        tagger.withDimension(dimensions[i], dimensions[i + 1]);
    }
    return tagger.createOrGet(metricRegistry);
}
 
Example #15
Source File: YammerExample.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
private static Gauge getGauge(MetricsRegistry metricsRegistry, MetricMetadata metricMetadata) {
    Gauge gauge = metricsRegistry.newGauge(YammerExample.class, "yammer.test.gauge",
            new Gauge<Double>() {
                @Override
                public Double value() {
                    return Math.sin(System.currentTimeMillis() * 0.001 * 2 * Math.PI / 60);
                }
            });

    metricMetadata.forMetric(gauge)
            .withSourceName(SIGNAL_FX)
            .withDimension(LIBRARY_VERSION, YAMMER);
    return gauge;
}
 
Example #16
Source File: YammerExample.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
private static Timer getTimer(MetricsRegistry metricsRegistry, MetricMetadata metricMetadata) {
    Timer timer = metricsRegistry
            .newTimer(YammerExample.class, "yammer.test.timer", TimeUnit.MILLISECONDS, TimeUnit.SECONDS);
    metricMetadata.forMetric(timer)
            .withSourceName(SIGNAL_FX)
            .withDimension(LIBRARY_VERSION, YAMMER);
    return timer;
}
 
Example #17
Source File: YammerExample.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
private static Counter getCounter(MetricsRegistry metricsRegistry,
                                  MetricMetadata metricMetadata) {
    Counter counter = metricsRegistry.newCounter(YammerExample.class, "yammer.test.counter");
    metricMetadata.forMetric(counter)
            .withSourceName("signalFx")
            .withDimension(LIBRARY_VERSION, YAMMER);
    return counter;
}
 
Example #18
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeMethod() {
    metricMetadataMock = mock(MetricMetadata.class);
    metricRegistryMock = mock(MetricRegistry.class);
    requestTimerBuilderMock = mock(MetricBuilder.class);
    dimensionConfiguratorMock = mock(MetricDimensionConfigurator.class);

    handler = new SignalFxEndpointMetricsHandler(
        metricMetadataMock, metricRegistryMock, requestTimerBuilderMock, dimensionConfiguratorMock
    );

    requestInfoMock = mock(RequestInfo.class);
    responseInfoMock = mock(ResponseInfo.class);
    httpStateMock = mock(HttpProcessingState.class);
    endpointMock = mock(Endpoint.class);

    requestStartTime = Instant.now().minus(42, ChronoUnit.MILLIS);
    httpMethod = HttpMethod.PATCH;
    matchingPathTemplate = "/" + UUID.randomUUID().toString();
    doReturn(requestStartTime).when(httpStateMock).getRequestStartTime();
    doReturn(endpointMock).when(httpStateMock).getEndpointForExecution();
    doReturn(httpMethod).when(requestInfoMock).getMethod();
    doReturn(matchingPathTemplate).when(httpStateMock).getMatchingPathTemplate();

    timerBuilderTaggerMock = mock(BuilderTagger.class);
    doReturn(timerBuilderTaggerMock).when(metricMetadataMock).forBuilder(requestTimerBuilderMock);

    doReturn(timerBuilderTaggerMock).when(dimensionConfiguratorMock).setupMetricWithDimensions(
        eq(timerBuilderTaggerMock), eq(requestInfoMock), eq(responseInfoMock), eq(httpStateMock), anyInt(),
        anyInt(), anyLong(), any(), anyString(), anyString(), anyString()
    );

    timerMock = mock(Timer.class);
    doReturn(timerMock).when(timerBuilderTaggerMock).createOrGet(metricRegistryMock);
}
 
Example #19
Source File: YammerExample.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        System.out.println("Running example...");

        Properties prop = new Properties();
        prop.load(new FileInputStream("auth.properties"));
        final String auth_token = prop.getProperty("auth");
        final String hostUrlStr = prop.getProperty("host");
        final URL hostUrl = new URL(hostUrlStr);
        System.out.println("Auth=" + auth_token + " .. host=" + hostUrl);
        SignalFxReceiverEndpoint endpoint = new SignalFxEndpoint(hostUrl.getProtocol(),
                hostUrl.getHost(), hostUrl.getPort());

        MetricsRegistry metricsRegistry = new MetricsRegistry();
        SignalFxReporter reporter = new SignalFxReporter.Builder(metricsRegistry,
                new StaticAuthToken(auth_token),
                hostUrlStr).setEndpoint(endpoint)
                .setOnSendErrorHandlerCollection(
                        Collections.<OnSendErrorHandler>singleton(new OnSendErrorHandler() {
                            public void handleError(MetricError error) {
                                System.out.println("" + error.getMessage());
                            }
                        }))
                .setDetailsToAdd(ImmutableSet.of(SignalFxReporter.MetricDetails.COUNT,
                        SignalFxReporter.MetricDetails.MIN,
                        SignalFxReporter.MetricDetails.MAX))
                .build();

        final MetricMetadata metricMetadata = reporter.getMetricMetadata();

        Counter counter = getCounter(metricsRegistry, metricMetadata);

        Metric cumulativeCounter = getCumulativeCounter(metricsRegistry, metricMetadata);

        Gauge gauge1 = getGauge(metricsRegistry, metricMetadata);

        Timer timer = getTimer(metricsRegistry, metricMetadata);

        // main body generating data and sending it in a loop
        while (true) {
            final TimerContext context = timer.time();
            try {
                System.out.println("Sending data...");
                Thread.sleep(500);
                counter.inc();
            } finally {
                context.stop();
            }
            reporter.report(); // Report all metrics
        }

    }
 
Example #20
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 4 votes vote down vote up
private MetricMetadata wireUpReporterForConstructor(SignalFxReporter reporterMock) {
    MetricMetadata metricMetadataMock = mock(MetricMetadata.class);
    doReturn(metricMetadataMock).when(reporterMock).getMetricMetadata();

    return metricMetadataMock;
}
 
Example #21
Source File: SignalFxReporterTest.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
private void testReporterWithDetails(){
	
	StoredDataPointReceiver dbank = new StoredDataPointReceiver();
       assertEquals(0, dbank.addDataPoints.size());

       Set<SignalFxReporter.MetricDetails> detailsToAdd = new HashSet<SignalFxReporter.MetricDetails>();
       detailsToAdd.add(SignalFxReporter.MetricDetails.STD_DEV);
       detailsToAdd.add(SignalFxReporter.MetricDetails.MEAN);
       
       MetricsRegistry metricRegistery = new MetricsRegistry();
       SignalFxReporter reporter = new SignalFxReporter.Builder(metricRegistery, new StaticAuthToken(""), "myserver")
               .setDataPointReceiverFactory(new StaticDataPointReceiverFactory(dbank))
               .setDetailsToAdd(
           		ImmutableSet.of(
       				SignalFxReporter.MetricDetails.COUNT,
       				SignalFxReporter.MetricDetails.MIN, 
       				SignalFxReporter.MetricDetails.MAX
           		)
               )
               .setName("testReporter")
               .setDefaultSourceName("defaultSource")
               .useLocalTime(false)
               .setOnSendErrorHandlerCollection(
               		Collections.<OnSendErrorHandler>singleton(new OnSendErrorHandler(){
                       	public void handleError(MetricError error){
                       		System.out.println("" + error.getMessage());
                       	}
                       })
               )
               .setFilter(MetricPredicate.ALL)
               .setRateUnit(TimeUnit.SECONDS)
               .setDetailsToAdd(detailsToAdd)
               .build();
       
       final MetricMetadata metricMetadata = reporter.getMetricMetadata();
       
       MetricName histogramName = new MetricName("group1", "type1", "histogram");
       Histogram histogram = metricRegistery.newHistogram(histogramName, true);
       histogram.update(10);
       histogram.update(14);
       histogram.update(7);
       
       metricMetadata.forMetric(histogram)
       	.withMetricName("histogram")
       	.withSourceName("histogram_source")
       	.withMetricType(SignalFxProtocolBuffers.MetricType.GAUGE)
       	.withDimension("key", "value");
       
       reporter.report();
       
       assertEquals(2, dbank.addDataPoints.size());
	
}
 
Example #22
Source File: SfxMetrics.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
public MetricMetadata getMetricMetadata() {
    return metricMetadata;
}
 
Example #23
Source File: SfxMetrics.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
private <T extends Metric> T build(MetricBuilder<T> builder, String metricName,
                                   String... dimensions) {
    MetricMetadata.BuilderTagger<T> tagger = metricMetadata.forBuilder(builder);
    return getT(metricName, tagger, dimensions);
}
 
Example #24
Source File: SfxMetrics.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
private <T extends Metric> T build(MetricBuilder<T> builder, String metricName,
                                   Map<String, String> dimensions) {
    MetricMetadata.BuilderTagger<T> tagger = metricMetadata.forBuilder(builder);
    return getT(metricName, tagger, dimensions);
}
 
Example #25
Source File: SignalFxAwareCodahaleMetricsCollectorTest.java    From riposte with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeMethod() {
    metricRegistryMock = mock(MetricRegistry.class);
    sfxReporterFactoryMock = mock(SignalFxReporterFactory.class);
    sfxReporterMock = mock(SignalFxReporter.class);
    metricMetadataMock = mock(MetricMetadata.class);

    doReturn(sfxReporterMock).when(sfxReporterFactoryMock).getReporter(any(MetricRegistry.class));
    doReturn(metricMetadataMock).when(sfxReporterMock).getMetricMetadata();

    doReturn(reportingInterval).when(sfxReporterFactoryMock).getInterval();
    doReturn(reportingTimeUnit).when(sfxReporterFactoryMock).getTimeUnit();

    timerBuilderMock = mock(MetricBuilder.class);
    histogramBuilderMock = mock(MetricBuilder.class);
    genericMetricBuilderMock = mock(MetricBuilder.class);

    timerMock = mock(Timer.class);
    meterMock = mock(Meter.class);
    histogramMock = mock(Histogram.class);
    counterMock = mock(Counter.class);
    gaugeMock = mock(Gauge.class);
    genericMetricMock = mock(Metric.class);

    timerTaggerMock = mock(BuilderTagger.class);
    meterTaggerMock = mock(BuilderTagger.class);
    histogramTaggerMock = mock(BuilderTagger.class);
    counterTaggerMock = mock(BuilderTagger.class);
    gaugeTaggerMock = mock(Tagger.class);
    genericMetricTaggerMock = mock(BuilderTagger.class);

    setupBuilderTaggerMock(timerTaggerMock, timerBuilderMock, timerMock);
    setupBuilderTaggerMock(meterTaggerMock, MetricBuilder.METERS, meterMock);
    setupBuilderTaggerMock(histogramTaggerMock, histogramBuilderMock, histogramMock);
    setupBuilderTaggerMock(counterTaggerMock, MetricBuilder.COUNTERS, counterMock);
    setupTaggerMock(gaugeTaggerMock);
    setupBuilderTaggerMock(genericMetricTaggerMock, genericMetricBuilderMock, genericMetricMock);

    sfxImpl = new SignalFxAwareCodahaleMetricsCollector(
        metricRegistryMock, metricMetadataMock, timerBuilderMock, histogramBuilderMock
    );
}
 
Example #26
Source File: SignalFxEndpointMetricsHandler.java    From riposte with Apache License 2.0 4 votes vote down vote up
protected static MetricMetadata extractMetricMetadataFromSignalFxReporter(SignalFxReporter reporter) {
    if (reporter  == null)
        throw new IllegalArgumentException("SignalFxReporter cannot be null");

    return reporter.getMetricMetadata();
}
 
Example #27
Source File: SfxMetrics.java    From signalfx-java with Apache License 2.0 3 votes vote down vote up
/**
 * Get or create a new incremental counter.
 *
 * @param metricName
 *         The metric name.
 * @param dimensions
 *         Additional dimension key/value pairs, as a map.
 * @return The {@link IncrementalCounter} instance.
 */
public IncrementalCounter incrementalCounter(String metricName,
                                             Map<String, String> dimensions) {
    MetricMetadata.BuilderTagger<IncrementalCounter> metric = metricMetadata
            .forBuilder(IncrementalCounter.Builder.INSTANCE);
    return getT(metricName, metric, dimensions);
}
 
Example #28
Source File: SfxMetrics.java    From signalfx-java with Apache License 2.0 3 votes vote down vote up
/**
 * Register the given {@link Gauge} as a cumulative counter.
 *
 * Cumulative counters fundamentally function like gauges, but use a delta rollup by default.
 * This method allows you to report a gauge that measures a monotonically increasing value as a
 * cumulative counter to SignalFx.
 *
 * @param metricName
 *         The metric name.
 * @param gauge
 *         The {@link Gauge} instance.
 * @param dimensions
 *         Additional dimension key/value pairs (an even number of strings must be provided).
 */
public void registerGaugeAsCumulativeCounter(String metricName, Gauge<?> gauge,
                                             String... dimensions) {
    MetricMetadata.Tagger<? extends Gauge<?>> tagger = metricMetadata
            .forMetric(metricRegistry.register(metricName, gauge))
            .withMetricName(metricName)
            .withMetricType(SignalFxProtocolBuffers.MetricType.CUMULATIVE_COUNTER);
    for (int i = 0; i < dimensions.length - 1; i += 2) {
        tagger.withDimension(dimensions[i], dimensions[i + 1]);
    }
}
 
Example #29
Source File: SfxMetrics.java    From signalfx-java with Apache License 2.0 3 votes vote down vote up
/**
 * Register the given {@link Gauge} as a cumulative counter.
 *
 * Cumulative counters fundamentally function like gauges, but use a delta rollup by default.
 * This method allows you to report a gauge that measures a monotonically increasing value as a
 * cumulative counter to SignalFx.
 *
 * @param metricName
 *         The metric name.
 * @param gauge
 *         The {@link Gauge} instance.
 * @param dimensions
 *         Additional dimension key/value pairs, as a map.
 */
public void registerGaugeAsCumulativeCounter(String metricName, Gauge<?> gauge,
                                             Map<String, String> dimensions) {
    MetricMetadata.Tagger<? extends Gauge<?>> tagger = metricMetadata
            .forMetric(metricRegistry.register(metricName, gauge))
            .withMetricName(metricName)
            .withMetricType(SignalFxProtocolBuffers.MetricType.CUMULATIVE_COUNTER);
    if (dimensions != null) {
        for (Map.Entry<String, String> entry : dimensions.entrySet()) {
            tagger.withDimension(entry.getKey(), entry.getValue());
        }
    }
}
 
Example #30
Source File: SignalFxEndpointMetricsHandler.java    From riposte with Apache License 2.0 3 votes vote down vote up
/**
 * Takes in information about the request and returns a {@link MetricMetadata.BuilderTagger} that will be used
 * to create or get the appropriately-dimensioned timer.
 *
 * @param rawBuilder The brand new {@link MetricMetadata.BuilderTagger}, ready for dimensioning. You should
 * return this using the fluent method API to add metric name, dimensions, etc, i.e.
 * {@code return rawBuilder.withMetricName(...).withDimension(...).with...;}. Will never be null.
 * @param requestInfo The {@link RequestInfo} for the request. Will never be null.
 * @param responseInfo The {@link ResponseInfo} for the response associated with the request. Will never be
 * null.
 * @param httpState The {@link HttpProcessingState} associated with the request. Will never be null.
 * @param responseHttpStatusCode The HTTP status code sent back in the response.
 * @param responseHttpStatusCodeXXValue Which category the response status code falls into,
 * i.e. 1xx, 2xx, 3xx, 4xx, 5xx, etc. This is just a convenience for
 * {@code (int)(responseHttpStatusCode / 100)}.
 * @param elapsedTimeMillis How long the request took in milliseconds.
 * @param endpoint The endpoint that handled the request. This may be null in short-circuit cases where no
 * endpoint was called.
 * @param endpointClass The endpoint class name, or "NONE" in short-circuit cases where no endpoint was called.
 * @param method The HTTP method of the request, or "NONE" if requestInfo.getMethod() is null (this should never
 * happen in practice).
 * @param matchingPathTemplate The URI/path template for the request.
 * @return The {@link MetricMetadata.BuilderTagger} that should be used to create or get the
 * appropriately-dimensioned timer. Implementations should likely use the given rawBuilder with fluent method
 * calls as intended, i.e. {@code return rawBuilder.withMetricName(...).withDimension(...).with...;}
 */
MetricMetadata.BuilderTagger<T> setupMetricWithDimensions(
    MetricMetadata.BuilderTagger<T> rawBuilder,
    RequestInfo<?> requestInfo,
    ResponseInfo<?> responseInfo,
    HttpProcessingState httpState,
    int responseHttpStatusCode,
    int responseHttpStatusCodeXXValue,
    long elapsedTimeMillis,
    Endpoint<?> endpoint,
    String endpointClass,
    String method,
    String matchingPathTemplate
);