Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.yammer.metrics.reporting;
  
  
  import java.io.File;
 import java.util.Map;
 import java.util.Set;
A reporter which periodically appends data from each metric to a metric-specific CSV file in an output directory.
 
 public class CsvReporter extends AbstractPollingReporter implements
                                                          MetricProcessor<CsvReporter.Context> {

    
Enables the CSV reporter for the default metrics registry, and causes it to write to files in outputDir with the specified period.

Parameters:
outputDir the directory in which .csv files will be created
period the period between successive outputs
unit the time unit of period
 
     public static void enable(File outputDirlong periodTimeUnit unit) {
         enable(Metrics.defaultRegistry(), outputDirperiodunit);
     }

    
Enables the CSV reporter for the given metrics registry, and causes it to write to files in outputDir with the specified period.

Parameters:
metricsRegistry the metrics registry
outputDir the directory in which .csv files will be created
period the period between successive outputs
unit the time unit of period
 
     public static void enable(MetricsRegistry metricsRegistryFile outputDirlong periodTimeUnit unit) {
         final CsvReporter reporter = new CsvReporter(metricsRegistryoutputDir);
         reporter.start(periodunit);
     }

    
The context used to output metrics.
 
     public interface Context {
        
Returns an open java.io.PrintStream for the metric with header already written to it.

Parameters:
header the CSV header
Returns:
an open java.io.PrintStream
Throws:
java.io.IOException if there is an error opening the stream or writing to it
 
         PrintStream getStream(String headerthrows IOException;
     }
 
     private final MetricPredicate predicate;
     private final File outputDir;
     private final Map<MetricNamePrintStreamstreamMap;
     private final Clock clock;
     private long startTime;

    
Creates a new CsvReporter which will write all metrics from the given com.yammer.metrics.core.MetricsRegistry to CSV files in the given output directory.

Parameters:
outputDir the directory to which files will be written
metricsRegistry the com.yammer.metrics.core.MetricsRegistry containing the metrics this reporter will report
 
     public CsvReporter(MetricsRegistry metricsRegistryFile outputDir) {
         this(metricsRegistry.outputDir);
     }

    
Creates a new CsvReporter which will write metrics from the given com.yammer.metrics.core.MetricsRegistry which match the given com.yammer.metrics.core.MetricPredicate to CSV files in the given output directory.

Parameters:
metricsRegistry the com.yammer.metrics.core.MetricsRegistry containing the metrics this reporter will report
predicate the com.yammer.metrics.core.MetricPredicate which metrics are required to match before being written to files
outputDir the directory to which files will be written
 
     public CsvReporter(MetricsRegistry metricsRegistry,
                        MetricPredicate predicate,
                        File outputDir) {
         this(metricsRegistrypredicateoutputDir, Clock.defaultClock());
     }

    
Creates a new CsvReporter which will write metrics from the given com.yammer.metrics.core.MetricsRegistry which match the given com.yammer.metrics.core.MetricPredicate to CSV files in the given output directory.

Parameters:
metricsRegistry the com.yammer.metrics.core.MetricsRegistry containing the metrics this reporter will report
predicate the com.yammer.metrics.core.MetricPredicate which metrics are required to match before being written to files
outputDir the directory to which files will be written
clock the clock used to measure time
    public CsvReporter(MetricsRegistry metricsRegistry,
                       MetricPredicate predicate,
                       File outputDir,
                       Clock clock) {
        super(metricsRegistry"csv-reporter");
        if (outputDir.exists() && !outputDir.isDirectory()) {
            throw new IllegalArgumentException(outputDir + " is not a directory");
        }
        this. = outputDir;
        this. = predicate;
        this. = new HashMap<MetricNamePrintStream>();
        this. = 0L;
        this. = clock;
    }

    
Returns an opened java.io.PrintStream for the given com.yammer.metrics.core.MetricName which outputs data to a metric-specific .csv file in the output directory.

Parameters:
metricName the name of the metric
Returns:
an opened java.io.PrintStream specific to metricName
Throws:
java.io.IOException if there is an error opening the stream
    protected PrintStream createStreamForMetric(MetricName metricNamethrows IOException {
        final File newFile = new File(metricName.getName() + ".csv");
        if (newFile.createNewFile()) {
            return new PrintStream(new FileOutputStream(newFile));
        }
        throw new IOException("Unable to create " + newFile);
    }
    @Override
    public void run() {
        final long time = ..toSeconds(.time() - );
        final Set<Entry<MetricNameMetric>> metrics = getMetricsRegistry().allMetrics().entrySet();
        try {
            for (Entry<MetricNameMetricentry : metrics) {
                final MetricName metricName = entry.getKey();
                final Metric metric = entry.getValue();
                if (.matches(metricNamemetric)) {
                    final Context context = new Context() {
                        @Override
                        public PrintStream getStream(String headerthrows IOException {
                            final PrintStream stream = getPrintStream(metricNameheader);
                            stream.print(time);
                            stream.print(',');
                            return stream;
                        }
                    };
                    metric.processWith(thisentry.getKey(), context);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void processMeter(MetricName nameMetered meterContext contextthrows IOException {
        final PrintStream stream = context.getStream(
                "# time,count,1 min rate,mean rate,5 min rate,15 min rate");
        stream.append(new StringBuilder()
                              .append(meter.count()).append(',')
                              .append(meter.oneMinuteRate()).append(',')
                              .append(meter.meanRate()).append(',')
                              .append(meter.fiveMinuteRate()).append(',')
                              .append(meter.fifteenMinuteRate()).toString())
              .println();
        stream.flush();
    }
    @Override
    public void processCounter(MetricName nameCounter counterContext contextthrows IOException {
        final PrintStream stream = context.getStream("# time,count");
        stream.println(counter.count());
        stream.flush();
    }
    @Override
    public void processHistogram(MetricName nameHistogram histogramContext contextthrows IOException {
        final PrintStream stream = context.getStream("# time,min,max,mean,median,stddev,95%,99%,99.9%");
        final Snapshot snapshot = histogram.getSnapshot();
        stream.append(new StringBuilder()
                              .append(histogram.min()).append(',')
                              .append(histogram.max()).append(',')
                              .append(histogram.mean()).append(',')
                              .append(snapshot.getMedian()).append(',')
                              .append(histogram.stdDev()).append(',')
                              .append(snapshot.get95thPercentile()).append(',')
                              .append(snapshot.get99thPercentile()).append(',')
                              .append(snapshot.get999thPercentile()).toString())
                .println();
        stream.println();
        stream.flush();
    }
    @Override
    public void processTimer(MetricName nameTimer timerContext contextthrows IOException {
        final PrintStream stream = context.getStream("# time,min,max,mean,median,stddev,95%,99%,99.9%");
        final Snapshot snapshot = timer.getSnapshot();
        stream.append(new StringBuilder()
                              .append(timer.min()).append(',')
                              .append(timer.max()).append(',')
                              .append(timer.mean()).append(',')
                              .append(snapshot.getMedian()).append(',')
                              .append(timer.stdDev()).append(',')
                              .append(snapshot.get95thPercentile()).append(',')
                              .append(snapshot.get99thPercentile()).append(',')
                              .append(snapshot.get999thPercentile()).toString())
                .println();
        stream.flush();
    }
    @Override
    public void processGauge(MetricName nameGauge<?> gaugeContext contextthrows IOException {
        final PrintStream stream = context.getStream("# time,value");
        stream.println(gauge.value());
        stream.flush();
    }
    @Override
    public void start(long periodTimeUnit unit) {
        this. = .time();
        super.start(periodunit);
    }
    @Override
    public void shutdown() {
        try {
            super.shutdown();
        } finally {
            for (PrintStream out : .values()) {
                out.close();
            }
        }
    }
    private PrintStream getPrintStream(MetricName metricNameString header)
            throws IOException {
        PrintStream stream;
        synchronized () {
            stream = .get(metricName);
            if (stream == null) {
                stream = createStreamForMetric(metricName);
                .put(metricNamestream);
                stream.println(header);
            }
        }
        return stream;
    }
New to GrepCode? Check out our FAQ X