private <T extends Metric> MetricImpl toImpl(String name, T metric) { // Find subtype of Metric, needed for user-defined metrics Class<?> clazz = metric.getClass(); do { Optional<Class<?>> optionalClass = Arrays.stream(clazz.getInterfaces()) .filter(c -> Metric.class.isAssignableFrom(c)) .findFirst(); if (optionalClass.isPresent()) { clazz = optionalClass.get(); break; } clazz = clazz.getSuperclass(); } while (clazz != null); return toImpl(new Metadata(name, MetricType.from(clazz == null ? metric.getClass() : clazz)), metric); }
@Override public int hashCode() { int result = name.hashCode(); result = 31 * result + type.hashCode(); result = 31 * result + unit.hashCode(); return result; }
public String getTypeRaw() { return value.getTypeRaw().name(); }
@Override public <T extends Metric> T register(Metadata metadata, T t) throws IllegalArgumentException { // add default tags ServiceConfigInfo configInfo = ServiceConfigInfo.getInstance(); if(configInfo.shouldAddToTags()) { metadata.addTag("environment=" + configInfo.getEnvironment()); metadata.addTag("serviceName=" + configInfo.getServiceName()); metadata.addTag("serviceVersion=" + configInfo.getServiceVersion()); metadata.addTag("instanceId=" + configInfo.getInstanceId()); } Optional<String> tagsFromConfig = ConfigurationUtil.getInstance().get("MP_METRICS_TAGS"); tagsFromConfig.ifPresent(metadata::addTags); try { metricRegistry.register(metadata.getName(), new MetricAdapter(t, metadata)); } catch (IllegalArgumentException e) { com.codahale.metrics.Metric m = metricRegistry.getMetrics().get(metadata.getName()); if (m instanceof MetricAdapter) { Metadata existingMetadata = ((MetricAdapter) m).getMetadata(); if (existingMetadata.isReusable() && metadata.isReusable() && existingMetadata.getTypeRaw().equals(metadata.getTypeRaw())) { return t; } else { throw e; } } } return t; }
/** * Sets the metric type using a String representation of {@link MetricType}. * @param type the new metric type * @throws IllegalArgumentException if the String is not a valid {@link MetricType} */ public void setType(String type) throws IllegalArgumentException { this.type = MetricType.from(type); }
@Override public <T extends Metric> T register(String name, T t) throws IllegalArgumentException { return register(new Metadata(name, MetricType.from(t.getClass())), t); }