io.micrometer.core.instrument.binder.BaseUnits Java Examples

The following examples show how to use io.micrometer.core.instrument.binder.BaseUnits. 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: ClassLoaderMetrics.java    From micrometer with Apache License 2.0 8 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    ClassLoadingMXBean classLoadingBean = ManagementFactory.getClassLoadingMXBean();

    Gauge.builder("jvm.classes.loaded", classLoadingBean, ClassLoadingMXBean::getLoadedClassCount)
            .tags(tags)
            .description("The number of classes that are currently loaded in the Java virtual machine")
            .baseUnit(BaseUnits.CLASSES)
            .register(registry);

    FunctionCounter.builder("jvm.classes.unloaded", classLoadingBean, ClassLoadingMXBean::getUnloadedClassCount)
            .tags(tags)
            .description("The total number of classes unloaded since the Java virtual machine has started execution")
            .baseUnit(BaseUnits.CLASSES)
            .register(registry);
}
 
Example #2
Source File: CountedThreadFactory.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Wraps a {@link ThreadFactory} with an explicit name and records the number of created, running
 * and terminated threads.
 *
 * @param delegate {@link ThreadFactory} to wrap.
 * @param registry {@link MeterRegistry} that will contain the metrics.
 * @param name name for this delegate.
 * @param tags tags that can provide additional context.
 */
public CountedThreadFactory(
    ThreadFactory delegate, MeterRegistry registry, String name, Iterable<Tag> tags) {
  this.delegate = delegate;
  this.created =
      Counter.builder("thread.factory.created")
          .tags(Tags.concat(tags, "name", name))
          .description(
              "The approximate number of threads which were created with a thread factory")
          .baseUnit(BaseUnits.THREADS)
          .register(registry);
  this.terminated =
      Counter.builder("thread.factory.terminated")
          .tags(Tags.concat(tags, "name", name))
          .description("The approximate number of threads which have finished execution")
          .baseUnit(BaseUnits.THREADS)
          .register(registry);
  Gauge.builder("thread.factory.running", running, AtomicInteger::get)
      .tags(Tags.concat(tags, "name", name))
      .description(
          "The approximate number of threads which have started to execute, but have not terminated")
      .baseUnit(BaseUnits.THREADS)
      .register(registry);
}
 
Example #3
Source File: TimedHandler.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public TimedHandler(MeterRegistry registry, Iterable<Tag> tags, HttpServletRequestTagsProvider tagsProvider) {
    this.registry = registry;
    this.tags = tags;
    this.tagsProvider = tagsProvider;

    this.openRequests = LongTaskTimer.builder("jetty.server.dispatches.open")
            .description("Jetty dispatches that are currently in progress")
            .tags(tags)
            .register(registry);

    this.asyncDispatches = Counter.builder("jetty.server.async.dispatches")
            .description("Asynchronous dispatches")
            .tags(tags)
            .register(registry);

    this.asyncExpires = Counter.builder("jetty.server.async.expires")
            .description("Asynchronous operations that timed out before completing")
            .tags(tags)
            .register(registry);

    Gauge.builder("jetty.server.async.waits", asyncWaits, AtomicInteger::doubleValue)
            .description("Pending asynchronous wait operations")
            .baseUnit(BaseUnits.OPERATIONS)
            .tags(tags)
            .register(registry);
}
 
Example #4
Source File: DatabaseTableMetrics.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    ToDoubleFunction<DataSource> totalRows = ds -> {
        try (Connection conn = ds.getConnection();
             PreparedStatement ps = conn.prepareStatement(query);
             ResultSet rs = ps.executeQuery()) {
            rs.next();
            return rs.getInt(1);
        } catch (SQLException ignored) {
            return 0;
        }
    };

    Gauge.builder("db.table.size", dataSource, totalRows)
            .tags(tags)
            .tag("db", dataSourceName)
            .tag("table", tableName)
            .description("Number of rows in a database table")
            .baseUnit(BaseUnits.ROWS)
            .register(registry);
}
 
Example #5
Source File: TomcatMetrics.java    From micrometer with Apache License 2.0 6 votes vote down vote up
private void registerThreadPoolMetrics(MeterRegistry registry) {
    registerMetricsEventually("type", "ThreadPool", (name, allTags) -> {
        Gauge.builder("tomcat.threads.config.max", mBeanServer,
                s -> safeDouble(() -> s.getAttribute(name, "maxThreads")))
                .tags(allTags)
                .baseUnit(BaseUnits.THREADS)
                .register(registry);

        Gauge.builder("tomcat.threads.busy", mBeanServer,
                s -> safeDouble(() -> s.getAttribute(name, "currentThreadsBusy")))
                .tags(allTags)
                .baseUnit(BaseUnits.THREADS)
                .register(registry);

        Gauge.builder("tomcat.threads.current", mBeanServer,
                s -> safeDouble(() -> s.getAttribute(name, "currentThreadCount")))
                .tags(allTags)
                .baseUnit(BaseUnits.THREADS)
                .register(registry);
    });
}
 
Example #6
Source File: FileDescriptorMetrics.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    if (openFilesMethod != null) {
        Gauge.builder("process.files.open", osBean, x -> invoke(openFilesMethod))
                .tags(tags)
                .description("The open file descriptor count")
                .baseUnit(BaseUnits.FILES)
                .register(registry);
    }

    if (maxFilesMethod != null) {
        Gauge.builder("process.files.max", osBean, x -> invoke(maxFilesMethod))
                .tags(tags)
                .description("The maximum file descriptor count")
                .baseUnit(BaseUnits.FILES)
                .register(registry);
    }
}
 
Example #7
Source File: JvmHeapPressureMetrics.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Override
public void bindTo(@NonNull MeterRegistry registry) {
    Gauge.builder("jvm.memory.usage.after.gc", lastOldGenUsageAfterGc, AtomicReference::get)
            .tags(tags)
            .tag("area", "heap")
            .tag("generation", "old")
            .description("The percentage of old gen heap used after the last GC event, in the range [0..1]")
            .baseUnit(BaseUnits.PERCENT)
            .register(registry);

    Gauge.builder("jvm.gc.overhead", gcPauseSum,
            pauseSum -> {
                double overIntervalMillis = Math.min(System.nanoTime() - startOfMonitoring, lookback.toNanos()) / 1e6;
                return gcPauseSum.poll() / overIntervalMillis;
            })
            .tags(tags)
            .description("An approximation of the percent of CPU time used by GC activities over the last lookback period or since monitoring began, whichever is shorter, in the range [0..1]")
            .baseUnit(BaseUnits.PERCENT)
            .register(registry);
}
 
Example #8
Source File: DiskSpaceMetrics.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    Iterable<Tag> tagsWithPath = Tags.concat(tags, "path", absolutePath);
    Gauge.builder("disk.free", path, File::getUsableSpace)
            .tags(tagsWithPath)
            .description("Usable space for path")
            .baseUnit(BaseUnits.BYTES)
            .strongReference(true)
            .register(registry);
    Gauge.builder("disk.total", path, File::getTotalSpace)
            .tags(tagsWithPath)
            .description("Total space for path")
            .baseUnit(BaseUnits.BYTES)
            .strongReference(true)
            .register(registry);
}
 
Example #9
Source File: CompositeMeterRegistryTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@DisplayName("base units on meters that support them are passed through underlying registries")
@Test
void baseUnitsPreserved() {
    composite.add(simple);

    Counter.builder("counter").baseUnit(BaseUnits.BYTES).register(composite);
    DistributionSummary.builder("summary").baseUnit(BaseUnits.BYTES).register(composite);
    Gauge.builder("gauge", new AtomicInteger(0), AtomicInteger::get).baseUnit(BaseUnits.BYTES).register(composite);

    assertThat(simple.get("counter").counter().getId().getBaseUnit()).isEqualTo(BaseUnits.BYTES);
    assertThat(simple.get("summary").summary().getId().getBaseUnit()).isEqualTo(BaseUnits.BYTES);
    assertThat(simple.get("gauge").gauge().getId().getBaseUnit()).isEqualTo(BaseUnits.BYTES);
}
 
Example #10
Source File: JvmMemoryMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private void assertJvmBufferMetrics(MeterRegistry registry, String bufferId) {
    assertThat(registry.get("jvm.buffer.count").tags("id", bufferId)
        .gauge().value()).isGreaterThanOrEqualTo(0);

    Gauge memoryUsedDirect = registry.get("jvm.buffer.memory.used").tags("id", bufferId).gauge();
    assertThat(memoryUsedDirect.value()).isNotNull();
    assertThat(memoryUsedDirect.getId().getBaseUnit()).isEqualTo(BaseUnits.BYTES);

    Gauge bufferTotal = registry.get("jvm.buffer.total.capacity").tags("id", bufferId).gauge();
    assertThat(bufferTotal.value()).isGreaterThanOrEqualTo(0);
    assertThat(bufferTotal.getId().getBaseUnit()).isEqualTo(BaseUnits.BYTES);
}
 
Example #11
Source File: JvmMemoryMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private void assertJvmMemoryMetrics(MeterRegistry registry, String area) {
    Gauge memUsed = registry.get("jvm.memory.used").tags("area", area).gauge();
    assertThat(memUsed.value()).isGreaterThanOrEqualTo(0);
    assertThat(memUsed.getId().getBaseUnit()).isEqualTo(BaseUnits.BYTES);

    Gauge memCommitted = registry.get("jvm.memory.committed").tags("area", area).gauge();
    assertThat(memCommitted.value()).isNotNull();
    assertThat(memCommitted.getId().getBaseUnit()).isEqualTo(BaseUnits.BYTES);

    Gauge memMax = registry.get("jvm.memory.max").tags("area", area).gauge();
    assertThat(memMax.value()).isNotNull();
    assertThat(memMax.getId().getBaseUnit()).isEqualTo(BaseUnits.BYTES);
}
 
Example #12
Source File: LoggingMeterRegistryTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void humanReadableByteCount() {
    LoggingMeterRegistry.Printer printer = registry.new Printer(DistributionSummary.builder("my.summary")
            .baseUnit(BaseUnits.BYTES)
            .register(registry));

    assertThat(printer.humanReadableBaseUnit(Double.NaN)).isEqualTo("NaN B");
    assertThat(printer.humanReadableBaseUnit(1.0)).isEqualTo("1 B");
    assertThat(printer.humanReadableBaseUnit(1024)).isEqualTo("1 KiB");
    assertThat(printer.humanReadableBaseUnit(1024 * 1024 * 2.5678976654)).isEqualTo("2.567898 MiB");
}
 
Example #13
Source File: PrometheusMeterRegistryTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Issue("#1883")
@Test
void namesToCollectors() {
    AtomicInteger n = new AtomicInteger(0);
    Gauge.builder("gauge", n, AtomicInteger::get).tags("a", "b").baseUnit(BaseUnits.BYTES).register(registry);
    assertThat(prometheusRegistry).extracting("namesToCollectors").extracting("gauge_bytes").isNotNull();
}
 
Example #14
Source File: ServiceLevelObjectiveConfiguration.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Bean
HealthMeterRegistry healthMeterRegistry() {
    HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT)
            .serviceLevelObjectives(JvmServiceLevelObjectives.MEMORY)
            .serviceLevelObjectives(OperatingSystemServiceLevelObjectives.DISK)
            .serviceLevelObjectives(
                    ServiceLevelObjective.build("api.error.ratio")
                            .failedMessage("API error ratio")
                            .baseUnit(BaseUnits.PERCENT)
                            .tag("uri.matches", "/api/**")
                            .tag("error.outcome", "SERVER_ERROR")
                            .errorRatio(
                                    s -> s.name("http.server.requests").tag("uri", uri -> uri.startsWith("/api")),
                                    all -> all.tag("outcome", "SERVER_ERROR")
                            ).isLessThan(0.01)
            )
            .build();

    for (ServiceLevelObjective slo : registry.getServiceLevelObjectives()) {
        applicationContext.registerBean(
                camelCasedHealthIndicatorNames.name(slo.getName(), Type.GAUGE),
                HealthContributor.class,
                () -> toHealthContributor(registry, slo)
        );
    }

    return registry;
}
 
Example #15
Source File: JettySslHandshakeMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void handshakeSucceeded(Event event) {
    SSLSession session = event.getSSLEngine().getSession();
    Counter.builder(METER_NAME)
            .baseUnit(BaseUnits.EVENTS)
            .description(DESCRIPTION)
            .tag(TAG_RESULT, "succeeded")
            .tag(TAG_PROTOCOL, session.getProtocol())
            .tag(TAG_CIPHER_SUITE, session.getCipherSuite())
            .tags(tags)
            .register(registry)
            .increment();
}
 
Example #16
Source File: CountedRejectedExecutionHandler.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public CountedRejectedExecutionHandler(
    RejectedExecutionHandler delegate, MeterRegistry registry, String name, Iterable<Tag> tags) {
  this.delegate = delegate;
  this.counter =
      Counter.builder("executor.rejected")
          .tags(Tags.concat(tags, "name", name))
          .description("The number of tasks not accepted for execution")
          .baseUnit(BaseUnits.TASKS)
          .register(registry);
}
 
Example #17
Source File: JettySslHandshakeMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public JettySslHandshakeMetrics(MeterRegistry registry, Iterable<Tag> tags) {
    this.registry = registry;
    this.tags = tags;

    this.handshakesFailed = Counter.builder(METER_NAME)
            .baseUnit(BaseUnits.EVENTS)
            .description(DESCRIPTION)
            .tag(TAG_RESULT, "failed")
            .tag(TAG_PROTOCOL, TAG_VALUE_UNKNOWN)
            .tag(TAG_CIPHER_SUITE, TAG_VALUE_UNKNOWN)
            .tags(tags)
            .register(registry);
}
 
Example #18
Source File: JettyStatisticsMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    bindTimer(registry, "jetty.requests", "Request duration", StatisticsHandler::getRequests, StatisticsHandler::getRequestTimeTotal);
    bindTimer(registry, "jetty.dispatched", "Dispatch duration", StatisticsHandler::getDispatched, StatisticsHandler::getDispatchedTimeTotal);

    bindCounter(registry, "jetty.async.requests", "Total number of async requests", StatisticsHandler::getAsyncRequests);
    bindCounter(registry, "jetty.async.dispatches", "Total number of requests that have been asynchronously dispatched", StatisticsHandler::getAsyncDispatches);
    bindCounter(registry, "jetty.async.expires", "Total number of async requests that have expired", StatisticsHandler::getExpires);
    FunctionCounter.builder("jetty.responses.size", statisticsHandler, StatisticsHandler::getResponsesBytesTotal)
        .description("Total number of bytes across all responses")
        .baseUnit(BaseUnits.BYTES)
        .tags(tags)
        .register(registry);

    bindGauge(registry, "jetty.requests.active", "Number of requests currently active", StatisticsHandler::getRequestsActive);
    bindGauge(registry, "jetty.dispatched.active", "Number of dispatches currently active", StatisticsHandler::getDispatchedActive);
    bindGauge(registry, "jetty.dispatched.active.max", "Maximum number of active dispatches being handled", StatisticsHandler::getDispatchedActiveMax);

    bindTimeGauge(registry, "jetty.dispatched.time.max", "Maximum time spent in dispatch handling", StatisticsHandler::getDispatchedTimeMax);

    bindGauge(registry, "jetty.async.requests.waiting", "Currently waiting async requests", StatisticsHandler::getAsyncRequestsWaiting);
    bindGauge(registry, "jetty.async.requests.waiting.max", "Maximum number of waiting async requests", StatisticsHandler::getAsyncRequestsWaitingMax);

    bindTimeGauge(registry, "jetty.request.time.max", "Maximum time spent handling requests", StatisticsHandler::getRequestTimeMax);
    bindTimeGauge(registry, "jetty.stats", "Time stats have been collected for", StatisticsHandler::getStatsOnMs);

    bindStatusCounters(registry);
}
 
Example #19
Source File: OkHttpConnectionPoolMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void bindTo(@NonNull MeterRegistry registry) {
    String connectionCountName = namePrefix + ".connection.count";
    Gauge.builder(connectionCountName, connectionStats,
            cs -> {
                if (cs.get() == null) {
                    cs.set(new ConnectionPoolConnectionStats());
                }
                return cs.get().getActiveCount();
            })
            .baseUnit(BaseUnits.CONNECTIONS)
            .description("The state of connections in the OkHttp connection pool")
            .tags(Tags.of(tags).and(TAG_STATE, "active"))
            .register(registry);

    Gauge.builder(connectionCountName, connectionStats,
            cs -> {
                if (cs.get() == null) {
                    cs.set(new ConnectionPoolConnectionStats());
                }
                return cs.get().getIdleConnectionCount();
            })
            .baseUnit(BaseUnits.CONNECTIONS)
            .description("The state of connections in the OkHttp connection pool")
            .tags(Tags.of(tags).and(TAG_STATE, "idle"))
            .register(registry);

    if (this.maxIdleConnectionCount != null) {
        Gauge.builder(namePrefix + ".connection.limit", () -> this.maxIdleConnectionCount)
                .baseUnit(BaseUnits.CONNECTIONS)
                .description("The maximum idle connection count in an OkHttp connection pool.")
                .tags(Tags.concat(tags))
                .register(registry);
    }
}
 
Example #20
Source File: HazelcastCacheMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
protected void bindImplementationSpecificMetrics(MeterRegistry registry) {
    Gauge.builder("cache.entries", cache, cache -> cache.getLocalMapStats().getBackupEntryCount())
            .tags(getTagsWithCacheName()).tag("ownership", "backup")
            .description("The number of backup entries held by this member")
            .register(registry);

    Gauge.builder("cache.entries", cache, cache -> cache.getLocalMapStats().getOwnedEntryCount())
            .tags(getTagsWithCacheName()).tag("ownership", "owned")
            .description("The number of owned entries held by this member")
            .register(registry);

    Gauge.builder("cache.entry.memory", cache, cache -> cache.getLocalMapStats().getBackupEntryMemoryCost())
            .tags(getTagsWithCacheName()).tag("ownership", "backup")
            .description("Memory cost of backup entries held by this member")
            .baseUnit(BaseUnits.BYTES)
            .register(registry);

    Gauge.builder("cache.entry.memory", cache, cache -> cache.getLocalMapStats().getOwnedEntryMemoryCost())
            .tags(getTagsWithCacheName()).tag("ownership", "owned")
            .description("Memory cost of owned entries held by this member")
            .baseUnit(BaseUnits.BYTES)
            .register(registry);

    FunctionCounter.builder("cache.partition.gets", cache, cache -> cache.getLocalMapStats().getGetOperationCount())
            .tags(getTagsWithCacheName())
            .description("The total number of get operations executed against this partition")
            .register(registry);

    timings(registry);
    nearCacheMetrics(registry);
}
 
Example #21
Source File: LoggingMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
String humanReadableBaseUnit(double value) {
    String baseUnit = meter.getId().getBaseUnit();
    if (BaseUnits.BYTES.equals(baseUnit)) {
        return humanReadableByteCount(value);
    }
    return decimalOrNan(value) + (baseUnit != null ? " " + baseUnit : "");
}
 
Example #22
Source File: JvmCompilationMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    CompilationMXBean compilationBean = ManagementFactory.getCompilationMXBean();
    if (compilationBean != null && compilationBean.isCompilationTimeMonitoringSupported()) {
        FunctionCounter.builder("jvm.compilation.time", compilationBean, CompilationMXBean::getTotalCompilationTime)
                .tags(Tags.concat(tags, "compiler", compilationBean.getName()))
                .description("The approximate accumulated elapsed time spent in compilation")
                .baseUnit(BaseUnits.MILLISECONDS)
                .register(registry);
    }
}
 
Example #23
Source File: TomcatMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private void registerGlobalRequestMetrics(MeterRegistry registry) {
    registerMetricsEventually("type", "GlobalRequestProcessor", (name, allTags) -> {
        FunctionCounter.builder("tomcat.global.sent", mBeanServer,
            s -> safeDouble(() -> s.getAttribute(name, "bytesSent")))
            .tags(allTags)
            .baseUnit(BaseUnits.BYTES)
            .register(registry);

        FunctionCounter.builder("tomcat.global.received", mBeanServer,
            s -> safeDouble(() -> s.getAttribute(name, "bytesReceived")))
            .tags(allTags)
            .baseUnit(BaseUnits.BYTES)
            .register(registry);

        FunctionCounter.builder("tomcat.global.error", mBeanServer,
                s -> safeDouble(() -> s.getAttribute(name, "errorCount")))
                .tags(allTags)
                .register(registry);

        FunctionTimer.builder("tomcat.global.request", mBeanServer,
                s -> safeLong(() -> s.getAttribute(name, "requestCount")),
                s -> safeDouble(() -> s.getAttribute(name, "processingTime")), TimeUnit.MILLISECONDS)
                .tags(allTags)
                .register(registry);

        TimeGauge.builder("tomcat.global.request.max", mBeanServer, TimeUnit.MILLISECONDS,
                s -> safeDouble(() -> s.getAttribute(name, "maxTime")))
                .tags(allTags)
                .register(registry);
    });
}
 
Example #24
Source File: TomcatMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private void registerSessionMetrics(MeterRegistry registry) {
    if (manager == null) {
        // If the binder is created but unable to find the session manager don't register those metrics
        return;
    }

    Gauge.builder("tomcat.sessions.active.max", manager, Manager::getMaxActive)
            .tags(tags)
            .baseUnit(BaseUnits.SESSIONS)
            .register(registry);

    Gauge.builder("tomcat.sessions.active.current", manager, Manager::getActiveSessions)
            .tags(tags)
            .baseUnit(BaseUnits.SESSIONS)
            .register(registry);

    FunctionCounter.builder("tomcat.sessions.created", manager, Manager::getSessionCounter)
            .tags(tags)
            .baseUnit(BaseUnits.SESSIONS)
            .register(registry);

    FunctionCounter.builder("tomcat.sessions.expired", manager, Manager::getExpiredSessions)
            .tags(tags)
            .baseUnit(BaseUnits.SESSIONS)
            .register(registry);

    FunctionCounter.builder("tomcat.sessions.rejected", manager, Manager::getRejectedSessions)
            .tags(tags)
            .baseUnit(BaseUnits.SESSIONS)
            .register(registry);

    TimeGauge.builder("tomcat.sessions.alive.max", manager, TimeUnit.SECONDS, Manager::getSessionMaxAliveTime)
            .tags(tags)
            .register(registry);
}
 
Example #25
Source File: JvmThreadMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

    Gauge.builder("jvm.threads.peak", threadBean, ThreadMXBean::getPeakThreadCount)
            .tags(tags)
            .description("The peak live thread count since the Java virtual machine started or peak was reset")
            .baseUnit(BaseUnits.THREADS)
            .register(registry);

    Gauge.builder("jvm.threads.daemon", threadBean, ThreadMXBean::getDaemonThreadCount)
            .tags(tags)
            .description("The current number of live daemon threads")
            .baseUnit(BaseUnits.THREADS)
            .register(registry);

    Gauge.builder("jvm.threads.live", threadBean, ThreadMXBean::getThreadCount)
            .tags(tags)
            .description("The current number of live threads including both daemon and non-daemon threads")
            .baseUnit(BaseUnits.THREADS)
            .register(registry);

    try {
        threadBean.getAllThreadIds();
        for (Thread.State state : Thread.State.values()) {
            Gauge.builder("jvm.threads.states", threadBean, (bean) -> getThreadStateCount(bean, state))
                    .tags(Tags.concat(tags, "state", getStateTagValue(state)))
                    .description("The current number of threads having " + state + " state")
                    .baseUnit(BaseUnits.THREADS)
                    .register(registry);
        }
    } catch (Error error) {
        // An error will be thrown for unsupported operations
        // e.g. SubstrateVM does not support getAllThreadIds
    }
}
 
Example #26
Source File: LogbackMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
MetricsTurboFilter(MeterRegistry registry, Iterable<Tag> tags) {
    errorCounter = Counter.builder("logback.events")
            .tags(tags).tags("level", "error")
            .description("Number of error level events that made it to the logs")
            .baseUnit(BaseUnits.EVENTS)
            .register(registry);

    warnCounter = Counter.builder("logback.events")
            .tags(tags).tags("level", "warn")
            .description("Number of warn level events that made it to the logs")
            .baseUnit(BaseUnits.EVENTS)
            .register(registry);

    infoCounter = Counter.builder("logback.events")
            .tags(tags).tags("level", "info")
            .description("Number of info level events that made it to the logs")
            .baseUnit(BaseUnits.EVENTS)
            .register(registry);

    debugCounter = Counter.builder("logback.events")
            .tags(tags).tags("level", "debug")
            .description("Number of debug level events that made it to the logs")
            .baseUnit(BaseUnits.EVENTS)
            .register(registry);

    traceCounter = Counter.builder("logback.events")
            .tags(tags).tags("level", "trace")
            .description("Number of trace level events that made it to the logs")
            .baseUnit(BaseUnits.EVENTS)
            .register(registry);
}
 
Example #27
Source File: CommonsObjectPool2Metrics.java    From micrometer with Apache License 2.0 4 votes vote down vote up
@Override
public void bindTo(@NonNull MeterRegistry registry) {
    for (String type : TYPES) {
        registerMetricsEventually(
                type,
                (o, tags) -> {
                    registerGaugeForObject(registry, o,
                            "NumIdle", "num.idle", tags,
                            "The number of instances currently idle in this pool", BaseUnits.OBJECTS);
                    registerGaugeForObject(registry, o,
                            "NumWaiters", "num.waiters", tags,
                            "The estimate of the number of threads currently blocked waiting for an object from the pool",
                            BaseUnits.THREADS);

                    registerFunctionCounterForObject(registry, o,
                            "CreatedCount", "created", tags,
                            "The total number of objects created for this pool over the lifetime of the pool",
                            BaseUnits.OBJECTS);
                    registerFunctionCounterForObject(registry, o,
                            "BorrowedCount", "borrowed", tags,
                            "The total number of objects successfully borrowed from this pool over the lifetime of the pool",
                            BaseUnits.OBJECTS);
                    registerFunctionCounterForObject(registry, o,
                            "ReturnedCount", "returned", tags,
                            "The total number of objects returned to this pool over the lifetime of the pool",
                            BaseUnits.OBJECTS);
                    registerFunctionCounterForObject(registry, o,
                            "DestroyedCount", "destroyed", tags,
                            "The total number of objects destroyed by this pool over the lifetime of the pool",
                            BaseUnits.OBJECTS);
                    registerFunctionCounterForObject(registry, o,
                            "DestroyedByEvictorCount", "destroyed.by.evictor", tags,
                            "The total number of objects destroyed by the evictor associated with this pool over the lifetime of the pool",
                            BaseUnits.OBJECTS);
                    registerFunctionCounterForObject(registry, o,
                            "DestroyedByBorrowValidationCount", "destroyed.by.borrow.validation", tags,
                            "The total number of objects destroyed by this pool as a result of failing validation during borrowObject() over the lifetime of the pool",
                            BaseUnits.OBJECTS);

                    registerTimeGaugeForObject(registry, o,
                            "MaxBorrowWaitTimeMillis", "max.borrow.wait", tags,
                            "The maximum time a thread has waited to borrow objects from the pool");
                    registerTimeGaugeForObject(registry, o,
                            "MeanActiveTimeMillis", "mean.active", tags,
                            "The mean time objects are active");
                    registerTimeGaugeForObject(registry, o,
                            "MeanIdleTimeMillis", "mean.idle", tags,
                            "The mean time objects are idle");
                    registerTimeGaugeForObject(registry, o,
                            "MeanBorrowWaitTimeMillis", "mean.borrow.wait", tags,
                            "The mean time threads wait to borrow an object");
                });
    }
}
 
Example #28
Source File: SofaRpcMetrics.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    Gauge.builder("sofa.threadpool.config.core", () -> Optional.of(serverConfig)
        .map(AtomicReference::get)
        .map(ServerConfig::getCoreThreads)
        .orElse(0))
        .tags(common)
        .baseUnit(BaseUnits.THREADS)
        .register(registry);
    Gauge.builder("sofa.threadpool.config.max", () -> Optional.of(serverConfig)
        .map(AtomicReference::get)
        .map(ServerConfig::getMaxThreads)
        .orElse(0))
        .tags(common)
        .baseUnit(BaseUnits.THREADS)
        .register(registry);
    Gauge.builder("sofa.threadpool.config.queue", () -> Optional.of(serverConfig)
        .map(AtomicReference::get)
        .map(ServerConfig::getQueues)
        .orElse(0))
        .tags(common)
        .baseUnit(BaseUnits.TASKS)
        .register(registry);
    Gauge.builder("sofa.threadpool.active", () -> Optional.of(executor)
        .map(AtomicReference::get)
        .map(ThreadPoolExecutor::getActiveCount)
        .orElse(0))
        .tags(common)
        .baseUnit(BaseUnits.THREADS)
        .register(registry);
    Gauge.builder("sofa.threadpool.idle", () -> Optional.of(executor)
        .map(AtomicReference::get)
        .map(e -> e.getPoolSize() - e.getActiveCount())
        .orElse(0))
        .tags(common)
        .baseUnit(BaseUnits.THREADS)
        .register(registry);
    Gauge.builder("sofa.threadpool.queue.size", () -> Optional.of(executor)
        .map(AtomicReference::get)
        .map(ThreadPoolExecutor::getQueue)
        .map(Collection::size)
        .orElse(0))
        .tags(common)
        .baseUnit(BaseUnits.TASKS)
        .register(registry);
    provider = Counter.builder("sofa.provider")
        .tags(common)
        .register(registry);
    consumer = Counter.builder("sofa.consumer")
        .tags(common)
        .register(registry);

    initialed.set(registry);
}
 
Example #29
Source File: PrometheusMeterRegistryTest.java    From micrometer with Apache License 2.0 4 votes vote down vote up
@Test
void baseUnitMakesItToScrape() {
    AtomicInteger n = new AtomicInteger(0);
    Gauge.builder("gauge", n, AtomicInteger::get).tags("a", "b").baseUnit(BaseUnits.BYTES).register(registry);
    assertThat(registry.scrape()).contains("gauge_bytes");
}
 
Example #30
Source File: PrometheusNamingConventionTest.java    From micrometer with Apache License 2.0 4 votes vote down vote up
@Test
void unitsAreAppendedToGauges() {
    assertThat(convention.name("response.size", Meter.Type.GAUGE, BaseUnits.BYTES)).isEqualTo("response_size_bytes");
    assertThat(convention.name("gauge", Meter.Type.GAUGE)).isEqualTo("gauge");
}