All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sksamuel.scruffy.metrics.metrics.scala Maven / Gradle / Ivy

There is a newer version: 1.14.0
Show newest version
package com.sksamuel.scruffy.metrics

import java.io.File
import java.util.concurrent.TimeUnit

import com.codahale.metrics._
import com.sksamuel.scruffy.HttpModule
import com.sksamuel.scruffy.http.Serializer

import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration._

class BasicMetricsModule(implicit val executor: ExecutionContext) extends HttpModule {

  protected def createRegistry = new MetricRegistry
  protected def metricExcludes = Set("/metrics.json", "/metrics.xml")
  protected def metricsListener = new MetricsListener(registry, metricExcludes)
  protected lazy val registry = createRegistry

  add(metricsListener)
}

class MetricsModule(implicit executor: ExecutionContext, serializer: Serializer[MetricsResult])
  extends BasicMetricsModule {

  import scala.collection.JavaConverters._

  get("metrics.json") { req =>
    Future.successful {
      ok.json(MetricsResult(registry.getMetrics.asScala.toMap))
    }
  }

  get("metrics.xml") { req =>
    Future.successful {
      ok.xml(MetricsResult(registry.getMetrics.asScala.toMap))
    }
  }
}

trait MetricsJmxSupport {
  self: BasicMetricsModule =>

  private val _jmxreporter =
    JmxReporter
      .forRegistry(registry)
      .convertRatesTo(TimeUnit.SECONDS)
      .convertDurationsTo(TimeUnit.MILLISECONDS)
      .build()

  _jmxreporter.start()
}

trait MetricsCsvSupport {
  self: BasicMetricsModule =>

  def metricsCsvReporterInterval: FiniteDuration = 1.seconds
  def metricsCsvOutputFile: File = new File("metrics.csv")

  private val _jmxreporter =
    CsvReporter
      .forRegistry(registry)
      .convertRatesTo(TimeUnit.SECONDS)
      .convertDurationsTo(TimeUnit.MILLISECONDS)
      .build(metricsCsvOutputFile)

  _jmxreporter.start(metricsCsvReporterInterval.toMillis, TimeUnit.MILLISECONDS)
}

trait MetricsConsoleSupport {
  self: BasicMetricsModule =>

  def metricsConsoleReporterInterval: FiniteDuration = 1.seconds

  private val _consolereporter =
    ConsoleReporter
      .forRegistry(registry)
      .convertRatesTo(TimeUnit.SECONDS)
      .convertDurationsTo(TimeUnit.MILLISECONDS)
      .build()

  _consolereporter.start(metricsConsoleReporterInterval.toMillis, TimeUnit.MILLISECONDS)
}

trait MetricsSlf4jSupport {
  self: BasicMetricsModule =>

  def metricsSlf4jReporterInterval: FiniteDuration = 1.seconds

  private val _slf4jreporter =
    Slf4jReporter
      .forRegistry(registry)
      .convertRatesTo(TimeUnit.SECONDS)
      .convertDurationsTo(TimeUnit.MILLISECONDS)
      .build()

  _slf4jreporter.start(metricsSlf4jReporterInterval.toMillis, TimeUnit.MILLISECONDS)
}






© 2015 - 2024 Weber Informatics LLC | Privacy Policy