下面列出了怎么用com.codahale.metrics.MetricFilter的API类实例代码及写法,或者点击链接到github查看源代码。
private Map<String, Gauge> extractGauges(
final MetricRegistry metricRegistry, final MetricFilter filter) {
Map<String, Gauge> gauges = new HashMap<>();
// find the AggregatorMetric metrics from within all currently registered metrics
final Optional<Map<String, Gauge>> aggregatorMetrics =
FluentIterable.from(metricRegistry.getMetrics().entrySet())
.firstMatch(isAggregatorMetric())
.transform(aggregatorMetricToGauges());
// find the SparkBeamMetric metrics from within all currently registered metrics
final Optional<Map<String, Gauge>> beamMetrics =
FluentIterable.from(metricRegistry.getMetrics().entrySet())
.firstMatch(isSparkBeamMetric())
.transform(beamMetricToGauges());
if (aggregatorMetrics.isPresent()) {
gauges.putAll(Maps.filterEntries(aggregatorMetrics.get(), matches(filter)));
}
if (beamMetrics.isPresent()) {
gauges.putAll(Maps.filterEntries(beamMetrics.get(), matches(filter)));
}
return gauges;
}
@Test
public void testPointsSent() throws Exception {
MetricRegistry registry = new MetricRegistry();
new BasicJvmMetrics(registry);
ScheduledReporter reporter = new ScheduledReporter(registry, "test", MetricFilter.ALL,
TimeUnit.SECONDS, TimeUnit.MILLISECONDS) {
@Override
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
Assert.assertFalse(gauges.isEmpty());
Assert.assertNotNull(gauges.get("jvm.uptime"));
for (Map.Entry<String, Gauge> entry : gauges.entrySet()) {
Assert.assertNotNull(entry.getValue().getValue());
}
}
};
reporter.report();
reporter.close();
}
private HadoopMetrics2Reporter(MetricRegistry registry, TimeUnit rateUnit, TimeUnit durationUnit,
MetricFilter filter, MetricsSystem metrics2System, String jmxContext, String description, String recordName,
String context) {
super(registry, "hadoop-metrics2-reporter", filter, rateUnit, durationUnit);
this.metrics2Registry = new MetricsRegistry(Interns.info(jmxContext, description));
this.metrics2System = metrics2System;
this.recordName = recordName;
this.context = context;
// These could really be Collection.emptyMap(), but this makes testing a bit easier.
this.dropwizardGauges = EMPTY_GAUGE_MAP;
this.dropwizardCounters = EMPTY_COUNTER_MAP;
this.dropwizardHistograms = EMPTY_HISTOGRAM_MAP;
this.dropwizardMeters = EMPTY_METER_MAP;
this.dropwizardTimers = EMPTY_TIMER_MAP;
// Register this source with the Metrics2 system.
// Make sure this is the last thing done as getMetrics() can be called at any time after.
this.metrics2System.register(Objects.requireNonNull(jmxContext), Objects.requireNonNull(description), this);
}
@Override
public void init(ServletConfig config) throws ServletException {
final ServletContext context = config.getServletContext();
if (null == registry) {
final Object registryAttr = context.getAttribute(JVM_METRICS_REGISTRY);
if (registryAttr instanceof MetricRegistry) {
this.registry = (MetricRegistry) registryAttr;
} else {
throw new ServletException("Couldn't find a JVMMetricRegistry instance.");
}
}
final TimeUnit rateUnit = parseTimeUnit(context.getInitParameter(RATE_UNIT), TimeUnit.SECONDS);
final TimeUnit durationUnit = parseTimeUnit(context.getInitParameter(DURATION_UNIT), TimeUnit.SECONDS);
final boolean showSamples = Boolean.parseBoolean(context.getInitParameter(SHOW_SAMPLES));
MetricFilter filter = (MetricFilter) context.getAttribute(METRIC_FILTER);
if (filter == null) {
filter = MetricFilter.ALL;
}
this.mapper = new ObjectMapper().registerModule(new MetricsModule(rateUnit, durationUnit, showSamples, filter));
this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN);
this.jsonpParamName = context.getInitParameter(CALLBACK_PARAM);
}
@Override
public void report(MetricRegistry metricRegistry) {
JbootMetricInfluxdbReporterConfig config = Jboot.config(JbootMetricInfluxdbReporterConfig.class);
final ScheduledReporter reporter = metrics_influxdb.InfluxdbReporter.forRegistry(metricRegistry)
.protocol(new HttpInfluxdbProtocol("http"
, config.getHost()
, config.getPort()
, config.getUser()
, config.getPassword()
, config.getDbName()))
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.filter(MetricFilter.ALL)
.skipIdleMetrics(false)
// .tag("cluster", config.getTagCluster())
// .tag("client", config.getTagClient())
// .tag("server", serverIP)
// .transformer(new CategoriesMetricMeasurementTransformer("module", "artifact"))
.build();
reporter.start(10, TimeUnit.SECONDS);
}
/** Create a new instance. */
SpectatorReporter(
MetricRegistry metricRegistry,
Registry spectatorRegistry,
NameFunction nameFunction,
ValueFunction valueFunction,
Pattern gaugeCounters) {
super(metricRegistry,
"spectator", // name
MetricFilter.ALL, // filter
TimeUnit.SECONDS, // rateUnit
TimeUnit.SECONDS); // durationUnit
this.spectatorRegistry = spectatorRegistry;
this.nameFunction = nameFunction;
this.valueFunction = valueFunction;
this.gaugeCounters = gaugeCounters;
}
@BeforeEach
public void setUp() {
Clock clock = mock(Clock.class);
graphite = mock(Graphite.class);
MetricRegistry registry = mock(MetricRegistry.class);
when(clock.getTime()).thenReturn(TIMESTAMP * 1000);
reporter = forRegistry(registry)
.withClock(clock)
.prefixedWith("prefix")
.convertRatesTo(SECONDS)
.convertDurationsTo(MILLISECONDS)
.filter(MetricFilter.ALL)
.build(graphite);
logging = new LoggingTestSupport(GraphiteReporter.class);
}
/**
* This method starts a separate thread that listens to key expirations events.
*
* @param sessionManager
*/
@Override
public void setSessionManager(final SessionManager sessionManager) {
this.sessionManager = sessionManager;
MetricRegistry metrics = sessionManager.getMetrics();
if (metrics != null) {
// Cleanup old metrics related to this namespace
metrics.removeMatching(new MetricFilter() {
@Override
public boolean matches(String name, Metric metric) {
return name.startsWith(name(RedisConfiguration.METRIC_PREFIX, "redis"));
}
});
if (sticky) {
failoverMetrics = metrics.meter(name(RedisConfiguration.METRIC_PREFIX, namespace, "redis", "failover"));
}
redis.startMonitoring(metrics);
}
expirationManager.startExpiredSessionsTask(sessionManager);
}
/**
* This returns the set of jars required by a basic Gobblin ingestion job. In general, these need to be distributed
* to workers in a distributed environment.
*/
private void loadCoreGobblinJarsToDistributedJars() {
// Gobblin-api
distributeJarByClassWithPriority(State.class, 0);
// Gobblin-core
distributeJarByClassWithPriority(ConstructState.class, 0);
// Gobblin-core-base
distributeJarByClassWithPriority(InstrumentedExtractorBase.class, 0);
// Gobblin-metrics-base
distributeJarByClassWithPriority(MetricContext.class, 0);
// Gobblin-metrics
distributeJarByClassWithPriority(GobblinMetrics.class, 0);
// Gobblin-metastore
distributeJarByClassWithPriority(FsStateStore.class, 0);
// Gobblin-runtime
distributeJarByClassWithPriority(Task.class, 0);
// Gobblin-utility
distributeJarByClassWithPriority(PathUtils.class, 0);
// joda-time
distributeJarByClassWithPriority(ReadableInstant.class, 0);
// guava
distributeJarByClassWithPriority(Escaper.class, -10); // Escaper was added in guava 15, so we use it to identify correct jar
// dropwizard.metrics-core
distributeJarByClassWithPriority(MetricFilter.class, 0);
// pegasus
distributeJarByClassWithPriority(DataTemplate.class, 0);
// commons-lang3
distributeJarByClassWithPriority(ClassUtils.class, 0);
// avro
distributeJarByClassWithPriority(SchemaBuilder.class, 0);
// guava-retry
distributeJarByClassWithPriority(RetryListener.class, 0);
// config
distributeJarByClassWithPriority(ConfigFactory.class, 0);
// reflections
distributeJarByClassWithPriority(Reflections.class, 0);
// javassist
distributeJarByClassWithPriority(ClassFile.class, 0);
}
public Builder(MetricRegistry registry) {
this.registry = registry;
this.rateUnit = TimeUnit.SECONDS;
this.durationUnit = TimeUnit.MILLISECONDS;
this.filter = MetricFilter.ALL;
}
void destroy() {
final ThreadId savedId = this.id;
LOG.info("Replicator {} is going to quit", savedId);
releaseReader();
// Unregister replicator metric set
if (this.nodeMetrics.isEnabled()) {
this.nodeMetrics.getMetricRegistry() //
.removeMatching(MetricFilter.startsWith(getReplicatorMetricName(this.options)));
}
this.state = State.Destroyed;
notifyReplicatorStatusListener((Replicator) savedId.getData(), ReplicatorEvent.DESTROYED);
savedId.unlockAndDestroy();
this.id = null;
}
@Override
public boolean matches(String name, Metric metric) {
for (MetricFilter eachFilter: filters) {
if (!eachFilter.matches(name, metric)) {
return false;
}
}
return true;
}
@Test
public void instrumentationProvidersLoadingDefaultIsEmpty() throws Exception {
DefaultMetricsService service = new DefaultMetricsService();
service.init(new GatewayConfigImpl(), null);
Map<Class<?>, InstrumentationProvider> map = service.getInstrumentationProviders();
Assert.assertTrue(map.entrySet().isEmpty());
Assert.assertNull(service.getInstrumented(HttpClientBuilder.class));
service.getMetricRegistry().removeMatching(MetricFilter.ALL);
}
@Test
public void stopShouldCloseEnclosedClient() throws IOException {
new DatadogReporter(registry, client, "foo", Option.empty(), Option.empty(),
MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.SECONDS).stop();
verify(client).close();
}
@Override
public boolean matches(String s, Metric metric) {
for (MetricFilter filter : filters) {
if (filter.matches(s, metric)) {
return true;
}
}
return false;
}
private Builder(MetricRegistry registry) {
this.registry = registry;
this.output = System.out;
this.locale = Locale.getDefault();
this.timeZone = TimeZone.getDefault();
this.rateUnit = TimeUnit.SECONDS;
this.durationUnit = TimeUnit.MILLISECONDS;
this.filter = MetricFilter.ALL;
}
@SuppressWarnings("unchecked")
private <T extends com.codahale.metrics.Metric> SortedMap<String, T> getSimplyNamedMetrics(Class<T> mClass,
Optional<MetricFilter> filter) {
ImmutableSortedMap.Builder<String, T> builder = ImmutableSortedMap.naturalOrder();
for (Map.Entry<String, InnerMetric> entry : this.contextAwareMetrics.entrySet()) {
if (mClass.isInstance(entry.getValue())) {
if (filter.isPresent() && !filter.get().matches(entry.getKey(), entry.getValue().getContextAwareMetric())) {
continue;
}
builder.put(entry.getKey(), (T) entry.getValue());
}
}
return builder.build();
}
public Counter getCounter(final String meterName) {
final Set<Map.Entry<String, Counter>> entries = metricRegistry.getCounters(new MetricFilter() {
@Override
public boolean matches(final String name, final Metric metric) {
return name.equals(meterName);
}
}).entrySet();
Preconditions.checkState(entries.size() == 1);
return entries.iterator().next().getValue();
}
public OrFilter(MetricFilter... filters) {
if (filters != null) {
for (MetricFilter filter : filters) {
if (filter != null) {
this.filters.add(filter);
}
}
}
}
@Override
public SortedMap<String, Gauge> getGauges(final MetricFilter filter) {
return new ImmutableSortedMap.Builder<String, Gauge>(
Ordering.from(String.CASE_INSENSITIVE_ORDER))
.putAll(internalMetricRegistry.getGauges(filter))
.putAll(extractGauges(internalMetricRegistry, filter))
.build();
}
private Builder(MetricRegistry registry) {
this.registry = registry;
this.output = System.out;
this.locale = Locale.getDefault();
this.clock = Clock.defaultClock();
this.timeZone = TimeZone.getDefault();
this.rateUnit = TimeUnit.SECONDS;
this.durationUnit = TimeUnit.MILLISECONDS;
this.filter = MetricFilter.ALL;
}
@Override
protected void doInit() {
mdcContext = MDC.getCopyOfContextMap();
mdcContext.put("registry", "m:" + registryName);
Slf4jReporter.Builder builder = Slf4jReporter
.forRegistry(metricManager.registry(registryName))
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS);
final MetricFilter filter = newMetricFilter();
builder = builder.filter(filter);
if (instancePrefix != null) {
builder = builder.prefixedWith(instancePrefix);
}
if (logger == null || logger.isEmpty()) {
// construct logger name from Group
if (pluginInfo.attributes.containsKey("group")) {
logger = SolrMetricManager.enforcePrefix(pluginInfo.attributes.get("group"));
} else if (pluginInfo.attributes.containsKey("registry")) {
String reg = SolrMetricManager.enforcePrefix(pluginInfo.attributes.get("registry"));
String[] names = reg.split("\\.");
if (names.length < 2) {
logger = reg;
} else {
logger = names[0] + "." + names[1];
}
}
}
builder = builder.outputTo(LoggerFactory.getLogger(logger));
// build BUT don't start - scheduled execution is handled by the wrapper
Slf4jReporter delegate = builder.build();
reporter = new Slf4jReporterWrapper(logger, mdcContext, delegate, TimeUnit.SECONDS, TimeUnit.MILLISECONDS);
reporter.start(period, TimeUnit.SECONDS);
active = true;
}
private ServerReporter(MetricRegistry registry, TimeUnit rateUnit,
TimeUnit durationUnit, MetricFilter filter) {
super(registry, "server-reporter", filter, rateUnit, durationUnit);
this.gauges = ImmutableSortedMap.of();
this.counters = ImmutableSortedMap.of();
this.histograms = ImmutableSortedMap.of();
this.meters = ImmutableSortedMap.of();
this.timers = ImmutableSortedMap.of();
}
private JmxListener(MBeanServer mBeanServer, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit,
ObjectNameFactory objectNameFactory, String tag) {
this.mBeanServer = mBeanServer;
this.name = name;
this.filter = filter;
this.rateUnit = rateUnit;
this.durationUnit = durationUnit;
this.registered = new ConcurrentHashMap<>();
this.objectNameFactory = objectNameFactory;
this.tag = tag;
this.exp = Query.eq(Query.attr(INSTANCE_TAG), Query.value(tag));
}
@BeforeClass
@SuppressWarnings("unchecked")
public void setUp() {
TaskInputOutputContext<Object, Object, Object, Object> mockContext = Mockito.mock(TaskInputOutputContext.class);
this.recordsProcessedCount = Mockito.mock(Counter.class);
Mockito.when(mockContext.getCounter(
this.name, MetricRegistry.name(RECORDS_PROCESSED, Measurements.COUNT.getName())))
.thenReturn(this.recordsProcessedCount);
this.recordProcessRateCount = Mockito.mock(Counter.class);
Mockito.when(mockContext.getCounter(
this.name, MetricRegistry.name(RECORD_PROCESS_RATE, Measurements.COUNT.getName())))
.thenReturn(this.recordProcessRateCount);
this.recordSizeDistributionCount = Mockito.mock(Counter.class);
Mockito.when(mockContext.getCounter(
this.name, MetricRegistry.name(RECORD_SIZE_DISTRIBUTION, Measurements.COUNT.getName())))
.thenReturn(this.recordSizeDistributionCount);
this.totalDurationCount = Mockito.mock(Counter.class);
Mockito.when(mockContext.getCounter(
this.name, MetricRegistry.name(TOTAL_DURATION, Measurements.COUNT.getName())))
.thenReturn(this.totalDurationCount);
this.queueSize = Mockito.mock(Counter.class);
Mockito.when(mockContext.getCounter(this.name, QUEUE_SIZE)).thenReturn(this.queueSize);
this.hadoopCounterReporter = NewAPIHadoopCounterReporter.builder(mockContext)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.SECONDS)
.filter(MetricFilter.ALL)
.build(MetricContext.builder(this.name).build());
}
@Test
public void prefixShouldPrepend() {
DatadogReporter reporter = new DatadogReporter(
registry, client, "foo", Option.empty(), Option.empty(),
MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.SECONDS);
assertEquals("foo.bar", reporter.prefix("bar"));
}
@Test
public void testEmpty() throws Exception {
String str = "{ metricFilter : {} }";
Config config = ConfigFactory.parseString(str);
MetricFilter filter = PatternMetricFilter.parse(new Configs(), config);
assertNotSame(filter, MetricFilter.ALL);
assertTrue(filter.matches("foo", new Counter()));
assertTrue(filter.toString().length() > 0);
}
private static InfluxDbReporter startInfluxDbReporter(MetricRegistry registry, InfluxDbSender influxDbSender)
throws Exception {
final Map<String, String> tags = new HashMap<String, String>();
tags.put("host", "localhost");
final InfluxDbReporter reporter = InfluxDbReporter
.forRegistry(registry)
.withTags(tags)
.skipIdleMetrics(true)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.filter(MetricFilter.ALL)
.build(influxDbSender);
reporter.start(10, TimeUnit.SECONDS);
return reporter;
}
private Collection<Integer> statusCountsExcluding(String excluded) {
MetricFilter filter = (name, metric) ->
(name.startsWith("styx.response.status.") || name.startsWith("origins.response.status.")) && !name.equals(excluded);
return registry.getCounters(filter).values().stream()
.map(Counter::getCount)
.map(Long::intValue)
.collect(toList());
}
@BeforeClass
public void setUp() throws Exception {
String contextName = CONTEXT_NAME + "_" + UUID.randomUUID().toString();
Reporter mockedReporter = Mockito.mock(Reporter.class);
this.recordsProcessedCount = Mockito.mock(Counters.Counter.class);
Mockito.when(mockedReporter.getCounter(
contextName, MetricRegistry.name(RECORDS_PROCESSED, Measurements.COUNT.getName())))
.thenReturn(this.recordsProcessedCount);
this.recordProcessRateCount = Mockito.mock(Counters.Counter.class);
Mockito.when(mockedReporter.getCounter(
contextName, MetricRegistry.name(RECORD_PROCESS_RATE, Measurements.COUNT.getName())))
.thenReturn(this.recordProcessRateCount);
this.recordSizeDistributionCount = Mockito.mock(Counters.Counter.class);
Mockito.when(mockedReporter.getCounter(
contextName, MetricRegistry.name(RECORD_SIZE_DISTRIBUTION, Measurements.COUNT.getName())))
.thenReturn(this.recordSizeDistributionCount);
this.totalDurationCount = Mockito.mock(Counters.Counter.class);
Mockito.when(mockedReporter.getCounter(
contextName, MetricRegistry.name(TOTAL_DURATION, Measurements.COUNT.getName())))
.thenReturn(this.totalDurationCount);
this.queueSize = Mockito.mock(Counters.Counter.class);
Mockito.when(mockedReporter.getCounter(contextName, QUEUE_SIZE)).thenReturn(this.queueSize);
this.hadoopCounterReporter = HadoopCounterReporter.builder(mockedReporter)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.SECONDS)
.filter(MetricFilter.ALL)
.build(MetricContext.builder(contextName).buildStrict());
}