com.codahale.metrics.json.MetricsModule Java Examples

The following examples show how to use com.codahale.metrics.json.MetricsModule. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JVMMetricsServlet.java    From hermes with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #2
Source File: MetricsResource.java    From knox with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
  if (null == registry) {
    final Object registryAttr = context.getAttribute(METRICS_REGISTRY);
    if (registryAttr instanceof MetricRegistry) {
      this.registry = (MetricRegistry) registryAttr;
    } else {
      throw new IllegalStateException(String.format(Locale.ROOT, "Couldn't find a MetricRegistry instance with key %s",
          METRICS_REGISTRY));
    }
  }
  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));
  this.mapper = new ObjectMapper().registerModule(new MetricsModule(rateUnit, durationUnit,
      showSamples));
  this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN);
  log.basicInfo(String.format(Locale.ROOT, "Successfully initialized the registry '%s'", METRICS_REGISTRY));
}
 
Example #3
Source File: KafkaReporter.java    From metrics-kafka with Apache License 2.0 6 votes vote down vote up
private KafkaReporter(MetricRegistry registry, String name,
		TimeUnit rateUnit, TimeUnit durationUnit, boolean showSamples, MetricFilter filter,
		String topic, ProducerConfig config, String prefix,
		String hostName, String ip) {
	super(registry, name, filter, rateUnit, durationUnit);
	this.topic = topic;
	this.config = config;
	this.prefix = prefix;
	this.hostName = hostName;
	this.ip = ip;
	
	this.mapper = new ObjectMapper().registerModule(new MetricsModule(rateUnit,
               durationUnit,
               showSamples));

	producer = new Producer<String, String>(config);

	kafkaExecutor = Executors
			.newSingleThreadExecutor(new ThreadFactoryBuilder()
					.setNameFormat("kafka-producer-%d").build());
}
 
Example #4
Source File: AmqpReporter.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
private AmqpReporter(Builder builder) {
    super(builder.registry, "amqp-reporter", builder.filter, builder.rateUnit, builder.durationUnit);
    this.routingKey = builder.routingKey;
    this.exchangeName = builder.exchangeName;
    Assert.hasText(this.exchangeName, "exchangeName is null or empty");
    this.exchangeFactory = builder.exchangeFactory;
    this.messagePropertiesCallback = builder.messagePropertiesCallback;


    this.connectionFactoryProvider = builder.connectionFactoryProvider;
    Assert.notNull(this.connectionFactoryProvider, "connectionFactoryProvider can't be null");

    objectMapper.registerModules(new HealthCheckModule(),
      new MetricsModule(builder.rateUnit, builder.durationUnit, false /* if enable histogram data will be serialized */));
}
 
Example #5
Source File: SingularityS3BaseModule.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
@Named(METRICS_OBJECT_MAPPER)
public ObjectMapper getObjectMapper(ObjectMapper mapper) {
  return mapper.registerModule(
    new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false)
  );
}
 
Example #6
Source File: TopologyEventsMetricsCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    TopologyMetricsService service = get(TopologyMetricsService.class);

    if (outputJson()) {
        ObjectMapper mapper = new ObjectMapper()
            .registerModule(new MetricsModule(TimeUnit.SECONDS,
                                              TimeUnit.MILLISECONDS,
                                              false));
        ObjectNode result = mapper.createObjectNode();
        result = json(mapper, result, "topologyDeviceEvent",
                      service.topologyDeviceEventMetric());
        result = json(mapper, result, "topologyHostEvent",
                      service.topologyHostEventMetric());
        result = json(mapper, result, "topologyLinkEvent",
                      service.topologyLinkEventMetric());
        result = json(mapper, result, "topologyGraphEvent",
                      service.topologyGraphEventMetric());
        result = json(mapper, result, "topologyGraphReasonsEvent",
                      service.topologyGraphReasonsEventMetric());
        print("%s", result);
    } else {
        printEventMetric("Device", service.topologyDeviceEventMetric());
        printEventMetric("Host", service.topologyHostEventMetric());
        printEventMetric("Link", service.topologyLinkEventMetric());
        printEventMetric("Graph", service.topologyGraphEventMetric());
        printEventMetric("Graph Reasons",
                         service.topologyGraphReasonsEventMetric());
    }
}
 
Example #7
Source File: IntentEventsMetricsCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    IntentMetricsService service = get(IntentMetricsService.class);

    if (outputJson()) {
        ObjectMapper mapper = new ObjectMapper()
            .registerModule(new MetricsModule(TimeUnit.SECONDS,
                                              TimeUnit.MILLISECONDS,
                                              false));
        ObjectNode result = mapper.createObjectNode();
        result = json(mapper, result, "intentSubmitted",
                      service.intentSubmittedEventMetric());
        result = json(mapper, result, "intentInstalled",
                      service.intentInstalledEventMetric());
        result = json(mapper, result, "intentFailed",
                      service.intentFailedEventMetric());
        result = json(mapper, result, "intentWithdrawRequested",
                      service.intentWithdrawRequestedEventMetric());
        result = json(mapper, result, "intentWithdrawn",
                      service.intentWithdrawnEventMetric());
        result = json(mapper, result, "intentPurged",
                      service.intentPurgedEventMetric());
        print("%s", result);
    } else {
        printEventMetric("Submitted",
                         service.intentSubmittedEventMetric());
        printEventMetric("Installed",
                         service.intentInstalledEventMetric());
        printEventMetric("Failed",
                         service.intentFailedEventMetric());
        printEventMetric("Withdraw Requested",
                         service.intentWithdrawRequestedEventMetric());
        printEventMetric("Withdrawn",
                         service.intentWithdrawnEventMetric());
        printEventMetric("Purged",
                         service.intentPurgedEventMetric());
    }
}
 
Example #8
Source File: KafkaReporter.java    From metrics-kafka with Apache License 2.0 5 votes vote down vote up
private KafkaReporter(MetricRegistry registry,
                      String name,
                      MetricFilter filter,
                      TimeUnit rateUnit,
                      TimeUnit durationUnit,
                      String kafkaTopic,
                      Properties kafkaProperties) {
    super(registry, name, filter, rateUnit, durationUnit);
    this.registry = registry;
    mapper = new ObjectMapper().registerModule(new MetricsModule(rateUnit,
                                                                 durationUnit,
                                                                 false));
    this.kafkaTopic = kafkaTopic;
    kafkaProducer = new Producer<String, String>(new ProducerConfig(kafkaProperties));
}
 
Example #9
Source File: JsonFileMetricsReporter.java    From kylin with Apache License 2.0 5 votes vote down vote up
public JsonFileMetricsReporter(MetricRegistry registry, KylinConfig conf) {
    this.metricRegistry = registry;
    this.jsonWriter = new ObjectMapper()
            .registerModule(new MetricsModule(TimeUnit.MILLISECONDS, TimeUnit.MILLISECONDS, false))
            .writerWithDefaultPrettyPrinter();
    executorService = Executors.newSingleThreadScheduledExecutor();
    this.conf = conf;

    frequency = KylinConfig.getInstanceFromEnv().getMetricsReporterFrequency();
    pathString = KylinConfig.getInstanceFromEnv().getMetricsFileLocation();
    path = new Path(pathString);
}
 
Example #10
Source File: MetricsObjectMapperFactory.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper create(boolean indent) {
  ObjectMapper objectMapper = new ObjectMapper();
  // This will cause the objectmapper to not close the underlying output stream
  objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
  objectMapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
  objectMapper.registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false, MetricFilter.ALL));
  SimpleModule module = new SimpleModule();
  module.addSerializer(ExtendedMeter.class, new ExtendedMeterSerializer(TimeUnit.SECONDS));
  module.addSerializer(BigDecimal.class, new ToStringSerializer());
  objectMapper.registerModule(module);
  if (indent) {
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
  }
  return objectMapper;
}
 
Example #11
Source File: MetricsServlet.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * New instance, which will report on the supplied metrics.
 *
 * @param registry the metrics registry to provide metrics from
 */
public MetricsServlet(MetricRegistry registry) {
  super(LOGGER, MetricsServlet.class);
  this.registry = registry;

  getMapper().registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false));
}
 
Example #12
Source File: JsonFileMetricsReporter.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public JsonFileMetricsReporter(MetricRegistry registry, KylinConfig conf) {
    this.metricRegistry = registry;
    this.jsonWriter = new ObjectMapper()
            .registerModule(new MetricsModule(TimeUnit.MILLISECONDS, TimeUnit.MILLISECONDS, false))
            .writerWithDefaultPrettyPrinter();
    executorService = Executors.newSingleThreadScheduledExecutor();
    this.conf = conf;

    frequency = KylinConfig.getInstanceFromEnv().getMetricsReporterFrequency();
    pathString = KylinConfig.getInstanceFromEnv().getMetricsFileLocation();
    path = new Path(pathString);
}
 
Example #13
Source File: JsonSupplierTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void supportsModules() {
    MetricRegistry metricsRegistry = new MetricRegistry();
    metricsRegistry.register("gauge", gauge("foo"));
    metricsRegistry.counter("counter").inc(7);

    JsonSupplier supplier = JsonSupplier.create(() -> metricsRegistry, new MetricsModule(SECONDS, MILLISECONDS, false));

    assertThat(supplier.get(), matchesRegex(quote("{\"version\":\"") +
            "\\d+\\.\\d+\\.\\d+" +
            quote("\",\"gauges\":{\"gauge\":{\"value\":\"foo\"}},\"counters\":{\"counter\":{\"count\":7}},\"histograms\":{},\"meters\":{},\"timers\":{}}")));
}
 
Example #14
Source File: MetricsHandler.java    From styx with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new handler.
 *
 * @param metricRegistry  metrics registry
 * @param cacheExpiration duration for which generated page content should be cached
 */
public MetricsHandler(MetricRegistry metricRegistry, Optional<Duration> cacheExpiration) {
    this.urlMatcher = new UrlPatternRouter.Builder()
            .get(".*/metrics", new RootMetricsHandler(
                    metricRegistry,
                    cacheExpiration,
                    new MetricsModule(SECONDS, MILLISECONDS, DO_NOT_SHOW_SAMPLES),
                    new FullMetricsModule()))
            .get(".*/metrics/.*", (request, context) -> Eventual.of(filteredMetricResponse(request)))
            .build();

    this.metricRegistry = metricRegistry;
}
 
Example #15
Source File: JsonReformatterTest.java    From styx with Apache License 2.0 4 votes vote down vote up
@Test
public void createsMetricsJsonCorrectly() throws JsonProcessingException {
    MetricRegistry registry = new MetricRegistry();

    registry.counter("styx.origins.status.200").inc();
    registry.counter("styx.origins.status.500").inc(2);
    registry.counter("styx.error").inc(3);
    registry.counter("foo.bar").inc(4);

    registry.register("styx.mygauge", (Gauge<Integer>) () -> 123);

    String before = new ObjectMapper()
            .registerModule(new MetricsModule(SECONDS, MILLISECONDS, false))
            .writeValueAsString(registry);

    String after = JsonReformatter.reformat(before);

    assertThat(after, matchesRegex(quote("{\n" +
            "  \"counters\":{\n" +
            "    \"foo.bar.count\":4,\n" +
            "    \"styx\":{\n" +
            "      \"error.count\":3,\n" +
            "      \"origins.status\":{\n" +
            "          \"200.count\":1,\n" +
            "          \"500.count\":2\n" +
            "        }\n" +
            "    }\n" +
            "  },\n" +
            "  \"gauges.styx.mygauge.value\":123,\n" +
            "  \"histograms\":{\n" +
            "\n" +
            "  },\n" +
            "  \"meters\":{\n" +
            "\n" +
            "  },\n" +
            "  \"timers\":{\n" +
            "\n" +
            "  },\n" +
            "  \"version\":\"") +
            "\\d+\\.\\d+\\.\\d+" +
            quote("\"\n" +
            "}")));
}
 
Example #16
Source File: CodahaleMetrics.java    From kylin with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
public String dumpJson() throws Exception {
    ObjectMapper jsonMapper = new ObjectMapper()
            .registerModule(new MetricsModule(TimeUnit.MILLISECONDS, TimeUnit.MILLISECONDS, false));
    return jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(metricRegistry);
}
 
Example #17
Source File: AdminServerBuilder.java    From styx with Apache License 2.0 4 votes vote down vote up
private JsonHandler<DashboardData> dashboardDataHandler(StyxConfig styxConfig) {
    return new JsonHandler<>(new DashboardDataSupplier(backendServicesRegistry, environment, styxConfig),
            Optional.of(Duration.ofSeconds(10)),
            new MetricsModule(SECONDS, MILLISECONDS, false));
}
 
Example #18
Source File: MetricsSnapshotTest.java    From styx with Apache License 2.0 4 votes vote down vote up
@BeforeEach
public void setUp() throws Exception {
    registry = new CodaHaleMetricRegistry();
    jsonSupplier = JsonSupplier.create(() -> registry, new MetricsModule(SECONDS, MILLISECONDS, false));
}
 
Example #19
Source File: MetricsServletSink.java    From incubator-iotdb with Apache License 2.0 4 votes vote down vote up
public ServletContextHandler getHandler() {
  ObjectMapper mapper = new ObjectMapper()
      .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, false));
  return JettyUtil.createMetricsServletHandler(mapper, registry);
}
 
Example #20
Source File: CodahaleMetrics.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
public String dumpJson() throws Exception {
    ObjectMapper jsonMapper = new ObjectMapper()
            .registerModule(new MetricsModule(TimeUnit.MILLISECONDS, TimeUnit.MILLISECONDS, false));
    return jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(metricRegistry);
}
 
Example #21
Source File: JVMMetricsHandler.java    From styx with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a new handler.
 *
 * @param metricRegistry  metrics registry
 * @param cacheExpiration duration for which generated page content should be cached
 */
public JVMMetricsHandler(MetricRegistry metricRegistry, Optional<Duration> cacheExpiration) {
    super(new FilteredRegistry(metricRegistry), cacheExpiration, new MetricsModule(SECONDS, MILLISECONDS, DO_NOT_SHOW_SAMPLES));
}