io.micrometer.core.instrument.search.Search Java Examples

The following examples show how to use io.micrometer.core.instrument.search.Search. 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: ServiceLevelObjective.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public final NumericQuery count(Function<Search, Search> search) {
    return new Instant(name, tags, baseUnit, failedMessage, requires, search, s -> s.meters().stream()
            .map(m -> {
                if (m instanceof Counter) {
                    return ((Counter) m).count();
                } else if (m instanceof Timer) {
                    return (double) ((Timer) m).count();
                } else if (m instanceof FunctionTimer) {
                    return ((FunctionTimer) m).count();
                } else if (m instanceof FunctionCounter) {
                    ((FunctionCounter) m).count();
                } else if (m instanceof LongTaskTimer) {
                    return (double) ((LongTaskTimer) m).activeTasks();
                }
                return Double.NaN;
            })
            .reduce(Double.NaN, SUM_OR_NAN)
    );
}
 
Example #2
Source File: MetricsListener.java    From spring-boot-starter-batch-web with Apache License 2.0 6 votes vote down vote up
@Override
public void afterJob(JobExecution jobExecution) {
	long jobDuration = jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime();
	meterRegistry.gauge(METRIC_NAME, Arrays.asList(//
			new ImmutableTag("context", jobExecution.getJobInstance().getJobName()), //
			new ImmutableTag("name", "duration")//
	), jobDuration);
	// What the f*** is that Thread.sleep doing here? ;-)
	// Metrics are written asynchronously to Spring Boot's repository. In our tests we experienced
	// that sometimes batch execution was so fast that this listener couldn't export the metrics
	// because they hadn't been written. It all happened in the same millisecond. So we added
	// a Thread.sleep of 100 milliseconds which gives us enough safety and doesn't hurt anyone.
	try {
		Thread.sleep(100);
	} catch (InterruptedException e) {
		throw new RuntimeException(e);
	}
	// Export Metrics to Console
	Search search = meterRegistry.find(METRIC_NAME);
	LOGGER.info(metricsOutputFormatter.format(search.gauges(), search.timers()));
}
 
Example #3
Source File: ServiceLevelObjective.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public final NumericQuery maxPercentile(Function<Search, Search> search, double percentile) {
    return new Instant(name, tags, baseUnit, failedMessage, requires, search, s -> s.meters().stream()
            .map(m -> {
                ValueAtPercentile[] valueAtPercentiles = new ValueAtPercentile[0];
                if (m instanceof DistributionSummary) {
                    valueAtPercentiles = ((DistributionSummary) m).takeSnapshot().percentileValues();
                } else if (m instanceof Timer) {
                    valueAtPercentiles = ((Timer) m).takeSnapshot().percentileValues();
                } else if (m instanceof LongTaskTimer) {
                    valueAtPercentiles = ((LongTaskTimer) m).takeSnapshot().percentileValues();
                }

                return Arrays.stream(valueAtPercentiles)
                        .filter(vap -> vap.percentile() == percentile)
                        .map(ValueAtPercentile::value)
                        .findAny()
                        .orElse(Double.NaN);
            })
            .reduce(Double.NaN, MAX_OR_NAN)
    );
}
 
Example #4
Source File: ServiceLevelObjective.java    From micrometer with Apache License 2.0 6 votes vote down vote up
/**
 * @param search The search criteria for a {@link Gauge}.
 * @return The value of the first matching gauge time series.
 */
public final NumericQuery value(Function<Search, Search> search) {
    return new Instant(name, tags, baseUnit, failedMessage, requires, search, s -> s.meters().stream()
            .map(m -> {
                if (m instanceof TimeGauge) {
                    return ((TimeGauge) m).value(TimeUnit.NANOSECONDS);
                } else if (m instanceof Gauge) {
                    return ((Gauge) m).value();
                }
                return Double.NaN;
            })
            .filter(n -> !Double.isNaN(n))
            .findAny()
            .orElse(Double.NaN)
    );
}
 
Example #5
Source File: CustomActuatorMetricServiceImpl.java    From adaptive-alerting with Apache License 2.0 6 votes vote down vote up
@Generated
@Scheduled(fixedDelay = 60000)
public void exportMetrics() {
    final List<Integer> statusCount = new ArrayList<>();
    for (final String status : statusList) {
        Search search = registry.find(status);
        if (search != null) {
            Counter counter = search.counter();
            statusCount.add(counter != null ? ((int) counter.count()) : 0);
            registry.remove(counter);
        } else {
            statusCount.add(0);
        }
    }
    statusMetricsByMinute.add(statusCount);
}
 
Example #6
Source File: JHipsterMetricsEndpoint.java    From jhipster with Apache License 2.0 5 votes vote down vote up
private Map<String, Number> processMetrics() {
    Map<String, Number> resultsProcess = new HashMap<>();

    Collection<Gauge> gauges = Search.in(this.meterRegistry).name(s -> s.contains("cpu") || s.contains("system") || s.contains("process")).gauges();
    gauges.forEach(gauge -> resultsProcess.put(gauge.getId().getName(), gauge.value()));

    Collection<TimeGauge> timeGauges = Search.in(this.meterRegistry).name(s -> s.contains("process")).timeGauges();
    timeGauges.forEach(gauge -> resultsProcess.put(gauge.getId().getName(), gauge.value(TimeUnit.MILLISECONDS)));

    return resultsProcess;
}
 
Example #7
Source File: CustomActuatorMetricService.java    From tutorials with MIT License 5 votes vote down vote up
@Scheduled(fixedDelay = 60000)
private void exportMetrics() {
    final ArrayList<Integer> statusCount = new ArrayList<Integer>();
    for (final String status : statusList) {
        Search search = registry.find(status);
        if (search != null) {
            Counter counter = search.counter();
            statusCount.add(counter != null ? ((int) counter.count()) : 0);
            registry.remove(counter);
        } else {
            statusCount.add(0);
        }
    }
    statusMetricsByMinute.add(statusCount);
}
 
Example #8
Source File: MetricsInterceptorMicrometerTest.java    From kork with Apache License 2.0 5 votes vote down vote up
private Stream<List<Tag>> getAllTagsAndRemovePercentileTag(Search actual) {
  return actual.counters().stream()
      .map(c -> c.getId().getTags())
      .map(
          tags ->
              tags.stream()
                  .filter(tag -> !tag.getKey().equalsIgnoreCase("percentile"))
                  .collect(Collectors.toList()));
}
 
Example #9
Source File: SchedulerMetricDecorator.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Override
public void dispose() {
	Search.in(globalRegistry)
	      .tagKeys(TAG_SCHEDULER_ID)
	      .meters()
	      .forEach(globalRegistry::remove);

	//note default isDisposed (returning false) is good enough, since the cleared
	//collections can always be reused even though they probably won't
	this.seenSchedulers.clear();
	this.schedulerDifferentiator.clear();
	this.executorDifferentiator.clear();
}
 
Example #10
Source File: JHipsterMetricsEndpoint.java    From jhipster with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> garbageCollectorMetrics() {
    Map<String, Object> resultsGarbageCollector = new HashMap<>();

    Collection<Timer> timers = Search.in(this.meterRegistry).name(s -> s.contains("jvm.gc.pause")).timers();
    timers.forEach(timer -> {
        String key = timer.getId().getName();

        HashMap<String, Number> gcPauseResults = new HashMap<>();
        gcPauseResults.put("count", timer.count());
        gcPauseResults.put("max", timer.max(TimeUnit.MILLISECONDS));
        gcPauseResults.put("totalTime", timer.totalTime(TimeUnit.MILLISECONDS));
        gcPauseResults.put("mean", timer.mean(TimeUnit.MILLISECONDS));

        ValueAtPercentile[] percentiles = timer.takeSnapshot().percentileValues();
        for (ValueAtPercentile percentile : percentiles) {
            gcPauseResults.put(String.valueOf(percentile.percentile()), percentile.value(TimeUnit.MILLISECONDS));
        }

        resultsGarbageCollector.putIfAbsent(key, gcPauseResults);
    });

    Collection<Gauge> gauges = Search.in(this.meterRegistry).name(s -> s.contains("jvm.gc") && !s.contains("jvm.gc.pause")).gauges();
    gauges.forEach(gauge -> resultsGarbageCollector.put(gauge.getId().getName(), gauge.value()));

    Collection<Counter> counters = Search.in(this.meterRegistry).name(s -> s.contains("jvm.gc") && !s.contains("jvm.gc.pause")).counters();
    counters.forEach(counter -> resultsGarbageCollector.put(counter.getId().getName(), counter.count()));

    gauges = Search.in(this.meterRegistry).name(s -> s.contains("jvm.classes.loaded")).gauges();
    Double classesLoaded = gauges.stream().map(Gauge::value).reduce((x, y) -> (x + y)).orElse((double) 0);
    resultsGarbageCollector.put("classesLoaded", classesLoaded);

    Collection<FunctionCounter> functionCounters = Search.in(this.meterRegistry).name(s -> s.contains("jvm.classes.unloaded")).functionCounters();
    Double classesUnloaded = functionCounters.stream().map(FunctionCounter::count).reduce((x, y) -> (x + y)).orElse((double) 0);
    resultsGarbageCollector.put("classesUnloaded", classesUnloaded);

    return resultsGarbageCollector;
}
 
Example #11
Source File: ServiceLevelObjective.java    From micrometer with Apache License 2.0 5 votes vote down vote up
Instant(String name, Tags tags, @Nullable String baseUnit,
        @Nullable String failedMessage, Collection<MeterBinder> requires,
        Function<Search, Search> search, Function<Search, Double> toValue) {
    super(name, tags, baseUnit, failedMessage, requires);
    this.search = search;
    this.toValue = toValue;
}
 
Example #12
Source File: ServiceLevelObjective.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public final NumericQuery max(Function<Search, Search> search) {
    return new Instant(name, tags, baseUnit, failedMessage, requires, search, s -> s.meters().stream()
            .map(m -> {
                if (m instanceof DistributionSummary) {
                    return ((DistributionSummary) m).max();
                } else if (m instanceof Timer) {
                    return ((Timer) m).max(TimeUnit.NANOSECONDS);
                } else if (m instanceof LongTaskTimer) {
                    return ((LongTaskTimer) m).max(TimeUnit.NANOSECONDS);
                }
                return Double.NaN;
            })
            .reduce(Double.NaN, MAX_OR_NAN)
    );
}
 
Example #13
Source File: ServiceLevelObjective.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public final NumericQuery total(Function<Search, Search> search) {
    return new Instant(name, tags, baseUnit, failedMessage, requires, search, s -> s.meters().stream()
            .map(m -> {
                if (m instanceof DistributionSummary) {
                    return ((DistributionSummary) m).totalAmount();
                } else if (m instanceof Timer) {
                    return ((Timer) m).totalTime(TimeUnit.NANOSECONDS);
                } else if (m instanceof LongTaskTimer) {
                    return ((LongTaskTimer) m).duration(TimeUnit.NANOSECONDS);
                }
                return Double.NaN;
            })
            .reduce(Double.NaN, SUM_OR_NAN)
    );
}
 
Example #14
Source File: ServiceLevelObjective.java    From micrometer with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<MeterFilter> acceptFilters() {
    return Collections.singleton(search.apply(Search.in(NOOP_REGISTRY)).acceptFilter());
}
 
Example #15
Source File: ServiceLevelObjective.java    From micrometer with Apache License 2.0 4 votes vote down vote up
protected Double getValue(MeterRegistry registry) {
    return toValue.apply(search.apply(Search.in(registry)));
}
 
Example #16
Source File: MicrometerPluginTest.java    From riptide with MIT License 4 votes vote down vote up
private Search search() {
    return registry.find("http.outgoing-requests");
}
 
Example #17
Source File: SchedulerMetricDecorator.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized ScheduledExecutorService apply(Scheduler scheduler, ScheduledExecutorService service) {
	//this is equivalent to `toString`, a detailed name like `parallel("foo", 3)`
	String schedulerName = Scannable
			.from(scheduler)
			.scanOrDefault(Attr.NAME, scheduler.getClass().getName());

	//we hope that each NAME is unique enough, but we'll differentiate by Scheduler
	String schedulerId =
			seenSchedulers.computeIfAbsent(scheduler, s -> {
				int schedulerDifferentiator = this.schedulerDifferentiator
						.computeIfAbsent(schedulerName, k -> new AtomicInteger(0))
						.getAndIncrement();

				return (schedulerDifferentiator == 0) ? schedulerName
						: schedulerName + "#" + schedulerDifferentiator;
			});

	//we now want an executorId unique to a given scheduler
	String executorId = schedulerId + "-" +
			executorDifferentiator.computeIfAbsent(scheduler, key -> new AtomicInteger(0))
			                      .getAndIncrement();

	Tags tags = Tags.of(TAG_SCHEDULER_ID, schedulerId);

	/*
	Design note: we assume that a given Scheduler won't apply the decorator twice to the
	same ExecutorService. Even though, it would simply create an extraneous meter for
	that ExecutorService, which we think is not that bad (compared to paying the price
	upfront of also tracking executors instances to deduplicate). The main goal is to
	detect Scheduler instances that have already started decorating their executors,
	in order to avoid consider two calls in a row as duplicates (yet still being able
	to distinguish between two instances with the same name and configuration).
	 */

	class MetricsRemovingScheduledExecutorService extends DelegatingScheduledExecutorService {

		MetricsRemovingScheduledExecutorService() {
			super(ExecutorServiceMetrics.monitor(globalRegistry, service, executorId, tags));
		}

		@Override
		public List<Runnable> shutdownNow() {
			removeMetrics();
			return super.shutdownNow();
		}

		@Override
		public void shutdown() {
			removeMetrics();
			super.shutdown();
		}

		void removeMetrics() {
			Search.in(globalRegistry)
			      .tag("name", executorId)
			      .meters()
			      .forEach(globalRegistry::remove);
		}
	}
	return new MetricsRemovingScheduledExecutorService();
}
 
Example #18
Source File: MetricsInterceptorMicrometerTest.java    From kork with Apache License 2.0 4 votes vote down vote up
@Test
public void allPublishedMetricsHaveTheSameSetOfTagsAndCanBeRegisteredInMicrometer()
    throws Exception {
  MockHttpServletRequest request1 = new MockHttpServletRequest();
  request1.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, Collections.emptyMap());

  MockHttpServletRequest request2 = new MockHttpServletRequest();
  request2.setAttribute(
      HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE,
      Collections.singletonMap("path-var-1", "path-val-1"));
  request2.setParameter("param-1", "val-1");

  interceptCall(interceptor, request1, RESPONSE, HANDLER, null);
  interceptCall(interceptor, request1, RESPONSE, HANDLER, new RuntimeException());
  interceptCall(interceptor, request2, RESPONSE, HANDLER, null);
  interceptCall(interceptor, request2, RESPONSE, HANDLER, new IllegalArgumentException());

  Search actual = simpleMeterRegistry.find("controller.invocations");
  assertThat(getAllTagsAndRemovePercentileTag(actual))
      .hasSize(4)
      .containsOnly(
          Arrays.asList(
              Tag.of("cause", "IllegalArgumentException"),
              Tag.of("controller", "TestController"),
              Tag.of("method", "execute"),
              Tag.of("param-1", "val-1"),
              Tag.of("param-2", "None"),
              Tag.of("path-var-1", "path-val-1"),
              Tag.of("path-var-2", "None"),
              Tag.of("statistic", "percentile"),
              Tag.of("status", "5xx"),
              Tag.of("statusCode", "500"),
              Tag.of("success", "false")),
          Arrays.asList(
              Tag.of("cause", "RuntimeException"),
              Tag.of("controller", "TestController"),
              Tag.of("method", "execute"),
              Tag.of("param-1", "None"),
              Tag.of("param-2", "None"),
              Tag.of("path-var-1", "None"),
              Tag.of("path-var-2", "None"),
              Tag.of("statistic", "percentile"),
              Tag.of("status", "5xx"),
              Tag.of("statusCode", "500"),
              Tag.of("success", "false")),
          Arrays.asList(
              Tag.of("cause", "None"),
              Tag.of("controller", "TestController"),
              Tag.of("method", "execute"),
              Tag.of("param-1", "val-1"),
              Tag.of("param-2", "None"),
              Tag.of("path-var-1", "path-val-1"),
              Tag.of("path-var-2", "None"),
              Tag.of("statistic", "percentile"),
              Tag.of("status", "2xx"),
              Tag.of("statusCode", "200"),
              Tag.of("success", "true")),
          Arrays.asList(
              Tag.of("cause", "None"),
              Tag.of("controller", "TestController"),
              Tag.of("method", "execute"),
              Tag.of("param-1", "None"),
              Tag.of("param-2", "None"),
              Tag.of("path-var-1", "None"),
              Tag.of("path-var-2", "None"),
              Tag.of("statistic", "percentile"),
              Tag.of("status", "2xx"),
              Tag.of("statusCode", "200"),
              Tag.of("success", "true")));
}
 
Example #19
Source File: ServiceLevelObjective.java    From micrometer with Apache License 2.0 4 votes vote down vote up
public NumericQuery errorRatio(Function<Search, Search> searchAll,
                               Function<Search, Search> searchErrors) {
    return count(searchAll.andThen(searchErrors))
            .dividedBy(over -> over.count(searchAll));
}
 
Example #20
Source File: MetricsAssert.java    From initializr with Apache License 2.0 4 votes vote down vote up
public MetricsAssert hasNoValue(String... metrics) {
	Arrays.asList(metrics).forEach(
			(metric) -> assertThat(Search.in(this.meterRegistry).name((n) -> n.startsWith(metric)).counter())
					.isNull());
	return this;
}
 
Example #21
Source File: MetricsAssert.java    From initializr with Apache License 2.0 4 votes vote down vote up
public MetricsAssert metricsCount(int count) {
	assertThat(Search.in(this.meterRegistry).meters()).hasSize(count);
	return this;
}
 
Example #22
Source File: MeterRegistry.java    From micrometer with Apache License 2.0 2 votes vote down vote up
/**
 * Initiate a search beginning with a metric name. If constraints added in the search are not satisfied, the search
 * will return {@code null}.
 *
 * @param name The meter name to locate.
 * @return A new search.
 */
public Search find(String name) {
    return Search.in(this).name(name);
}