Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.yammer.metrics.reporting;
  
 
 import java.util.Map;
An HTTP servlet which outputs the metrics in a com.yammer.metrics.core.MetricsRegistry (and optionally the data provided by com.yammer.metrics.core.VirtualMachineMetrics) in a JSON object. Only responds to GET requests.

If the servlet context has an attribute named com.yammer.metrics.reporting.MetricsServlet.registry which is a com.yammer.metrics.core.MetricsRegistry instance, MetricsServlet will use it instead of com.yammer.metrics.Metrics.

MetricsServlet also takes an initialization parameter, show-jvm-metrics, which should be a boolean value (e.g., "true" or "false"). It determines whether or not JVM-level metrics will be included in the JSON output.

GET requests to MetricsServlet can make use of the following query-string parameters:

/metrics?class=com.example.service
class is a string used to filter the metrics in the JSON by metric name. In the given example, only metrics for classes whose canonical name starts with com.example.service would be shown. You can also use jvm for just the JVM-level metrics.
/metrics?pretty=true
pretty determines whether or not the JSON which is returned is printed with indented whitespace or not. If you're looking at the JSON in the browser, use this.
/metrics?full-samples=true
full-samples determines whether or not the JSON which is returned will include the full content of histograms' and timers' reservoir samples. If you're aggregating across hosts, you may want to do this to allow for more accurate quantile calculations.
 
 public class MetricsServlet extends HttpServlet implements MetricProcessor<MetricsServlet.Context> {

    
The attribute name of the com.yammer.metrics.core.MetricsRegistry instance in the servlet context.
 
     public static final String REGISTRY_ATTRIBUTE = MetricsServlet.class.getName() + ".registry";

    
The attribute name of the com.fasterxml.jackson.core.JsonFactory instance in the servlet context.
 
     public static final String JSON_FACTORY_ATTRIBUTE = JsonFactory.class.getCanonicalName();

    
The initialization parameter name which determines whether or not JVM_level metrics will be included in the JSON output.
 
     public static final String SHOW_JVM_METRICS = "show-jvm-metrics";
 
     static final class Context {
         final boolean showFullSamples;
         final JsonGenerator json;
 
         Context(JsonGenerator jsonboolean showFullSamples) {
             this. = json;
             this. = showFullSamples;
         }
     }
 
     private static final JsonFactory DEFAULT_JSON_FACTORY = new JsonFactory(new ObjectMapper());
     private static final Logger LOGGER = LoggerFactory.getLogger(MetricsServlet.class);
     private static final String CONTENT_TYPE = "application/json";
 
     private final Clock clock;
     private final VirtualMachineMetrics vm;
     private MetricsRegistry registry;
     private JsonFactory factory;
     private boolean showJvmMetrics;

    
Creates a new MetricsServlet.
    public MetricsServlet() {
        this(Clock.defaultClock(), VirtualMachineMetrics.getInstance(),
             Metrics.defaultRegistry(), true);
    }

    
Creates a new MetricsServlet.

Parameters:
showJvmMetrics whether or not JVM-level metrics will be included in the output
    public MetricsServlet(boolean showJvmMetrics) {
        this(Clock.defaultClock(), VirtualMachineMetrics.getInstance(),
             Metrics.defaultRegistry(), showJvmMetrics);
    }

    
Creates a new MetricsServlet.

Parameters:
clock the clock used for the current time
vm a com.yammer.metrics.core.VirtualMachineMetrics instance
registry a com.yammer.metrics.core.MetricsRegistry
factory a com.fasterxml.jackson.core.JsonFactory
showJvmMetrics whether or not JVM-level metrics will be included in the output
    public MetricsServlet(Clock clock,
                          VirtualMachineMetrics vm,
                          MetricsRegistry registry,
                          JsonFactory factory,
                          boolean showJvmMetrics) {
        this. = clock;
        this. = vm;
        this. = registry;
        this. = factory;
        this. = showJvmMetrics;
    }
    @Override
    public void init(ServletConfig configthrows ServletException {
        final Object factory = config.getServletContext()
                                     .getAttribute();
        if (factory instanceof JsonFactory) {
            this. = (JsonFactoryfactory;
        }
        final Object o = config.getServletContext().getAttribute();
        if (o instanceof MetricsRegistry) {
            this. = (MetricsRegistryo;
        }
        final String showJvmMetricsParam = config.getInitParameter();
        if (showJvmMetricsParam != null) {
            this. = Boolean.parseBoolean(showJvmMetricsParam);
        }
    }
    @Override
    protected void doGet(HttpServletRequest reqHttpServletResponse respthrows ServletExceptionIOException {
        final String classPrefix = req.getParameter("class");
        final boolean pretty = Boolean.parseBoolean(req.getParameter("pretty"));
        final boolean showFullSamples = Boolean.parseBoolean(req.getParameter("full-samples"));
        resp.setStatus(.);
        resp.setContentType();
        final OutputStream output = resp.getOutputStream();
        final JsonGenerator json = .createJsonGenerator(output.);
        if (pretty) {
            json.useDefaultPrettyPrinter();
        }
        json.writeStartObject();
        {
            if ( && ("jvm".equals(classPrefix) || classPrefix == null)) {
                writeVmMetrics(json);
            }
            writeRegularMetrics(jsonclassPrefixshowFullSamples);
        }
        json.writeEndObject();
        json.close();
    }
    private void writeVmMetrics(JsonGenerator jsonthrows IOException {
        json.writeFieldName("jvm");
        json.writeStartObject();
        {
            json.writeFieldName("vm");
            json.writeStartObject();
            {
                json.writeStringField("name".name());
                json.writeStringField("version".version());
            }
            json.writeEndObject();
            json.writeFieldName("memory");
            json.writeStartObject();
            {
                json.writeNumberField("totalInit".totalInit());
                json.writeNumberField("totalUsed".totalUsed());
                json.writeNumberField("totalMax".totalMax());
                json.writeNumberField("totalCommitted".totalCommitted());
                json.writeNumberField("heapInit".heapInit());
                json.writeNumberField("heapUsed".heapUsed());
                json.writeNumberField("heapMax".heapMax());
                json.writeNumberField("heapCommitted".heapCommitted());
                json.writeNumberField("heap_usage".heapUsage());
                json.writeNumberField("non_heap_usage".nonHeapUsage());
                json.writeFieldName("memory_pool_usages");
                json.writeStartObject();
                {
                    for (Map.Entry<StringDoublepool : .memoryPoolUsage().entrySet()) {
                        json.writeNumberField(pool.getKey(), pool.getValue());
                    }
                }
                json.writeEndObject();
            }
            json.writeEndObject();
            final Map<StringVirtualMachineMetrics.BufferPoolStatsbufferPoolStats = .getBufferPoolStats();
            if (!bufferPoolStats.isEmpty()) {
                json.writeFieldName("buffers");
                json.writeStartObject();
                {
                    json.writeFieldName("direct");
                    json.writeStartObject();
                    {
                        json.writeNumberField("count"bufferPoolStats.get("direct").getCount());
                        json.writeNumberField("memoryUsed"bufferPoolStats.get("direct").getMemoryUsed());
                        json.writeNumberField("totalCapacity"bufferPoolStats.get("direct").getTotalCapacity());
                    }
                    json.writeEndObject();
                    json.writeFieldName("mapped");
                    json.writeStartObject();
                    {
                        json.writeNumberField("count"bufferPoolStats.get("mapped").getCount());
                        json.writeNumberField("memoryUsed"bufferPoolStats.get("mapped").getMemoryUsed());
                        json.writeNumberField("totalCapacity"bufferPoolStats.get("mapped").getTotalCapacity());
                    }
                    json.writeEndObject();
                }
                json.writeEndObject();
            }
            json.writeNumberField("daemon_thread_count".daemonThreadCount());
            json.writeNumberField("thread_count".threadCount());
            json.writeNumberField("current_time".time());
            json.writeNumberField("uptime".uptime());
            json.writeNumberField("fd_usage".fileDescriptorUsage());
            json.writeFieldName("thread-states");
            json.writeStartObject();
            {
                for (Map.Entry<Thread.StateDoubleentry : .threadStatePercentages()
                                                               .entrySet()) {
                    json.writeNumberField(entry.getKey().toString().toLowerCase(),
                                          entry.getValue());
                }
            }
            json.writeEndObject();
            json.writeFieldName("garbage-collectors");
            json.writeStartObject();
            {
                for (Map.Entry<StringVirtualMachineMetrics.GarbageCollectorStatsentry : .garbageCollectors()
                                                                                              .entrySet()) {
                    json.writeFieldName(entry.getKey());
                    json.writeStartObject();
                    {
                        final VirtualMachineMetrics.GarbageCollectorStats gc = entry.getValue();
                        json.writeNumberField("runs"gc.getRuns());
                        json.writeNumberField("time"gc.getTime(.));
                    }
                    json.writeEndObject();
                }
            }
            json.writeEndObject();
        }
        json.writeEndObject();
    }
    public void writeRegularMetrics(JsonGenerator jsonString classPrefixboolean showFullSamplesthrows IOException {
        for (Map.Entry<StringSortedMap<MetricNameMetric>> entry : .groupedMetrics().entrySet()) {
            if (classPrefix == null || entry.getKey().startsWith(classPrefix)) {
                json.writeFieldName(entry.getKey());
                json.writeStartObject();
                {
                    for (Map.Entry<MetricNameMetricsubEntry : entry.getValue().entrySet()) {
                        json.writeFieldName(subEntry.getKey().getName());
                        try {
                            subEntry.getValue()
                                    .processWith(this,
                                                 subEntry.getKey(),
                                                 new Context(jsonshowFullSamples));
                        } catch (Exception e) {
                            .warn("Error writing out {}"subEntry.getKey(), e);
                        }
                    }
                }
                json.writeEndObject();
            }
        }
    }
    @Override
    public void processHistogram(MetricName nameHistogram histogramContext contextthrows Exception {
        final JsonGenerator json = context.json;
        json.writeStartObject();
        {
            json.writeStringField("type""histogram");
            json.writeNumberField("count"histogram.count());
            writeSummarizable(histogramjson);
            writeSampling(histogramjson);
            if (context.showFullSamples) {
                json.writeObjectField("values"histogram.getSnapshot().getValues());
            }
        }
        json.writeEndObject();
    }
    @Override
    public void processCounter(MetricName nameCounter counterContext contextthrows Exception {
        final JsonGenerator json = context.json;
        json.writeStartObject();
        {
            json.writeStringField("type""counter");
            json.writeNumberField("count"counter.count());
        }
        json.writeEndObject();
    }
    @Override
    public void processGauge(MetricName nameGauge<?> gaugeContext contextthrows Exception {
        final JsonGenerator json = context.json;
        json.writeStartObject();
        {
            json.writeStringField("type""gauge");
            json.writeObjectField("value"evaluateGauge(gauge));
        }
        json.writeEndObject();
    }
    @Override
    public void processMeter(MetricName nameMetered meterContext contextthrows Exception {
        final JsonGenerator json = context.json;
        json.writeStartObject();
        {
            json.writeStringField("type""meter");
            json.writeStringField("event_type"meter.eventType());
            writeMeteredFields(meterjson);
        }
        json.writeEndObject();
    }
    @Override
    public void processTimer(MetricName nameTimer timerContext contextthrows Exception {
        final JsonGenerator json = context.json;
        json.writeStartObject();
        {
            json.writeStringField("type""timer");
            json.writeFieldName("duration");
            json.writeStartObject();
            {
                json.writeStringField("unit"timer.durationUnit().toString().toLowerCase());
                writeSummarizable(timerjson);
                writeSampling(timerjson);
                if (context.showFullSamples) {
                    json.writeObjectField("values"timer.getSnapshot().getValues());
                }
            }
            json.writeEndObject();
            json.writeFieldName("rate");
            json.writeStartObject();
            {
                writeMeteredFields(timerjson);
            }
            json.writeEndObject();
        }
        json.writeEndObject();
    }
    private static Object evaluateGauge(Gauge<?> gauge) {
        try {
            return gauge.value();
        } catch (RuntimeException e) {
            .warn("Error evaluating gauge"e);
            return "error reading gauge: " + e.getMessage();
        }
    }
    private static void writeSummarizable(Summarizable metricJsonGenerator jsonthrows IOException {
        json.writeNumberField("min"metric.min());
        json.writeNumberField("max"metric.max());
        json.writeNumberField("mean"metric.mean());
        json.writeNumberField("std_dev"metric.stdDev());
    }
    private static void writeSampling(Sampling metricJsonGenerator jsonthrows IOException {
        final Snapshot snapshot = metric.getSnapshot();
        json.writeNumberField("median"snapshot.getMedian());
        json.writeNumberField("p75"snapshot.get75thPercentile());
        json.writeNumberField("p95"snapshot.get95thPercentile());
        json.writeNumberField("p98"snapshot.get98thPercentile());
        json.writeNumberField("p99"snapshot.get99thPercentile());
        json.writeNumberField("p999"snapshot.get999thPercentile());
    }
    private static void writeMeteredFields(Metered meteredJsonGenerator jsonthrows IOException {
        json.writeStringField("unit"metered.rateUnit().toString().toLowerCase());
        json.writeNumberField("count"metered.count());
        json.writeNumberField("mean"metered.meanRate());
        json.writeNumberField("m1"metered.oneMinuteRate());
        json.writeNumberField("m5"metered.fiveMinuteRate());
        json.writeNumberField("m15"metered.fifteenMinuteRate());
    }
New to GrepCode? Check out our FAQ X