Java Code Examples for io.micrometer.core.instrument.MeterRegistry#timer()

The following examples show how to use io.micrometer.core.instrument.MeterRegistry#timer() . 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: LocalJobRunner.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor create the object.
 *
 * @param dataServices    The {@link DataServices} instance to use
 * @param genieEventBus   The event bus implementation to use
 * @param workflowTasks   List of all the workflow tasks to be executed
 * @param genieWorkingDir Working directory for genie where it creates jobs directories
 * @param registry        The metrics registry to use
 */
public LocalJobRunner(
    @NotNull final DataServices dataServices,
    @NonNull final GenieEventBus genieEventBus,
    @NotNull final List<WorkflowTask> workflowTasks,
    @NotNull final Resource genieWorkingDir,
    @NotNull final MeterRegistry registry
) {
    this.persistenceService = dataServices.getPersistenceService();
    this.genieEventBus = genieEventBus;
    this.jobWorkflowTasks = workflowTasks;
    this.baseWorkingDirPath = genieWorkingDir;

    // Metrics
    this.overallSubmitTimer = registry.timer("genie.jobs.submit.localRunner.overall.timer");
    this.createJobDirTimer = registry.timer("genie.jobs.submit.localRunner.createJobDir.timer");
    this.createRunScriptTimer = registry.timer("genie.jobs.submit.localRunner.createRunScript.timer");
    this.executeJobTimer = registry.timer("genie.jobs.submit.localRunner.executeJob.timer");
    this.saveJobExecutionTimer = registry.timer("genie.jobs.submit.localRunner.saveJobExecution.timer");
    this.publishJobStartedEventTimer = registry.timer("genie.jobs.submit.localRunner.publishJobStartedEvent.timer");
    this.createInitFailureDetailsFileTimer = registry.timer(
        "genie.jobs.submit.localRunner.createInitFailureDetailsFile.timer"
    );
}
 
Example 2
Source File: TimedCronExecutorService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
public TimedCronExecutorService(
    MeterRegistry registry,
    CronExecutorService delegate,
    String executorServiceName,
    Iterable<Tag> tags) {
  this.registry = registry;
  this.delegate = delegate;
  this.executionTimer =
      registry.timer("executor", Tags.concat(tags, "name", executorServiceName));
  this.idleTimer =
      registry.timer("executor.idle", Tags.concat(tags, "name", executorServiceName));
  this.scheduledOnce =
      registry.counter("executor.scheduled.once", Tags.concat(tags, "name", executorServiceName));
  this.scheduledRepetitively =
      registry.counter(
          "executor.scheduled.repetitively", Tags.concat(tags, "name", executorServiceName));
  this.scheduledCron =
      registry.counter("executor.scheduled.cron", Tags.concat(tags, "name", executorServiceName));
}
 
Example 3
Source File: TimerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("callable task that throws exception is still recorded")
default void recordCallableException(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");

    assertThrows(Exception.class, () -> {
        t.recordCallable(() -> {
            clock(registry).add(10, TimeUnit.NANOSECONDS);
            throw new Exception("uh oh");
        });
    });

    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, t.count()),
            () -> assertEquals(10, t.totalTime(TimeUnit.NANOSECONDS), 1.0e-12));
}
 
Example 4
Source File: TimerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("wrap supplier")
default void wrapSupplier(MeterRegistry registry) {
    Timer timer = registry.timer("myTimer");
    String expectedResult = "response";
    Supplier<String> supplier = () -> {
        clock(registry).add(10, TimeUnit.NANOSECONDS);
        return expectedResult;
    };
    try {
        Supplier<String> wrappedSupplier = timer.wrap(supplier);
        assertEquals(expectedResult, wrappedSupplier.get());
        clock(registry).add(step());
    } finally {
        assertAll(() -> assertEquals(1L, timer.count()),
                () -> assertEquals(10, timer.totalTime(TimeUnit.NANOSECONDS), 1.0e-12));
    }
}
 
Example 5
Source File: TimerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("record supplier")
default void recordWithSupplier(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    String expectedResult = "response";
    Supplier<String> supplier = () -> {
        clock(registry).add(10, TimeUnit.NANOSECONDS);
        return expectedResult;
    };
    try {
        String supplierResult = t.record(supplier);
        assertEquals(expectedResult, supplierResult);
        clock(registry).add(step());
    } finally {
        assertAll(() -> assertEquals(1L, t.count()),
                () -> assertEquals(10, t.totalTime(TimeUnit.NANOSECONDS), 1.0e-12));
    }
}
 
Example 6
Source File: TimerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("record a runnable task")
default void recordWithRunnable(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");

    Runnable r = () -> {
        clock(registry).add(10, TimeUnit.NANOSECONDS);
    };
    try {
        t.record(r);
        clock(registry).add(step());
    } finally {
        assertAll(() -> assertEquals(1L, t.count()),
                () -> assertEquals(10, t.totalTime(TimeUnit.NANOSECONDS), 1.0e-12));
    }
}
 
Example 7
Source File: TimedExecutorService.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public TimedExecutorService(MeterRegistry registry, ExecutorService delegate, String executorServiceName,
                            String metricPrefix, Iterable<Tag> tags) {
    this.registry = registry;
    this.delegate = delegate;
    Tags finalTags = Tags.concat(tags, "name", executorServiceName);
    this.executionTimer = registry.timer(metricPrefix + "executor", finalTags);
    this.idleTimer = registry.timer(metricPrefix + "executor.idle", finalTags);
}
 
Example 8
Source File: TimedExecutor.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public TimedExecutor(MeterRegistry registry, Executor delegate, String executorName, String metricPrefix, Iterable<Tag> tags) {
    this.registry = registry;
    this.delegate = delegate;
    Tags finalTags = Tags.concat(tags, "name", executorName);
    this.executionTimer = registry.timer(metricPrefix + "executor.execution", finalTags);
    this.idleTimer = registry.timer(metricPrefix + "executor.idle", finalTags);
}
 
Example 9
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("total time and count are preserved for a single timing")
default void record(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    t.record(42, TimeUnit.MILLISECONDS);
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, t.count()),
            () -> assertEquals(42, t.totalTime(TimeUnit.MILLISECONDS), 1.0e-12));
}
 
Example 10
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("record durations")
default void recordDuration(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    t.record(Duration.ofMillis(42));
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, t.count()),
            () -> assertEquals(42, t.totalTime(TimeUnit.MILLISECONDS), 1.0e-12));
}
 
Example 11
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("negative times are discarded by the Timer")
default void recordNegative(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    t.record(-42, TimeUnit.MILLISECONDS);

    assertAll(() -> assertEquals(0L, t.count()),
            () -> assertEquals(0, t.totalTime(TimeUnit.NANOSECONDS), 1.0e-12));
}
 
Example 12
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("zero times contribute to the count of overall events but do not add to total time")
default void recordZero(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    t.record(0, TimeUnit.MILLISECONDS);
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, t.count()),
            () -> assertEquals(0L, t.totalTime(TimeUnit.NANOSECONDS)));
}
 
Example 13
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("record with stateful Sample instance")
default void recordWithSample(MeterRegistry registry) {
    Timer timer = registry.timer("myTimer");
    Timer.Sample sample = Timer.start(registry);

    clock(registry).add(10, TimeUnit.NANOSECONDS);
    sample.stop(timer);
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, timer.count()),
            () -> assertEquals(10, timer.totalTime(TimeUnit.NANOSECONDS), 1.0e-12));
}
 
Example 14
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
default void recordMax(MeterRegistry registry) {
    Timer timer = registry.timer("my.timer");
    timer.record(10, TimeUnit.MILLISECONDS);
    timer.record(1, TimeUnit.SECONDS);

    clock(registry).add(step()); // for Atlas, which is step rather than ring-buffer based
    assertThat(timer.max(TimeUnit.SECONDS)).isEqualTo(1);
    assertThat(timer.max(TimeUnit.MILLISECONDS)).isEqualTo(1000);

    //noinspection ConstantConditions
    clock(registry).add(Duration.ofMillis(step().toMillis() * DistributionStatisticConfig.DEFAULT.getBufferLength()));
    assertThat(timer.max(TimeUnit.SECONDS)).isEqualTo(0);
}
 
Example 15
Source File: K8sMetricsAutoConfiguration.java    From foremast with Apache License 2.0 4 votes vote down vote up
@Override
public void customize(MeterRegistry registry) {
    String commonTagNameValuePair = metricsProperties.getCommonTagNameValuePairs();
    if (commonTagNameValuePair != null && !commonTagNameValuePair.isEmpty()) {
        String[] pairs = commonTagNameValuePair.split(",");
        for(String p : pairs) {
            String[] nameAndValue = p.split(":");
            if (nameAndValue == null || nameAndValue.length != 2) {
                throw new IllegalStateException("Invalid common tag name value pair:" + p);
            }

            String valuePattern = nameAndValue[1];
            int sepIndex = valuePattern.indexOf('|');
            String[] patterns = null;
            if (sepIndex > 0) {
                patterns = valuePattern.split(Pattern.quote("|"));
            }
            else {
                patterns = new String[] { valuePattern };
            }
            for(int i = 0; i < patterns.length; i ++) {
                String value = null;
                if (patterns[i].startsWith("ENV.")) {
                    value = System.getenv(patterns[i].substring(4));
                }
                else {
                    value = System.getProperty(patterns[i]);
                    if ((value == null || value.isEmpty()) && appContext != null) {
                        value = appContext.getEnvironment().getProperty(patterns[i]);
                    }
                }

                if (value != null && !value.isEmpty()) {
                    registry.config().commonTags(nameAndValue[0], value);
                    break;
                }
            }
        }
    }

    String statuses = metricsProperties.getInitializeForStatuses();
    if (statuses != null || !statuses.isEmpty()) {
        String[] statusCodes = statuses.split(",");
        for(String code: statusCodes) {
            if (metricsProperties.hasCaller()) {
                registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**", "caller", "*",  "outcome", "SERVER_ERROR");
            }
            else {
                registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**", "outcome", "SERVER_ERROR");
            }
        }
    }
}
 
Example 16
Source File: K8sMetricsAutoConfiguration.java    From foremast with Apache License 2.0 4 votes vote down vote up
@Override
public void customize(MeterRegistry registry) {
    String commonTagNameValuePair = k8sMetricsProperties.getCommonTagNameValuePairs();
    if (commonTagNameValuePair != null && !commonTagNameValuePair.isEmpty()) {
        String[] pairs = commonTagNameValuePair.split(",");
        for(String p : pairs) {
            String[] nameAndValue = p.split(":");
            if (nameAndValue == null || nameAndValue.length != 2) {
                throw new IllegalStateException("Invalid common tag name value pair:" + p);
            }

            String valuePattern = nameAndValue[1];
            int sepIndex = valuePattern.indexOf('|');
            String[] patterns = null;
            if (sepIndex > 0) {
                patterns = valuePattern.split(Pattern.quote("|"));
            }
            else {
                patterns = new String[] { valuePattern };
            }
            for(int i = 0; i < patterns.length; i ++) {
                String value = null;
                if (patterns[i].startsWith("ENV.")) {
                    value = System.getenv(patterns[i].substring(4));
                }
                else {
                    value = System.getProperty(patterns[i]);
                    if ((value == null || value.isEmpty()) && appContext != null) {
                        value = appContext.getEnvironment().getProperty(patterns[i]);
                    }
                }

                if (value != null && !value.isEmpty()) {
                    registry.config().commonTags(nameAndValue[0], value);
                    break;
                }
            }
        }
    }

    String statuses = k8sMetricsProperties.getInitializeForStatuses();
    if (statuses != null || !statuses.isEmpty()) {
        String[] statusCodes = statuses.split(",");
        for(String code: statusCodes) {
            if (k8sMetricsProperties.hasCaller()) {
                registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**", "caller", "*");
            }
            else {
                registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**");
            }
        }
    }
}
 
Example 17
Source File: K8sMetricsAutoConfiguration.java    From foremast with Apache License 2.0 4 votes vote down vote up
@Override
public void customize(MeterRegistry registry) {
    String commonTagNameValuePair = metricsProperties.getCommonTagNameValuePairs();
    if (commonTagNameValuePair != null && !commonTagNameValuePair.isEmpty()) {
        String[] pairs = commonTagNameValuePair.split(",");
        for(String p : pairs) {
            String[] nameAndValue = p.split(":");
            if (nameAndValue == null || nameAndValue.length != 2) {
                throw new IllegalStateException("Invalid common tag name value pair:" + p);
            }

            String valuePattern = nameAndValue[1];
            int sepIndex = valuePattern.indexOf('|');
            String[] patterns = null;
            if (sepIndex > 0) {
                patterns = valuePattern.split(Pattern.quote("|"));
            }
            else {
                patterns = new String[] { valuePattern };
            }
            for(int i = 0; i < patterns.length; i ++) {
                String value = null;
                if (patterns[i].startsWith("ENV.")) {
                    value = System.getenv(patterns[i].substring(4));
                }
                else {
                    value = System.getProperty(patterns[i]);
                    if ((value == null || value.isEmpty()) && appContext != null) {
                        value = appContext.getEnvironment().getProperty(patterns[i]);
                    }
                }

                if (value != null && !value.isEmpty()) {
                    registry.config().commonTags(nameAndValue[0], value);
                    break;
                }
            }
        }
    }

    String statuses = metricsProperties.getInitializeForStatuses();
    if (statuses != null || !statuses.isEmpty()) {
        String[] statusCodes = statuses.split(",");
        for(String code: statusCodes) {
            if (metricsProperties.hasCaller()) {
                registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**", "caller", "*");
            }
            else {
                registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**");
            }
        }
    }
}
 
Example 18
Source File: K8sMetricsAutoConfiguration.java    From foremast with Apache License 2.0 4 votes vote down vote up
@Override
public void customize(MeterRegistry registry) {
    String commonTagNameValuePair = metricsProperties.getCommonTagNameValuePairs();
    if (commonTagNameValuePair != null && !commonTagNameValuePair.isEmpty()) {
        String[] pairs = commonTagNameValuePair.split(",");
        for(String p : pairs) {
            String[] nameAndValue = p.split(":");
            if (nameAndValue == null || nameAndValue.length != 2) {
                throw new IllegalStateException("Invalid common tag name value pair:" + p);
            }

            String valuePattern = nameAndValue[1];
            int sepIndex = valuePattern.indexOf('|');
            String[] patterns = null;
            if (sepIndex > 0) {
                patterns = valuePattern.split(Pattern.quote("|"));
            }
            else {
                patterns = new String[] { valuePattern };
            }
            for(int i = 0; i < patterns.length; i ++) {
                String value = null;
                if (patterns[i].startsWith("ENV.")) {
                    value = System.getenv(patterns[i].substring(4));
                }
                else {
                    value = System.getProperty(patterns[i]);
                    if ((value == null || value.isEmpty()) && appContext != null) {
                        value = appContext.getEnvironment().getProperty(patterns[i]);
                    }
                }

                if (value != null && !value.isEmpty()) {
                    registry.config().commonTags(nameAndValue[0], value);
                    break;
                }
            }
        }
    }

    String statuses = metricsProperties.getInitializeForStatuses();
    if (statuses != null || !statuses.isEmpty()) {
        String[] statusCodes = statuses.split(",");
        for(String code: statusCodes) {
            if (metricsProperties.hasCaller()) {
                registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**", "caller", "*");
            }
            else {
                registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**");
            }
        }
    }
}
 
Example 19
Source File: MicrometerRSocket.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
private static Timer timer(
    MeterRegistry meterRegistry, String interactionModel, SignalType signalType, Tag... tags) {

  return meterRegistry.timer(
      "rsocket." + interactionModel, Tags.of(tags).and("signal.type", signalType.name()));
}
 
Example 20
Source File: MeterPool.java    From data-highway with Apache License 2.0 4 votes vote down vote up
public MeterPool(MeterRegistry registry) {
  counterPool = new KeyedSharedObjectPool<NameAndTags, Counter>() {
    @Override
    protected Counter constructValue(NameAndTags key) {
      return registry.counter(key.getName(), key.getTags());
    }

    @Override
    protected void destroyValue(NameAndTags key, Counter value) {
      registry.remove(value);
    }
  };

  timeGaugePool = new KeyedSharedObjectPool<NameAndTags, SettableTimeGauge>() {
    @Override
    protected SettableTimeGauge constructValue(NameAndTags key) {
      AtomicLong value = new AtomicLong();
      TimeGauge timeGauge = registry
          .more()
          .timeGauge(key.getName(), key.getTags(), value, MILLISECONDS, AtomicLong::doubleValue);
      return new SettableTimeGauge(timeGauge, value);
    }

    @Override
    protected void destroyValue(NameAndTags key, SettableTimeGauge value) {
      registry.remove(value);
    }
  };

  timerPool = new KeyedSharedObjectPool<NameAndTags, Timer>() {
    @Override
    protected Timer constructValue(NameAndTags key) {
      return registry.timer(key.getName(), key.getTags());
    }

    @Override
    protected void destroyValue(NameAndTags key, Timer value) {
      registry.remove(value);
    }
  };

  gaugePool = new KeyedSharedObjectPool<MeterPool.NameAndTags, SettableGauge>() {
    @Override
    protected SettableGauge constructValue(NameAndTags key) {
      AtomicLong value = new AtomicLong();
      Gauge gauge = Gauge.builder(key.getName(), value, AtomicLong::doubleValue).tags(key.getTags()).register(registry);
      return new SettableGauge(gauge, value);
    }

    @Override
    protected void destroyValue(NameAndTags key, SettableGauge value) {
      registry.remove(value);
    }
  };
}