0
# Metrics Core
1
2
Metrics Core is the foundational component of the Dropwizard Metrics library, providing comprehensive application-level metrics collection and monitoring capabilities for Java applications. It offers a rich toolkit of metric types including counters, gauges, histograms, meters, and timers that enable developers to measure and monitor the behavior of critical components in production environments.
3
4
The library features thread-safe metric collection, configurable sampling reservoirs for histograms, exponential decay algorithms for time-based metrics, and flexible reporting mechanisms including JMX, console, CSV, and SLF4J outputs. Designed for high-performance production use with minimal overhead, metrics-core supports custom metric implementations, metric filtering, and integration with various monitoring systems.
5
6
## Package Information
7
8
- **Package Name**: metrics-core
9
- **Package Type**: Maven
10
- **Language**: Java
11
- **Group ID**: io.dropwizard.metrics
12
- **Artifact ID**: metrics-core
13
- **Installation**: Add to Maven `pom.xml`:
14
15
```xml
16
<dependency>
17
<groupId>io.dropwizard.metrics</groupId>
18
<artifactId>metrics-core</artifactId>
19
<version>4.2.33</version>
20
</dependency>
21
```
22
23
For Gradle:
24
25
```gradle
26
implementation 'io.dropwizard.metrics:metrics-core:4.2.33'
27
```
28
29
## Core Imports
30
31
```java
32
import com.codahale.metrics.*;
33
```
34
35
Common specific imports:
36
37
```java
38
import com.codahale.metrics.MetricRegistry;
39
import com.codahale.metrics.Counter;
40
import com.codahale.metrics.Gauge;
41
import com.codahale.metrics.Histogram;
42
import com.codahale.metrics.Meter;
43
import com.codahale.metrics.Timer;
44
import com.codahale.metrics.ConsoleReporter;
45
```
46
47
## Basic Usage
48
49
```java
50
import com.codahale.metrics.*;
51
import java.util.concurrent.TimeUnit;
52
53
// Create a metric registry - the central repository for metrics
54
MetricRegistry registry = new MetricRegistry();
55
56
// Create different types of metrics
57
Counter requests = registry.counter("requests");
58
Histogram responseSizes = registry.histogram("response-sizes");
59
Meter requestMeter = registry.meter("request-rate");
60
Timer timer = registry.timer("request-duration");
61
62
// Use the metrics
63
requests.inc(); // Increment counter
64
responseSizes.update(responseSize); // Record response size
65
requestMeter.mark(); // Mark an event occurrence
66
Timer.Context context = timer.time(); // Start timing
67
// ... do work ...
68
context.stop(); // Stop timing and record
69
70
// Set up reporting to console every 30 seconds
71
ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
72
.convertRatesTo(TimeUnit.SECONDS)
73
.convertDurationsTo(TimeUnit.MILLISECONDS)
74
.build();
75
reporter.start(30, TimeUnit.SECONDS);
76
77
// Or report once immediately
78
reporter.report();
79
```
80
81
## Architecture
82
83
Metrics Core is built around several key architectural components:
84
85
### Metric Registry System
86
- **MetricRegistry**: Central repository that manages all metrics by name
87
- **SharedMetricRegistries**: Global registry management for application-wide metrics
88
- **MetricSet**: Interface for grouping related metrics together
89
90
### Core Metric Types
91
- **Counter**: Thread-safe incrementing/decrementing counters
92
- **Gauge**: Instantaneous readings of arbitrary values
93
- **Meter**: Rate measurement (events per second with moving averages)
94
- **Histogram**: Statistical distribution of values with configurable sampling
95
- **Timer**: Combined timing and rate measurement with statistical analysis
96
97
### Sampling and Statistical Analysis
98
- **Reservoir**: Pluggable sampling strategies for histograms and timers
99
- **Snapshot**: Statistical views providing percentiles, mean, standard deviation
100
- **MovingAverages**: Exponentially weighted moving averages for rate calculations
101
102
### Reporting Framework
103
- **ScheduledReporter**: Abstract base for periodic reporting
104
- **Built-in Reporters**: Console, CSV, and SLF4J implementations
105
- **MetricFilter**: Selective reporting based on metric names and types
106
107
### Extensibility Points
108
- **Clock**: Pluggable time source for testing and alternate implementations
109
- **Custom Gauges**: Specialized gauge implementations for caching and derivation
110
- **Instrumentation**: Wrapper classes for automatic metrics collection
111
112
## Capabilities
113
114
### Core Metrics Framework
115
116
Central metric management and the primary metric types for application monitoring.
117
118
```java { .api }
119
// Central metric registry - primary entry point
120
public class MetricRegistry implements MetricSet {
121
public Counter counter(String name);
122
public Counter counter(String name, MetricSupplier<Counter> supplier);
123
public Histogram histogram(String name);
124
public Histogram histogram(String name, MetricSupplier<Histogram> supplier);
125
public Meter meter(String name);
126
public Meter meter(String name, MetricSupplier<Meter> supplier);
127
public Timer timer(String name);
128
public Timer timer(String name, MetricSupplier<Timer> supplier);
129
public <T extends Gauge> T gauge(String name);
130
public <T extends Gauge> T gauge(String name, MetricSupplier<T> supplier);
131
public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException;
132
public <T> Gauge<T> registerGauge(String name, Gauge<T> metric) throws IllegalArgumentException;
133
public void registerAll(MetricSet metrics) throws IllegalArgumentException;
134
public void registerAll(String prefix, MetricSet metrics) throws IllegalArgumentException;
135
public boolean remove(String name);
136
public void removeMatching(MetricFilter filter);
137
public SortedSet<String> getNames();
138
public SortedMap<String, Gauge> getGauges();
139
public SortedMap<String, Gauge> getGauges(MetricFilter filter);
140
public SortedMap<String, Counter> getCounters();
141
public SortedMap<String, Counter> getCounters(MetricFilter filter);
142
public SortedMap<String, Histogram> getHistograms();
143
public SortedMap<String, Histogram> getHistograms(MetricFilter filter);
144
public SortedMap<String, Meter> getMeters();
145
public SortedMap<String, Meter> getMeters(MetricFilter filter);
146
public SortedMap<String, Timer> getTimers();
147
public SortedMap<String, Timer> getTimers(MetricFilter filter);
148
public Map<String, Metric> getMetrics();
149
public static String name(String name, String... names);
150
public static String name(Class<?> klass, String... names);
151
}
152
153
// Thread-safe incrementing/decrementing counter
154
public class Counter implements Metric, Counting {
155
public void inc();
156
public void inc(long n);
157
public void dec();
158
public void dec(long n);
159
public long getCount();
160
}
161
162
// Instantaneous value reading (functional interface)
163
@FunctionalInterface
164
public interface Gauge<T> extends Metric {
165
T getValue();
166
}
167
168
// Rate measurement with moving averages
169
public class Meter implements Metered {
170
public Meter();
171
public Meter(Clock clock);
172
public Meter(MovingAverages movingAverages);
173
public Meter(MovingAverages movingAverages, Clock clock);
174
public void mark();
175
public void mark(long n);
176
public double getMeanRate();
177
public double getOneMinuteRate();
178
public double getFiveMinuteRate();
179
public double getFifteenMinuteRate();
180
public long getCount();
181
}
182
183
// Statistical distribution measurement
184
public class Histogram implements Metric, Sampling, Counting {
185
public Histogram(Reservoir reservoir);
186
public void update(int value);
187
public void update(long value);
188
public long getCount();
189
public Snapshot getSnapshot();
190
}
191
192
// Combined timing and rate measurement
193
public class Timer implements Metered, Sampling {
194
public Timer();
195
public Timer(Reservoir reservoir);
196
public Timer(Reservoir reservoir, Clock clock);
197
public void update(long duration, TimeUnit unit);
198
public void update(Duration duration);
199
public <T> T time(Callable<T> event) throws Exception;
200
public void time(Runnable event);
201
public Context time();
202
public <T> T timeSupplier(Supplier<T> event);
203
public long getCount();
204
public double getMeanRate();
205
public double getOneMinuteRate();
206
public double getFiveMinuteRate();
207
public double getFifteenMinuteRate();
208
public Snapshot getSnapshot();
209
210
public static class Context implements AutoCloseable {
211
public long stop();
212
public void close();
213
}
214
}
215
```
216
217
[Core Metrics Framework](./core-metrics.md)
218
219
### Advanced Gauge Types
220
221
Specialized gauge implementations for caching, derivation, and settable values.
222
223
```java { .api }
224
// Cache gauge values for performance
225
public abstract class CachedGauge<T> implements Gauge<T> {
226
public CachedGauge(long timeout, TimeUnit timeoutUnit);
227
public CachedGauge(Clock clock, long timeout, TimeUnit timeoutUnit);
228
protected abstract T loadValue();
229
}
230
231
// Derive values from another gauge
232
public abstract class DerivativeGauge<F, T> implements Gauge<T> {
233
public DerivativeGauge(Gauge<F> base);
234
protected abstract T transform(F value);
235
}
236
237
// Calculate ratios with NaN handling
238
public abstract class RatioGauge implements Gauge<Double> {
239
protected abstract Ratio getRatio();
240
241
public static class Ratio {
242
public static Ratio of(double numerator, double denominator);
243
}
244
}
245
246
// Gauges that can be explicitly set
247
public interface SettableGauge<T> extends Gauge<T> {
248
void setValue(T value);
249
}
250
251
public class DefaultSettableGauge<T> implements SettableGauge<T> {
252
public DefaultSettableGauge();
253
public DefaultSettableGauge(T initialValue);
254
public void setValue(T value);
255
public T getValue();
256
}
257
```
258
259
[Advanced Gauge Types](./advanced-gauges.md)
260
261
### Reservoirs and Sampling
262
263
Statistical sampling strategies for histograms and timers to manage memory usage while preserving statistical accuracy.
264
265
```java { .api }
266
// Base interface for sampling strategies
267
public interface Reservoir {
268
int size();
269
void update(long value);
270
Snapshot getSnapshot();
271
}
272
273
// Random sampling using Vitter's Algorithm R
274
public class UniformReservoir implements Reservoir {
275
public UniformReservoir();
276
public UniformReservoir(int size);
277
}
278
279
// Time-biased sampling favoring recent values
280
public class ExponentiallyDecayingReservoir implements Reservoir {
281
public ExponentiallyDecayingReservoir();
282
public ExponentiallyDecayingReservoir(int size, double alpha);
283
public ExponentiallyDecayingReservoir(int size, double alpha, Clock clock);
284
public void update(long value, long timestamp);
285
}
286
287
// Fixed-size sliding window of most recent values
288
public class SlidingWindowReservoir implements Reservoir {
289
public SlidingWindowReservoir(int size);
290
}
291
292
// Time-based sliding window
293
public class SlidingTimeWindowReservoir implements Reservoir {
294
public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit);
295
public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit, Clock clock);
296
}
297
```
298
299
[Reservoirs and Sampling](./reservoirs-sampling.md)
300
301
### Reporting Framework
302
303
Flexible reporting system for outputting metrics to various destinations on configurable schedules.
304
305
```java { .api }
306
// Abstract base for all scheduled reporters
307
public abstract class ScheduledReporter implements Closeable, Reporter {
308
public void start(long period, TimeUnit unit);
309
public void start(long initialDelay, long period, TimeUnit unit);
310
public void stop();
311
public void report();
312
protected abstract void report(
313
SortedMap<String, Gauge> gauges,
314
SortedMap<String, Counter> counters,
315
SortedMap<String, Histogram> histograms,
316
SortedMap<String, Meter> meters,
317
SortedMap<String, Timer> timers);
318
}
319
320
// Console/PrintStream output reporter
321
public class ConsoleReporter extends ScheduledReporter {
322
public static Builder forRegistry(MetricRegistry registry);
323
324
public static class Builder {
325
public Builder outputTo(PrintStream output);
326
public Builder convertRatesTo(TimeUnit rateUnit);
327
public Builder convertDurationsTo(TimeUnit durationUnit);
328
public Builder filter(MetricFilter filter);
329
public ConsoleReporter build();
330
}
331
}
332
333
// CSV file output reporter
334
public class CsvReporter extends ScheduledReporter {
335
public static Builder forRegistry(MetricRegistry registry);
336
337
public static class Builder {
338
public Builder convertRatesTo(TimeUnit rateUnit);
339
public Builder convertDurationsTo(TimeUnit durationUnit);
340
public Builder filter(MetricFilter filter);
341
public CsvReporter build(File directory);
342
}
343
}
344
345
// SLF4J logging reporter
346
public class Slf4jReporter extends ScheduledReporter {
347
public static Builder forRegistry(MetricRegistry registry);
348
349
public static class Builder {
350
public Builder outputTo(Logger logger);
351
public Builder markWith(Marker marker);
352
public Builder withLoggingLevel(LoggingLevel loggingLevel);
353
public Slf4jReporter build();
354
}
355
356
public enum LoggingLevel { TRACE, DEBUG, INFO, WARN, ERROR }
357
}
358
```
359
360
[Reporting Framework](./reporting.md)
361
362
### Utilities and Extensions
363
364
Helper classes for filtering, instrumentation, and extended functionality.
365
366
```java { .api }
367
// Global registry management
368
public class SharedMetricRegistries {
369
public static MetricRegistry getOrCreate(String name);
370
public static void setDefault(String name);
371
public static MetricRegistry getDefault();
372
public static void add(String name, MetricRegistry registry);
373
public static void remove(String name);
374
}
375
376
// Filtering metrics for reporting
377
@FunctionalInterface
378
public interface MetricFilter {
379
boolean matches(String name, Metric metric);
380
381
MetricFilter ALL = (name, metric) -> true;
382
static MetricFilter startsWith(String prefix);
383
static MetricFilter endsWith(String suffix);
384
static MetricFilter contains(String substring);
385
}
386
387
// ExecutorService with automatic metrics
388
public class InstrumentedExecutorService implements ExecutorService {
389
public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry);
390
public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry, String name);
391
}
392
393
// Registry event listener
394
public interface MetricRegistryListener extends EventListener {
395
void onGaugeAdded(String name, Gauge<?> gauge);
396
void onCounterAdded(String name, Counter counter);
397
void onHistogramAdded(String name, Histogram histogram);
398
void onMeterAdded(String name, Meter meter);
399
void onTimerAdded(String name, Timer timer);
400
// ... corresponding removal methods
401
402
abstract class Base implements MetricRegistryListener {
403
// No-op base implementation
404
}
405
}
406
407
// Supplier interface for metric factory methods
408
@FunctionalInterface
409
public interface MetricSupplier<T extends Metric> {
410
T newMetric();
411
}
412
```
413
414
[Utilities and Extensions](./utilities.md)
415
416
## Common Usage Patterns
417
418
### Application Metrics Setup
419
1. Create a `MetricRegistry` instance (or use `SharedMetricRegistries` for global access)
420
2. Register metrics using the registry's factory methods (`counter()`, `meter()`, etc.)
421
3. Configure and start reporters for desired output destinations
422
4. Instrument application code with metric updates
423
424
### Custom Histogram Configuration
425
Use specific reservoir implementations to control sampling behavior for histograms and timers based on your data characteristics and memory constraints.
426
427
### Multi-threaded Applications
428
All core metric types are thread-safe. Use `SharedMetricRegistries` to access the same metrics across different application components.
429
430
### Production Monitoring
431
Combine multiple reporters (console for debugging, CSV for analysis, SLF4J for log aggregation) to get comprehensive visibility into application behavior.
432
433
### Testing and Development
434
Use the `Clock` abstraction and custom implementations for deterministic testing of time-based metrics like meters and timers.