Intro to Dropwizard Metrics – Dropwizard指标介绍

最后修改: 2017年 1月 29日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

Metrics is a Java library which provides measuring instruments for Java applications.

Metrics是一个Java库,为Java应用程序提供测量工具。

It has several modules, and in this article, we will elaborate metrics-core module, metrics-healthchecks module, metrics-servlets module, and metrics-servlet module, and sketch out the rest, for your reference.

它有几个模块,在这篇文章中,我们将阐述metrics-core模块、metrics-healthchecks模块、metrics-servlets模块和metrics-servlet模块,并勾画出其他模块,供大家参考。

2. Module metrics-core

2.模块metrics-core

2.1. Maven Dependencies

2.1.Maven的依赖性

To use the metrics-core module, there’s only one dependency required which needs to be added to the pom.xml file:

要使用metrics-core模块,只需要在pom.xml文件中添加一个依赖项。

<dependency>
    <groupId>io.dropwizard.metrics</groupId>
    <artifactId>metrics-core</artifactId>
    <version>3.1.2</version>
</dependency>

And you can find its latest version here.

而你可以在这里找到其最新版本

2.2. MetricRegistry

2.2.MetricRegistry

Simply put, we’ll use the MetricRegistry class to register one or several metrics.

简单地说,我们将使用MetricRegistry类来注册一个或几个度量。

We can use one metrics registry for all of our metrics, but if we want to use different reporting methods for different metrics, we can also divide our metrics into groups and use different metrics registries for each group.

我们可以对所有的指标使用一个指标注册表,但是如果我们想对不同的指标使用不同的报告方法,我们也可以把我们的指标分成几组,对每组使用不同的指标注册表。

Let’s create a MetricRegistry now:

现在让我们创建一个MetricRegistry

MetricRegistry metricRegistry = new MetricRegistry();

And then we can register some metrics with this MetricRegistry:

然后我们可以用这个MetricRegistry注册一些度量。

Meter meter1 = new Meter();
metricRegistry.register("meter1", meter1);

Meter meter2 = metricRegistry.meter("meter2");

There are two basic ways of creating a new metric: instantiating one yourself or obtaining one from the metric registry. As you can see, we used both of them in the example above, we are instantiating the Meter object “meter1” and we are getting another Meter object “meter2” which is created by the metricRegistry.

有两种创建新度量衡的基本方法:自己实例化或从度量衡注册表中获取。正如你所看到的,我们在上面的例子中同时使用了这两种方式,我们正在实例化Meter对象 “meter1″,并且我们正在获得另一个Meter对象 “meter2″,它是由metricRegistry创建的。

In a metric registry, every metric has a unique name, as we used “meter1” and “meter2” as metric names above. MetricRegistry also provides a set of static helper methods to help us create proper metric names:

在度量衡注册表中,每个度量衡都有一个唯一的名字,正如我们在上面使用 “meter1 “和 “meter2 “作为度量衡名称。MetricRegistry还提供了一组静态帮助方法,以帮助我们创建合适的度量衡名称。

String name1 = MetricRegistry.name(Filter.class, "request", "count");
String name2 = MetricRegistry.name("CustomFilter", "response", "count");

If we need to manage a set of metric registries, we can use SharedMetricRegistries class, which is a singleton and thread-safe. We can add a metric register into it, retrieve this metric register from it, and remove it:

如果我们需要管理一组度量衡注册表,我们可以使用SharedMetricRegistries类,它是一个单子和线程安全的。我们可以在其中添加一个度量衡注册表,从其中检索这个度量衡注册表,并删除它。

SharedMetricRegistries.add("default", metricRegistry);
MetricRegistry retrievedMetricRegistry = SharedMetricRegistries.getOrCreate("default");
SharedMetricRegistries.remove("default");

3. Metrics Concepts

3.度量衡的概念

The metrics-core module provides several commonly used metric types: Meter, Gauge, Counter, Histogram and Timer, and Reporter to output metrics’ values.

Metrics-core模块提供了几种常用的度量衡类型。Meter, Gauge, Counter, HistogramTimer,以及Reporter来输出度量的值

3.1. Meter

3.1.

A Meter measures event occurrences count and rate:

一个Meter测量事件发生的数量和速率。

Meter meter = new Meter();
long initCount = meter.getCount();
assertThat(initCount, equalTo(0L));

meter.mark();
assertThat(meter.getCount(), equalTo(1L));

meter.mark(20);
assertThat(meter.getCount(), equalTo(21L));

double meanRate = meter.getMeanRate();
double oneMinRate = meter.getOneMinuteRate();
double fiveMinRate = meter.getFiveMinuteRate();
double fifteenMinRate = meter.getFifteenMinuteRate(); 

The getCount() method returns event occurrences count, and mark() method adds 1 or n to the event occurrences count. The Meter object provides four rates which represent average rates for the whole Meter lifetime, for the recent one minute, for the recent five minutes and for the recent quarter, respectively.

getCount()方法返回事件发生数,mark()方法在事件发生数上添加1或n。Meter对象提供了四个速率,分别代表整个Meter生命周期、最近一分钟、最近五分钟和最近一个季度的平均速率。

3.2. Gauge

3.2.测量仪

Gauge is an interface which is simply used to return a particular value. The metrics-core module provides several implementations of it: RatioGauge, CachedGauge, DerivativeGauge and JmxAttributeGauge.

Gauge是一个接口,它只是用来返回一个特定的值。metrics-core模块提供了它的几个实现。RatioGaugeCachedGaugeDerivativeGauge以及JmxAttributeGauge

RatioGauge is an abstract class and it measures the ratio of one value to another.

RatioGauge是一个抽象的类,它测量一个值与另一个值的比率。

Let’s see how to use it. First, we implement a class AttendanceRatioGauge:

让我们看看如何使用它。首先,我们实现一个AttendanceRatioGauge类。

public class AttendanceRatioGauge extends RatioGauge {
    private int attendanceCount;
    private int courseCount;

    @Override
    protected Ratio getRatio() {
        return Ratio.of(attendanceCount, courseCount);
    }
    
    // standard constructors
}

And then we test it:

然后我们测试它。

RatioGauge ratioGauge = new AttendanceRatioGauge(15, 20);

assertThat(ratioGauge.getValue(), equalTo(0.75));

CachedGauge is another abstract class which can cache value, therefore, it is quite useful when the values are expensive to calculate. To use it, we need to implement a class ActiveUsersGauge:

CachedGauge是另一个可以缓存数值的抽象类,因此,当数值的计算很昂贵时,它是相当有用的。为了使用它,我们需要实现一个ActiveUsersGauge类。

public class ActiveUsersGauge extends CachedGauge<List<Long>> {
    
    @Override
    protected List<Long> loadValue() {
        return getActiveUserCount();
    }
 
    private List<Long> getActiveUserCount() {
        List<Long> result = new ArrayList<Long>();
        result.add(12L);
        return result;
    }

    // standard constructors
}

Then we test it to see if it works as expected:

然后我们测试它,看它是否按预期工作。

Gauge<List<Long>> activeUsersGauge = new ActiveUsersGauge(15, TimeUnit.MINUTES);
List<Long> expected = new ArrayList<>();
expected.add(12L);

assertThat(activeUsersGauge.getValue(), equalTo(expected));

We set the cache’s expiration time to 15 minutes when instantiating the ActiveUsersGauge.

我们在实例化ActiveUsersGauge时将缓存的过期时间设置为15分钟。

DerivativeGauge is also an abstract class and it allows you to derive a value from other Gauge as its value.

DerivativeGauge也是一个抽象类,它允许你从其他Gauge中派生出一个值作为其值。

Let’s look at an example:

我们来看看一个例子。

public class ActiveUserCountGauge extends DerivativeGauge<List<Long>, Integer> {
    
    @Override
    protected Integer transform(List<Long> value) {
        return value.size();
    }

    // standard constructors
}

This Gauge derives its value from an ActiveUsersGauge, so we expect it to be the value from the base list’s size:

这个Gauge的值来自ActiveUsersGauge,所以我们希望它是来自基本列表的大小的值。

Gauge<List<Long>> activeUsersGauge = new ActiveUsersGauge(15, TimeUnit.MINUTES);
Gauge<Integer> activeUserCountGauge = new ActiveUserCountGauge(activeUsersGauge);

assertThat(activeUserCountGauge.getValue(), equalTo(1));

JmxAttributeGauge is used when we need to access other libraries’ metrics exposed via JMX.

JmxAttributeGauge在我们需要访问其他库通过JMX暴露的度量时使用。

3.3. Counter

3.3.计数器

The Counter is used for recording incrementations and decrementations:

计数器用于记录增量和减量。

Counter counter = new Counter();
long initCount = counter.getCount();
assertThat(initCount, equalTo(0L));

counter.inc();
assertThat(counter.getCount(), equalTo(1L));

counter.inc(11);
assertThat(counter.getCount(), equalTo(12L));

counter.dec();
assertThat(counter.getCount(), equalTo(11L));

counter.dec(6);
assertThat(counter.getCount(), equalTo(5L));

3.4. Histogram

3.4.直方图

Histogram is used for keeping track of a stream of Long values and it analyzes their statistical characteristics such as max, min, mean, median, standard deviation, 75th percentile and so on:

直方图用于跟踪值流,它分析它们的统计特征,如最大、最小、平均数、中位数、标准差、第75百分位数等。

Histogram histogram = new Histogram(new UniformReservoir());
histogram.update(5);
long count1 = histogram.getCount();
assertThat(count1, equalTo(1L));

Snapshot snapshot1 = histogram.getSnapshot();
assertThat(snapshot1.getValues().length, equalTo(1));
assertThat(snapshot1.getValues()[0], equalTo(5L));

histogram.update(20);
long count2 = histogram.getCount();
assertThat(count2, equalTo(2L));

Snapshot snapshot2 = histogram.getSnapshot();
assertThat(snapshot2.getValues().length, equalTo(2));
assertThat(snapshot2.getValues()[1], equalTo(20L));
assertThat(snapshot2.getMax(), equalTo(20L));
assertThat(snapshot2.getMean(), equalTo(12.5));
assertEquals(10.6, snapshot2.getStdDev(), 0.1);
assertThat(snapshot2.get75thPercentile(), equalTo(20.0));
assertThat(snapshot2.get999thPercentile(), equalTo(20.0));

Histogram samples the data by using reservoir sampling, and when we instantiate a Histogram object, we need to set its reservoir explicitly.

Histogram通过使用蓄水池采样对数据进行采样,当我们实例化一个Histogram对象时,我们需要明确设置其蓄水池。

Reservoir is an interface and metrics-core provides four implementations of them: ExponentiallyDecayingReservoir, UniformReservoir, SlidingTimeWindowReservoir, SlidingWindowReservoir.

Reservoir是一个接口,metrics-core提供了它们的四个实现。ExponentiallyDecayingReservoir, UniformReservoir, SlidingTimeWindowReservoir, SlidingWindowReservoir

In the section above, we mentioned that a metric can also be created by MetricRegistry, besides using a constructor. When we use metricRegistry.histogram(), it returns a Histogram instance with ExponentiallyDecayingReservoir implementation.

在上面的章节中,我们提到除了使用构造函数之外,MetricRegistry也可以创建一个度量衡。当我们使用metricRegistry.histogram()时,它会返回一个具有ExponentiallyDecayingReservoir实现的Histogram实例。

3.5. Timer

3.5.定时器

Timer is used for keeping track of multiple timing durations which are represented by Context objects, and it also provides their statistical data:

Timer用于跟踪由Context对象表示的多个定时持续时间,它还提供它们的统计数据。

Timer timer = new Timer();
Timer.Context context1 = timer.time();
TimeUnit.SECONDS.sleep(5);
long elapsed1 = context1.stop();

assertEquals(5000000000L, elapsed1, 1000000);
assertThat(timer.getCount(), equalTo(1L));
assertEquals(0.2, timer.getMeanRate(), 0.1);

Timer.Context context2 = timer.time();
TimeUnit.SECONDS.sleep(2);
context2.close();

assertThat(timer.getCount(), equalTo(2L));
assertEquals(0.3, timer.getMeanRate(), 0.1);

3.6. Reporter

3.6.报告人

When we need to output our measurements, we can use Reporter. This is an interface, and the metrics-core module provides several implementations of it, such as ConsoleReporter, CsvReporter, Slf4jReporter, JmxReporter and so on.

当我们需要输出我们的测量结果时,我们可以使用Reporter。这是一个接口,metrics-core模块提供了它的几个实现,如ConsoleReporterCsvReporterSlf4jReporterJmxReporter等等。

Here we use ConsoleReporter as an example:

这里我们用ConsoleReporter作为一个例子。

MetricRegistry metricRegistry = new MetricRegistry();

Meter meter = metricRegistry.meter("meter");
meter.mark();
meter.mark(200);
Histogram histogram = metricRegistry.histogram("histogram");
histogram.update(12);
histogram.update(17);
Counter counter = metricRegistry.counter("counter");
counter.inc();
counter.dec();

ConsoleReporter reporter = ConsoleReporter.forRegistry(metricRegistry).build();
reporter.start(5, TimeUnit.MICROSECONDS);
reporter.report();

Here is the sample output of the ConsoleReporter:

下面是ConsoleReporter的输出样本:

-- Histograms ------------------------------------------------------------------
histogram
count = 2
min = 12
max = 17
mean = 14.50
stddev = 2.50
median = 17.00
75% <= 17.00
95% <= 17.00
98% <= 17.00
99% <= 17.00
99.9% <= 17.00

-- Meters ----------------------------------------------------------------------
meter
count = 201
mean rate = 1756.87 events/second
1-minute rate = 0.00 events/second
5-minute rate = 0.00 events/second
15-minute rate = 0.00 events/second

4. Module metrics-healthchecks

4.模块metrics-healthchecks

Metrics has an extension metrics-healthchecks module for dealing with health checks.

Metrics有一个扩展的metrics-healthchecks模块,用于处理健康检查问题。

4.1. Maven Dependencies

4.1.Maven的依赖性

To use the metrics-healthchecks module, we need to add this dependency to the pom.xml file:

为了使用metrics-healthchecks模块,我们需要在pom.xml文件中添加这个依赖关系。

<dependency>
    <groupId>io.dropwizard.metrics</groupId>
    <artifactId>metrics-healthchecks</artifactId>
    <version>3.1.2</version>
</dependency>

And you can find its latest version here.

而你可以在这里找到其最新版本

4.2. Usage

4.2.使用方法

First, we need several classes which are responsible for specific health check operations, and these classes must implement HealthCheck.

首先,我们需要几个负责特定健康检查操作的类,这些类必须实现HealthCheck

For example, we use DatabaseHealthCheck and UserCenterHealthCheck:

例如,我们使用DatabaseHealthCheckUserCenterHealthCheck

public class DatabaseHealthCheck extends HealthCheck {
 
    @Override
    protected Result check() throws Exception {
        return Result.healthy();
    }
}
public class UserCenterHealthCheck extends HealthCheck {
 
    @Override
    protected Result check() throws Exception {
        return Result.healthy();
    }
}

Then, we need a HealthCheckRegistry (which is just like MetricRegistry), and register the DatabaseHealthCheck and UserCenterHealthCheck with it:

然后,我们需要一个HealthCheckRegistry(它就像MetricRegistry),并向它注册DatabaseHealthCheckUserCenterHealthCheck

HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();
healthCheckRegistry.register("db", new DatabaseHealthCheck());
healthCheckRegistry.register("uc", new UserCenterHealthCheck());

assertThat(healthCheckRegistry.getNames().size(), equalTo(2));

We can also unregister the HealthCheck:

我们还可以取消对HealthCheck的注册。

healthCheckRegistry.unregister("uc");
 
assertThat(healthCheckRegistry.getNames().size(), equalTo(1));

We can run all the HealthCheck instances:

我们可以运行所有的HealthCheck实例。

Map<String, HealthCheck.Result> results = healthCheckRegistry.runHealthChecks();
for (Map.Entry<String, HealthCheck.Result> entry : results.entrySet()) {
    assertThat(entry.getValue().isHealthy(), equalTo(true));
}

Finally, we can run a specific HealthCheck instance:

最后,我们可以运行一个特定的HealthCheck实例。

healthCheckRegistry.runHealthCheck("db");

5. Module metrics-servlets

5.模块metrics-servlets

Metrics provides us a handful of useful servlets which allow us to access metrics related data through HTTP requests.

Metrics为我们提供了一些有用的servlet,使我们能够通过HTTP请求访问与度量衡有关的数据。

5.1. Maven Dependencies

5.1.Maven的依赖性

To use the metrics-servlets module, we need to add this dependency to the pom.xml file:

为了使用metrics-servlets模块,我们需要在pom.xml文件中添加这个依赖关系。

<dependency>
    <groupId>io.dropwizard.metrics</groupId>
    <artifactId>metrics-servlets</artifactId>
    <version>3.1.2</version>
</dependency>

And you can find its latest version here.

而你可以在这里找到其最新版本

5.2. HealthCheckServlet Usage

5.2.HealthCheckServlet用法

HealthCheckServlet provides health check results. First, we need to create a ServletContextListener which exposes our HealthCheckRegistry:

HealthCheckServlet提供健康检查结果。首先,我们需要创建一个ServletContextListener,它可以暴露我们的HealthCheckRegistry

public class MyHealthCheckServletContextListener
  extends HealthCheckServlet.ContextListener {
 
    public static HealthCheckRegistry HEALTH_CHECK_REGISTRY
      = new HealthCheckRegistry();

    static {
        HEALTH_CHECK_REGISTRY.register("db", new DatabaseHealthCheck());
    }

    @Override
    protected HealthCheckRegistry getHealthCheckRegistry() {
        return HEALTH_CHECK_REGISTRY;
    }
}

Then, we add both this listener and HealthCheckServlet into the web.xml file:

然后,我们把这个监听器和HealthCheckServlet加入web.xml文件。

<listener>
    <listener-class>com.baeldung.metrics.servlets.MyHealthCheckServletContextListener</listener-class>
</listener>
<servlet>
    <servlet-name>healthCheck</servlet-name>
    <servlet-class>com.codahale.metrics.servlets.HealthCheckServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>healthCheck</servlet-name>
    <url-pattern>/healthcheck</url-pattern>
</servlet-mapping>

Now we can start the web application, and send a GET request to “http://localhost:8080/healthcheck” to get health check results. Its response should be like this:

现在我们可以启动Web应用程序,向 “http://localhost:8080/healthcheck “发送一个GET请求,以获得健康检查结果。它的响应应该是这样的。

{
  "db": {
    "healthy": true
  }
}

5.3. ThreadDumpServlet Usage

5.3.ThreadDumpServlet使用

ThreadDumpServlet provides information about all live threads in the JVM, their states, their stack traces, and the state of any locks they may be waiting for.
If we want to use it, we simply need to add these into the web.xml file:

ThreadDumpServlet提供了关于JVM中所有实时线程的信息,它们的状态,它们的堆栈跟踪,以及它们可能正在等待的任何锁的状态。
如果我们想使用它,我们只需要将这些添加到web.xml文件中。

<servlet>
    <servlet-name>threadDump</servlet-name>
    <servlet-class>com.codahale.metrics.servlets.ThreadDumpServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>threadDump</servlet-name>
    <url-pattern>/threaddump</url-pattern>
</servlet-mapping>

Thread dump data will be available at “http://localhost:8080/threaddump”.

线程转储数据将在 “http://localhost:8080/threaddump “提供。

5.4. PingServlet Usage

5.4.PingServlet使用

PingServlet can be used to test if the application is running. We add these into the web.xml file:

PingServlet可以用来测试应用程序是否正在运行。我们将这些添加到web.xml文件中。

<servlet>
    <servlet-name>ping</servlet-name>
    <servlet-class>com.codahale.metrics.servlets.PingServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ping</servlet-name>
    <url-pattern>/ping</url-pattern>
</servlet-mapping>

And then send a GET request to “http://localhost:8080/ping”. The response’s status code is 200 and its content is “pong”.

然后向 “http://localhost:8080/ping “发送一个GET请求。响应的状态代码是200,其内容是 “pong”。

5.5. MetricsServlet Usage

5.5.MetricsServlet使用

MetricsServlet provides metrics data. First, we need to create a ServletContextListener which exposes our MetricRegistry:

MetricsServlet提供指标数据。首先,我们需要创建一个ServletContextListener,它可以暴露我们的MetricRegistry

public class MyMetricsServletContextListener
  extends MetricsServlet.ContextListener {
    private static MetricRegistry METRIC_REGISTRY
     = new MetricRegistry();

    static {
        Counter counter = METRIC_REGISTRY.counter("m01-counter");
        counter.inc();

        Histogram histogram = METRIC_REGISTRY.histogram("m02-histogram");
        histogram.update(5);
        histogram.update(20);
        histogram.update(100);
    }

    @Override
    protected MetricRegistry getMetricRegistry() {
        return METRIC_REGISTRY;
    }
}

Both this listener and MetricsServlet need to be added into web.xml:

这个监听器和MetricsServlet都需要被添加到web.xml

<listener>
    <listener-class>com.codahale.metrics.servlets.MyMetricsServletContextListener</listener-class>
</listener>
<servlet>
    <servlet-name>metrics</servlet-name>
    <servlet-class>com.codahale.metrics.servlets.MetricsServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>metrics</servlet-name>
    <url-pattern>/metrics</url-pattern>
</servlet-mapping>

This will be exposed in our web application at “http://localhost:8080/metrics”. Its response should contain various metrics data:

这将在我们的网络应用中暴露在 “http://localhost:8080/metrics”。它的响应应该包含各种指标数据。

{
  "version": "3.0.0",
  "gauges": {},
  "counters": {
    "m01-counter": {
      "count": 1
    }
  },
  "histograms": {
    "m02-histogram": {
      "count": 3,
      "max": 100,
      "mean": 41.66666666666666,
      "min": 5,
      "p50": 20,
      "p75": 100,
      "p95": 100,
      "p98": 100,
      "p99": 100,
      "p999": 100,
      "stddev": 41.69998667732268
    }
  },
  "meters": {},
  "timers": {}
}

5.6. AdminServlet Usage

5.6.AdminServletUsage

AdminServlet aggregates HealthCheckServlet, ThreadDumpServlet, MetricsServlet, and PingServlet.

AdminServlet聚合了HealthCheckServletThreadDumpServletMetricsServletPingServlet

Let’s add these into the web.xml:

让我们把这些添加到web.xml中。

<servlet>
    <servlet-name>admin</servlet-name>
    <servlet-class>com.codahale.metrics.servlets.AdminServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/admin/*</url-pattern>
</servlet-mapping>

It can now be accessed at “http://localhost:8080/admin”. We will get a page containing four links, one for each of those four servlets.

现在可以通过 “http://localhost:8080/admin “访问它。我们将得到一个包含四个链接的页面,这四个servlet各一个。

Note that, if we want to do health check and access metrics data, those two listeners are still needed.

注意,如果我们想做健康检查和访问指标数据,仍然需要这两个监听器。

6. Module metrics-servlet

6.模块metrics-servlet

The metrics-servlet module provides a Filter which has several metrics: meters for status codes, a counter for the number of active requests, and a timer for request duration.

metrics-servlet模块提供了一个Filter,它有几个指标:状态代码的仪表、活动请求数的计数器和请求持续时间的计时器。

6.1. Maven Dependencies

6.1.Maven的依赖性

To use this module, let’s first add the dependency into the pom.xml:

要使用这个模块,首先让我们在pom.xml中添加依赖性。

<dependency>
    <groupId>io.dropwizard.metrics</groupId>
    <artifactId>metrics-servlet</artifactId>
    <version>3.1.2</version>
</dependency>

And you can find its latest version here.

而你可以在这里找到其最新版本

6.2. Usage

6.2.使用方法

To use it, we need to create a ServletContextListener which exposes our MetricRegistry to the InstrumentedFilter:

为了使用它,我们需要创建一个ServletContextListener,将我们的MetricRegistry暴露给InstrumentedFilter

public class MyInstrumentedFilterContextListener
  extends InstrumentedFilterContextListener {
 
    public static MetricRegistry REGISTRY = new MetricRegistry();

    @Override
    protected MetricRegistry getMetricRegistry() {
        return REGISTRY;
    }
}

Then, we add these into the web.xml:

然后,我们把这些添加到web.xml

<listener>
     <listener-class>
         com.baeldung.metrics.servlet.MyInstrumentedFilterContextListener
     </listener-class>
</listener>

<filter>
    <filter-name>instrumentFilter</filter-name>
    <filter-class>
        com.codahale.metrics.servlet.InstrumentedFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>instrumentFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Now the InstrumentedFilter can work. If we want to access its metrics data, we can do it through its MetricRegistry REGISTRY.

现在InstrumentedFilter可以工作了。如果我们想访问它的度量数据,我们可以通过它的MetricRegistry REGISTRY来进行。

7. Other Modules

7.其他模块

Except for the modules we introduced above, Metrics has some other modules for different purposes:

除了我们上面介绍的模块,Metrics还有一些其他的模块,用于不同的目的。

  • metrics-jvm: provides several useful metrics for instrumenting JVM internals
  • metrics-ehcache: provides InstrumentedEhcache, a decorator for Ehcache caches
  • metrics-httpclient: provides classes for instrumenting Apache HttpClient (4.x version)
  • metrics-log4j: provides InstrumentedAppender, a Log4j Appender implementation for log4j 1.x which records the rate of logged events by their logging level
  • metrics-log4j2: is similar to metrics-log4j, just for log4j 2.x
  • metrics-logback: provides InstrumentedAppender, a Logback Appender implementation which records the rate of logged events by their logging level
  • metrics-json: provides HealthCheckModule and MetricsModule for Jackson

What’s more, other than these main project modules, some other third party libraries provide integration with other libraries and frameworks.

更重要的是,除了这些主要的项目模块之外,其他一些第三方库提供了与其他库和框架的集成。

8. Conclusion

8.结论

Instrumenting applications is a common requirement, so in this article, we introduced Metrics, hoping that it can help you to solve your problem.

衡量应用程序是一个常见的要求,所以在这篇文章中,我们介绍了Metrics,希望它能帮助你解决你的问题。

As always, the complete source code for the example is available over on GitHub.

一如既往,该示例的完整源代码可在GitHub上获得over