Search in sources :

Example 16 with MetricName

use of com.palantir.tritium.metrics.registry.MetricName in project metric-schema by palantir.

the class UtilityGenerator method generateSimpleMetricFactory.

private static List<MethodSpec> generateSimpleMetricFactory(String namespace, String metricName, Optional<String> libraryName, MetricDefinition definition, ImplementationVisibility visibility) {
    boolean isGauge = MetricType.GAUGE.equals(definition.getType());
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(Custodian.sanitizeName(metricName)).addModifiers(visibility.apply()).returns(MetricTypes.type(definition.getType())).addParameters(definition.getTagDefinitions().stream().filter(tag -> tag.getValues().size() != 1).map(tag -> ParameterSpec.builder(getTagClassName(metricName, tag), Custodian.sanitizeName(tag.getName())).addAnnotation(Safe.class).build()).collect(ImmutableList.toImmutableList())).addJavadoc(Javadoc.render(definition.getDocs()));
    CodeBlock metricNameBlock = metricName(namespace, metricName, libraryName, definition);
    MethodSpec metricNameMethod = MethodSpec.methodBuilder(Custodian.sanitizeName(metricName + "MetricName")).addModifiers(visibility.apply()).addModifiers(Modifier.STATIC).returns(MetricName.class).addCode("return $L;", metricNameBlock).build();
    String metricRegistryMethod = MetricTypes.registryAccessor(definition.getType());
    if (isGauge) {
        methodBuilder.addParameter(ParameterizedTypeName.get(ClassName.get(Gauge.class), WildcardTypeName.subtypeOf(Object.class)), ReservedNames.GAUGE_NAME);
        // TODO(ckozak): Update to use a method which can log a warning and replace existing gauges.
        // See MetricRegistries.registerWithReplacement.
        methodBuilder.addStatement("$L.$L($L(), $L)", ReservedNames.REGISTRY_NAME, metricRegistryMethod, metricNameMethod.name, ReservedNames.GAUGE_NAME);
    } else {
        methodBuilder.addAnnotation(CheckReturnValue.class);
        methodBuilder.addStatement("return $L.$L($L)", ReservedNames.REGISTRY_NAME, metricRegistryMethod, metricNameBlock);
    }
    MethodSpec method = methodBuilder.build();
    return isGauge ? ImmutableList.of(method, metricNameMethod) : ImmutableList.of(method);
}
Also used : Iterables(com.google.common.collect.Iterables) ParameterSpec(com.squareup.javapoet.ParameterSpec) MetricName(com.palantir.tritium.metrics.registry.MetricName) Modifier(javax.lang.model.element.Modifier) CheckReturnValue(com.google.errorprone.annotations.CheckReturnValue) MethodSpec(com.squareup.javapoet.MethodSpec) FieldSpec(com.squareup.javapoet.FieldSpec) ClassName(com.squareup.javapoet.ClassName) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec) TaggedMetricRegistry(com.palantir.tritium.metrics.registry.TaggedMetricRegistry) JavaFile(com.squareup.javapoet.JavaFile) Objects(java.util.Objects) List(java.util.List) Safe(com.palantir.logsafe.Safe) ImmutableList(com.google.common.collect.ImmutableList) Optional(java.util.Optional) Gauge(com.codahale.metrics.Gauge) Preconditions(com.palantir.logsafe.Preconditions) CodeBlock(com.squareup.javapoet.CodeBlock) MethodSpec(com.squareup.javapoet.MethodSpec) CodeBlock(com.squareup.javapoet.CodeBlock) Safe(com.palantir.logsafe.Safe)

Example 17 with MetricName

use of com.palantir.tritium.metrics.registry.MetricName in project dialogue by palantir.

the class SimulationMetricsReporter method addSeries.

private void addSeries(Pattern metricNameRegex, Supplier<XYChart> chartSupplier) {
    Map<MetricName, List<Double>> map = measurements.asMap();
    List<MetricName> columns = map.keySet().stream().filter(metric -> !metric.equals(X_AXIS)).filter(metric -> metricNameRegex.asPredicate().test(asString(metric))).sorted(Comparator.comparing(SimulationMetricsReporter::asString)).collect(Collectors.toList());
    for (MetricName column : columns) {
        XYChart chart = chartSupplier.get();
        // if we render too many samples, it just ends up looking like a wall of colour
        int granularity = chart.getWidth() / 3;
        double[] xAxis = reduceGranularity(granularity, map.get(X_AXIS).stream().mapToDouble(d -> d).toArray());
        String[] nullToolTips = Collections.nCopies(xAxis.length, null).toArray(new String[] {});
        double[] series = reduceGranularity(granularity, map.get(column).stream().mapToDouble(d -> d).toArray());
        Preconditions.checkState(series.length == xAxis.length, "Series must all be same length", SafeArg.of("column", column), SafeArg.of("xaxis", xAxis.length), SafeArg.of("length", series.length));
        chart.addSeries(asString(column) + ".count", xAxis, series).setToolTips(nullToolTips);
    }
}
Also used : XYChartBuilder(org.knowm.xchart.XYChartBuilder) MetricName(com.palantir.tritium.metrics.registry.MetricName) LoggerFactory(org.slf4j.LoggerFactory) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Counting(com.codahale.metrics.Counting) SafeArg(com.palantir.logsafe.SafeArg) ImmutableList(com.google.common.collect.ImmutableList) XYSeries(org.knowm.xchart.XYSeries) Styler(org.knowm.xchart.style.Styler) Map(java.util.Map) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) Logger(org.slf4j.Logger) LoadingCache(com.github.benmanes.caffeine.cache.LoadingCache) BitmapEncoder(org.knowm.xchart.BitmapEncoder) XYChart(org.knowm.xchart.XYChart) Predicate(java.util.function.Predicate) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Gauge(com.codahale.metrics.Gauge) Pattern(java.util.regex.Pattern) Comparator(java.util.Comparator) Collections(java.util.Collections) Preconditions(com.palantir.logsafe.Preconditions) MetricName(com.palantir.tritium.metrics.registry.MetricName) XYChart(org.knowm.xchart.XYChart) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List)

Example 18 with MetricName

use of com.palantir.tritium.metrics.registry.MetricName in project dialogue by palantir.

the class BalancedScoreTracker method registerGauges.

private static void registerGauges(TaggedMetricRegistry taggedMetrics, String channelName, ImmutableList<ChannelScoreInfo> channels) {
    if (channels.size() > 10) {
        log.info("Not registering gauges as there are too many nodes {}", SafeArg.of("count", channels.size()));
        return;
    }
    for (int hostIndex = 0; hostIndex < channels.size(); hostIndex++) {
        MetricName metricName = DialogueBalancedMetrics.of(taggedMetrics).score().channelName(channelName).hostIndex(Integer.toString(hostIndex)).buildMetricName();
        // Weak gauge ensures this object can be GCd. Itherwise the tagged metric registry could hold the last ref!
        // Defensive averaging for the possibility that people create multiple channels with the same channelName.
        DialogueInternalWeakReducingGauge.getOrCreate(taggedMetrics, metricName, c -> c.computeScoreSnapshot().getScore(), longStream -> {
            long[] longs = longStream.toArray();
            if (log.isInfoEnabled() && longs.length > 1 && LongStream.of(longs).distinct().count() > 1) {
                log.info("Multiple ({}) objects contribute to the same gauge, taking the average " + "(beware this may be misleading) {} {}", SafeArg.of("count", longs.length), SafeArg.of("metricName", metricName), SafeArg.of("values", Arrays.toString(longs)));
            }
            return Arrays.stream(longs).average().orElse(0);
        }, channels.get(hostIndex));
    }
}
Also used : MetricName(com.palantir.tritium.metrics.registry.MetricName)

Example 19 with MetricName

use of com.palantir.tritium.metrics.registry.MetricName in project atlasdb by palantir.

the class MetricsManager method registerMetric.

/**
 * Add a new gauge metric of the given name.
 *
 * If the metric already exists, this will REPLACE it with a new metric.
 * Consider using {@link MetricsManager#registerOrAddToMetric} instead.
 */
public void registerMetric(Class clazz, String metricName, Gauge gauge, Map<String, String> tag) {
    MetricName metricToAdd = MetricName.builder().safeName(MetricRegistry.name(clazz, metricName)).safeTags(tag).build();
    if (taggedMetricRegistry.getMetrics().containsKey(metricToAdd)) {
        log.warn("Replacing the metric [ {} ]. This will happen if you are trying to re-register metrics " + "or have two tagged metrics with the same name across the application.", SafeArg.of("metricName", metricName));
        taggedMetricRegistry.remove(metricToAdd);
    }
    taggedMetricRegistry.gauge(metricToAdd, gauge);
}
Also used : MetricName(com.palantir.tritium.metrics.registry.MetricName)

Example 20 with MetricName

use of com.palantir.tritium.metrics.registry.MetricName in project atlasdb by palantir.

the class AtlasDbMetricsTest method instrumentTaggedAsyncFunction.

@Test
public void instrumentTaggedAsyncFunction() {
    AsyncTestService asyncTestService = AtlasDbMetrics.instrumentWithTaggedMetrics(taggedMetrics, AsyncTestService.class, this.asyncTestService);
    List<ListenableFuture<String>> futures = fireOffTenAsyncPings(asyncTestService);
    Instant now = Instant.now();
    MetricName metricName = MetricName.builder().safeName(ASYNC_PING_METRIC_NAME).build();
    awaitMetricsToBeReported(futures, metricName);
    assertThat(Instant.now()).as("in the event of scheduling issues, and despite having 10 concurrent futures, we complete " + "everything with 2*ttl").isBefore(now.plus(ASYNC_DURATION_TTL.plus(ASYNC_DURATION_TTL)));
    assertAllAsyncPingMetricsAreAccuratelyRecorded(futures, metricName);
}
Also used : MetricName(com.palantir.tritium.metrics.registry.MetricName) Instant(java.time.Instant) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Test(org.junit.Test)

Aggregations

MetricName (com.palantir.tritium.metrics.registry.MetricName)37 TaggedMetricRegistry (com.palantir.tritium.metrics.registry.TaggedMetricRegistry)11 Test (org.junit.jupiter.api.Test)10 Metric (com.codahale.metrics.Metric)9 DefaultTaggedMetricRegistry (com.palantir.tritium.metrics.registry.DefaultTaggedMetricRegistry)9 Timer (com.codahale.metrics.Timer)7 Counter (com.codahale.metrics.Counter)6 Histogram (com.codahale.metrics.Histogram)6 Meter (com.codahale.metrics.Meter)6 Test (org.junit.Test)6 Gauge (com.codahale.metrics.Gauge)5 Closeable (java.io.Closeable)5 ImmutableList (com.google.common.collect.ImmutableList)4 List (java.util.List)4 ConsoleReporter (com.codahale.metrics.ConsoleReporter)3 MetricSet (com.codahale.metrics.MetricSet)3 OkHttpClient (okhttp3.OkHttpClient)3 Request (okhttp3.Request)3 Response (okhttp3.Response)3 ExponentiallyDecayingReservoir (com.codahale.metrics.ExponentiallyDecayingReservoir)2