下面列出了com.codahale.metrics.MetricRegistry#name ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static String dropwizardMetricName(KafkaMetric kafkaMetric) {
MetricName name = kafkaMetric.metricName();
List<String> nameParts = new ArrayList<String>(2);
nameParts.add(name.group());
nameParts.addAll(name.tags().values());
nameParts.add(name.name());
StringBuilder builder = new StringBuilder();
for (String namePart : nameParts) {
builder.append(namePart);
builder.append(".");
}
builder.setLength(builder.length() - 1); // Remove the trailing dot.
String processedName = builder.toString().replace(' ', '_').replace("\\.", "_");
return MetricRegistry.name(METRIC_PREFIX, processedName);
}
@Inject
public CompositeConsistencyTimeProvider(Collection<ClusterInfo> clusterInfo,
List<FullConsistencyTimeProvider> providers,
MetricRegistry metricRegistry) {
checkNotNull(clusterInfo, "clusterInfo");
_providers = checkNotNull(providers, "providers");
// Publish metrics for the full consistency timestamp as a time lag compared to now. It's easier to alert
// on a time lag that exceeds min/max bounds compared to alerting on the timestamp itself.
for (final ClusterInfo cluster : clusterInfo) {
// Idempotent. Adds the gauge metric. If it already exists, then it gets the existing gauge.
String metricName = MetricRegistry.name("bv.emodb.sor", "FullConsistencyTimeProvider", "lag-" + cluster.getClusterMetric());
if (!metricRegistry.getGauges().containsKey(metricName)) {
metricRegistry.register(metricName,
new Gauge<Double>() {
@Override
public Double getValue() {
long timestamp = getMaxTimeStamp(cluster.getCluster());
long lag = System.currentTimeMillis() - timestamp;
return lag / 1000.0; // convert millis to seconds
}
});
}
}
}
static String metricPrefix(String app) {
Env env = Env.get();
String host = env == Env.LOCAL ? "localhost" : getHost();
String prefix = MetricRegistry.name(app, env.getName(), host);
log.info("Setting Metrics Prefix {}", prefix);
return prefix;
}
/**
* Returns compiled routes built from the given route map.
*
* @param metricRegistry the registry to generate per-(route,method) rate statistics in
*/
public CompiledRoutes(
Map<RoutePath, Map<HttpMethod, Handler>> rawRoutes, MetricRegistry metricRegistry) {
// Build a sorted map of the routes.
ImmutableSortedMap.Builder<RoutePath, ImmutableMap<HttpMethod, Handler>> routesBuilder =
ImmutableSortedMap.naturalOrder();
for (Map.Entry<RoutePath, Map<HttpMethod, Handler>> routeEntry : rawRoutes.entrySet()) {
ImmutableMap.Builder<HttpMethod, Handler> handlers = new ImmutableMap.Builder<>();
RoutePath route = routeEntry.getKey();
for (Map.Entry<HttpMethod, Handler> methodHandlerEntry : routeEntry.getValue().entrySet()) {
HttpMethod method = methodHandlerEntry.getKey();
// Wrap the user-provided handler in one that tracks request rates.
String metricName = MetricRegistry.name("routes", method.name(), route.toString());
String timerName = MetricRegistry.name("routeLatency", method.name(), route.toString());
final Handler userHandler = methodHandlerEntry.getValue();
final Meter meter = metricRegistry.meter(metricName);
final Timer timer = metricRegistry.timer(timerName);
// TODO (AD): Pull this out into an adapted handler in a separate class.
Handler adaptedHandler =
request -> {
meter.mark();
try {
return timer.time(() -> userHandler.handle(request));
} catch (Exception e) {
return request.connectionContext().exceptionHandler().handle(request, e);
}
};
handlers.put(method, adaptedHandler);
}
routesBuilder.put(route, handlers.build());
}
this.routes = routesBuilder.build();
}
/**
* @param prefix className or component name this metric registry collects metric for
* @param applicationName application Name needs to be in small case as it is used for hadoop2metrics
* @param metricsComponentName component name needs to be in small case as it is used for hadoop2metrics
* @param metricsDescription description of the metrics collected by this registry
*
*/
public MetricRegistryInfo(String prefix, String applicationName, String metricsComponentName,
String metricsDescription) {
this.prefix = prefix;
this.applicationName = applicationName;
this.metricsComponentName = metricsComponentName;
this.metricsDescription = metricsDescription;
this.fullName = MetricRegistry.name(applicationName, metricsComponentName, prefix);
}
/**
* Remove some metrics from a named registry
*
* @param registry registry name
* @param metricPath (optional) top-most metric name path elements. If empty then
* this is equivalent to calling {@link #clearRegistry(String)},
* otherwise non-empty elements will be joined using dotted notation
* to form a fully-qualified prefix. Metrics with names that start
* with the prefix will be removed.
* @return set of metrics names that have been removed.
*/
public Set<String> clearMetrics(String registry, String... metricPath) {
PrefixFilter filter;
if (metricPath == null || metricPath.length == 0) {
filter = new PrefixFilter("");
} else {
String prefix = MetricRegistry.name("", metricPath);
filter = new PrefixFilter(prefix);
}
registry(registry).removeMatching(filter);
return filter.getMatched();
}
private String metricNameForRunRepair(RepairSegment rs) {
String cleanHostName = Optional.ofNullable(rs.getCoordinatorHost()).orElse("null")
.replace('.', 'x')
.replaceAll("[^A-Za-z0-9]", "");
return MetricRegistry.name(
SegmentRunner.class,
"runRepair",
cleanHostName,
clusterName.replaceAll("[^A-Za-z0-9]", ""),
repairUnit.getKeyspaceName().replaceAll("[^A-Za-z0-9]", ""));
}
private SettableGauge createGauge(int partition) {
String name = MetricRegistry.name("partition", Integer.toString(partition), HIGHWATER_MARK);
SettableGauge gauge = new SettableGauge();
registry.register(name, gauge);
return gauge;
}
protected String getStatementTimer(Class<? extends Statement> clazz, String sql, String sqlId) {
final String lSqlId = sqlId == null ? getSqlId(sql) : sqlId;
return MetricRegistry.name(clazz, databaseName, lSqlId);
}
@Test
public void testCreateOrUpdateCounter() {
String numEvents = "numEvents";
String numErrors = "numErrors";
// create key-less counter
String fullKeylessMetricName = MetricRegistry.name(CLASS_NAME, numEvents);
_metricsManager.createOrUpdateCounter(CLASS_NAME, numEvents, 1);
Counter keylessCounter = _metricsManager.getMetric(fullKeylessMetricName);
Assert.assertEquals(keylessCounter.getCount(), 1);
_metricsManager.createOrUpdateCounter(CLASS_NAME, numEvents, 1);
Assert.assertEquals(keylessCounter.getCount(), 2);
_metricsManager.createOrUpdateCounter(CLASS_NAME, numEvents, 5);
// create keyed counters
String someKey = "someKey";
String fullMetricName = MetricRegistry.name(CLASS_NAME, someKey, numEvents);
_metricsManager.createOrUpdateCounter(CLASS_NAME, someKey, numEvents, 1);
Counter keyedCounter = _metricsManager.getMetric(fullMetricName);
Assert.assertEquals(keyedCounter.getCount(), 1);
_metricsManager.createOrUpdateCounter(CLASS_NAME, someKey, numEvents, 1);
Assert.assertEquals(keyedCounter.getCount(), 2);
_metricsManager.createOrUpdateCounter(CLASS_NAME, someKey, numErrors, 19);
Counter counter = _metricsManager.getMetric(MetricRegistry.name(CLASS_NAME, someKey, numErrors));
Assert.assertEquals(counter.getCount(), 19);
Assert.assertNotEquals(keyedCounter, keylessCounter);
Assert.assertNotEquals(keyedCounter, counter);
// create another key-less counter
String anotherFullKeylessMetricName = MetricRegistry.name(CLASS_NAME, numErrors);
_metricsManager.createOrUpdateCounter(CLASS_NAME, numErrors, 1);
Counter anotherKeylessCounter = _metricsManager.getMetric(anotherFullKeylessMetricName);
Assert.assertEquals(anotherKeylessCounter.getCount(), 1);
_metricsManager.createOrUpdateCounter(CLASS_NAME, numErrors, 1);
Assert.assertEquals(anotherKeylessCounter.getCount(), 2);
_metricsManager.createOrUpdateCounter(CLASS_NAME, numErrors, 5);
Assert.assertNotEquals(anotherKeylessCounter, keylessCounter);
// create another keyed counter
String anotherKey = "anotherKey";
String anotherFullMetricName = MetricRegistry.name(CLASS_NAME, anotherKey, numErrors);
_metricsManager.createOrUpdateCounter(CLASS_NAME, anotherKey, numErrors, 1);
Counter anotherKeyedCounter = _metricsManager.getMetric(anotherFullMetricName);
Assert.assertEquals(anotherKeyedCounter.getCount(), 1);
_metricsManager.createOrUpdateCounter(CLASS_NAME, anotherKey, numErrors, 1);
Assert.assertEquals(anotherKeyedCounter.getCount(), 2);
Assert.assertNotEquals(keyedCounter, anotherKeyedCounter);
// unregister and check cache
Assert.assertTrue(_metricsManager.checkCache(CLASS_NAME, null, numErrors).isPresent());
_metricsManager.unregisterMetric(CLASS_NAME, numErrors);
Assert.assertFalse(_metricsManager.checkCache(CLASS_NAME, null, numErrors).isPresent());
Assert.assertTrue(_metricsManager.checkCache(CLASS_NAME, anotherKey, numErrors).isPresent());
_metricsManager.unregisterMetric(CLASS_NAME, anotherKey, numErrors);
Assert.assertFalse(_metricsManager.checkCache(CLASS_NAME, anotherKey, numErrors).isPresent());
// others remain in cache
Assert.assertTrue(_metricsManager.checkCache(CLASS_NAME, null, numEvents).isPresent());
Assert.assertTrue(_metricsManager.checkCache(CLASS_NAME, someKey, numEvents).isPresent());
}
@Before
public void createTimedInstance() {
long id = Math.round(Math.random() * Long.MAX_VALUE);
instance = new TimedMethodWithNameFromElExpression(id);
timerName = MetricRegistry.name(TimedMethodWithNameFromElExpression.class, "timer " + id);
}
private String metricName(Class<?> bean, Executable executable, Class<? extends Annotation> type, String name, boolean absolute) {
String metric = name.isEmpty() ? bean.getSimpleName() : metricName.of(name);
return absolute ? MetricRegistry.name(metric, defaultName(executable, type)) : MetricRegistry.name(bean.getPackage().getName(), metric, defaultName(executable, type));
}
/**
* Get the metric name prepended with the caller's class name
*/
default String buildMetricName(String classSimpleName, String metricName) {
return MetricRegistry.name(classSimpleName, metricName);
}
private String getMetricName(String name) {
return MetricRegistry.name("bv.emodb.sor", "DefaultDataStore", name);
}
private String newMetric(String name) {
return MetricRegistry.name("bv.emodb.databus", "SystemQueue", name);
}
private String metricName(String name) {
String instanceId = config.getInstanceId().orElse(null);
return MetricRegistry.name(ModbusTcpMaster.class, instanceId, name);
}
private String metricName(String metric, String clusterName, String keyspaceName, UUID repairRunId) {
String cleanClusterName = clusterName.replaceAll("[^A-Za-z0-9]", "");
String cleanRepairRunId = repairRunId.toString().replaceAll("-", "");
String cleanKeyspaceName = keyspaceName.replaceAll("[^A-Za-z0-9]", "");
return MetricRegistry.name(RepairRunner.class, metric, cleanClusterName, cleanKeyspaceName, cleanRepairRunId);
}
private String newTimerName(String name) {
return MetricRegistry.name("bv.emodb.megabus", name, "readEvents");
}
/**
* {@inheritDoc}
* Example: java.sql.Connection.database.get
*/
public String getConnectionGetTimer() {
return MetricRegistry.name(Connection.class, databaseName, "get");
}
/**
* create name for metric based on specified class name
* @param clazz
* @param name
* @return
*/
public static String getName(Class<?> clazz, String name) {
return MetricRegistry.name(clazz.getCanonicalName(), name);
}