Skip to content

Instantly share code, notes, and snippets.

@dalegaspi
Last active October 25, 2017 00:20
Show Gist options
  • Save dalegaspi/98651605c02085064526b4c088c80a70 to your computer and use it in GitHub Desktop.
Save dalegaspi/98651605c02085064526b4c088c80a70 to your computer and use it in GitHub Desktop.
A new scala class for recording DropWizard Metrics artifacts as JSON with SLF4J Reporter
package com.tormund
import java.util
import java.util.concurrent.TimeUnit
import com.codahale.metrics._
import com.typesafe.scalalogging.StrictLogging
import org.json4s.DefaultFormats
/**
* an extension of the built-in SLF4J reporter to emit artifacts as JSON instead of regular string
*
* @param registry
* @param name
* @param filter
* @param rateUnit
* @param durationUnit
*/
class JsonSlf4jReporter(registry: MetricRegistry,
name: String,
filter: MetricFilter,
rateUnit: TimeUnit,
durationUnit: TimeUnit)
extends ScheduledReporter(registry: MetricRegistry,
name: String,
filter: MetricFilter,
rateUnit: TimeUnit,
durationUnit: TimeUnit) with StrictLogging {
case class TimerStats(name: String, count: Long, mean: Double, min: Double, max: Double)
/**
* emit the snapshots as JSON via SLF4J
*
* @param gauges
* @param counters
* @param histograms
* @param meters
* @param timers
*/
override def report(gauges: util.SortedMap[String, Gauge[_]],
counters: util.SortedMap[String, Counter],
histograms: util.SortedMap[String, Histogram],
meters: util.SortedMap[String, Meter],
timers: util.SortedMap[String, Timer]) = {
import org.json4s.jackson.Serialization._
import collection.JavaConverters._
implicit val formats = DefaultFormats
// obviously this is not complete but you get the idea of what we're trying to do here 😊
val stats = timers.asScala.map {
case (k, t) => (k, TimerStats(k, t.getCount,
convertDuration(t.getSnapshot.getMean),
convertDuration(t.getSnapshot.getMin),
convertDuration(t.getSnapshot.getMax)))
}
logger.info(s"${write(stats)}")
}
}
object JsonSlf4jReporter {
def apply(registry: MetricRegistry, name: String) = new JsonSlf4jReporter(registry, name, MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment