当前位置: 首页>>代码示例>>Scala>>正文


Scala MetricRegistry类代码示例

本文整理汇总了Scala中com.codahale.metrics.MetricRegistry的典型用法代码示例。如果您正苦于以下问题:Scala MetricRegistry类的具体用法?Scala MetricRegistry怎么用?Scala MetricRegistry使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了MetricRegistry类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: Metrics

//设置package包名称以及导入依赖的类
package com.onur.moviedb.metric

import java.lang.management.ManagementFactory
import java.util.concurrent.TimeUnit

import com.codahale.metrics.health.HealthCheckRegistry
import com.codahale.metrics.{JmxReporter, MetricRegistry, Slf4jReporter}
import com.codahale.metrics.jvm.{BufferPoolMetricSet, GarbageCollectorMetricSet, MemoryUsageGaugeSet, ThreadStatesGaugeSet}
import org.slf4j.LoggerFactory


object Metrics {
  lazy val metricRegistry: MetricRegistry = {
    val metricRegistry: MetricRegistry = new MetricRegistry
    Slf4jReporter.forRegistry(metricRegistry)
      .outputTo(LoggerFactory.getLogger("metrics"))
      .convertRatesTo(TimeUnit.SECONDS)
      .convertDurationsTo(TimeUnit.MILLISECONDS)
      .build
      .start(30, TimeUnit.SECONDS)
    JmxReporter.forRegistry(metricRegistry).build.start()
    metricRegistry.register("jvm-gc", new GarbageCollectorMetricSet)
    metricRegistry.register("jvm-buffer", new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer))
    metricRegistry.register("jvm-memory", new MemoryUsageGaugeSet)
    metricRegistry.register("jvm-threads", new ThreadStatesGaugeSet)
    metricRegistry
  }

  lazy val healthCheckRegistry = new HealthCheckRegistry
} 
开发者ID:onurzdg,项目名称:movie-db,代码行数:31,代码来源:Metrics.scala

示例2: givenCleanMetricRegistry

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentmapping.support

import com.codahale.metrics.MetricRegistry
import com.kenshoo.play.metrics.Metrics
import org.scalatest.Matchers
import org.scalatestplus.play.OneAppPerSuite

import scala.collection.JavaConversions

trait MetricTestSupport {
  self: OneAppPerSuite with Matchers =>

  private var metricsRegistry: MetricRegistry = _

  def givenCleanMetricRegistry(): Unit = {
    val registry = app.injector.instanceOf[Metrics].defaultRegistry
    for (metric <- JavaConversions.asScalaIterator[String](registry.getMetrics.keySet().iterator())) {
      registry.remove(metric)
    }
    metricsRegistry = registry
  }

  def timerShouldExistsAndBeenUpdated(metric: String): Unit = {
    metricsRegistry.getTimers.get(s"Timer-$metric").getCount should be >= 1L
  }

} 
开发者ID:hmrc,项目名称:agent-mapping,代码行数:28,代码来源:MetricTestSupport.scala

示例3: givenCleanMetricRegistry

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentaccesscontrol.support

import com.codahale.metrics.MetricRegistry
import com.kenshoo.play.metrics.Metrics
import org.scalatest.Matchers
import org.scalatestplus.play.OneAppPerSuite

import scala.collection.JavaConversions

trait MetricTestSupport {
  self: OneAppPerSuite with Matchers =>

  private var metricsRegistry: MetricRegistry = _

  def givenCleanMetricRegistry(): Unit = {
    val registry = app.injector.instanceOf[Metrics].defaultRegistry
    for (metric <- JavaConversions.asScalaIterator[String](registry.getMetrics.keySet().iterator())) {
      registry.remove(metric)
    }
    metricsRegistry = registry
  }

  def timerShouldExistsAndBeenUpdated(metric: String): Unit = {
    metricsRegistry.getTimers.get(s"Timer-$metric").getCount should be >= 1L
  }

} 
开发者ID:hmrc,项目名称:agent-access-control,代码行数:28,代码来源:MetricTestSupport.scala

示例4: CHMetricsStatsReceiver

//设置package包名称以及导入依赖的类
package org.http4s.finagle

import com.codahale.metrics.{ Gauge, MetricRegistry }
import com.twitter.finagle.stats.{ Counter, Stat, StatsReceiver, Gauge => FGauge }

import scalaz.syntax.id._

class CHMetricsStatsReceiver(registry: MetricRegistry, prefix: String) extends StatsReceiver {
  override val repr: AnyRef = this

  override def counter(names: String*): Counter =
    registry.counter(format(names)) |> { c =>
      new Counter {
        override def incr(delta: Int): Unit = c.inc(delta.toLong)
      }
    }

  override def addGauge(names: String*)(f: => Float): FGauge =
    format(names) |> { name =>
      registry.register(format(names), new Gauge[Float] {
        override def getValue: Float = f
      }) |> { g =>
        new FGauge {
          override def remove(): Unit = { registry.remove(name); () }
        }
      }
    }

  override def stat(names: String*): Stat =
    registry.histogram(format(names)) |> { h =>
      new Stat {
        override def add(value: Float): Unit = h.update(value.toLong)
      }
    }

  private def format(names: Seq[String]): String =
    (prefix +: names).mkString(".")
} 
开发者ID:lukiano,项目名称:finagle-http4s,代码行数:39,代码来源:CHMetricsStatsReceiver.scala

示例5: app

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentrelationships.support

import com.codahale.metrics.MetricRegistry
import com.kenshoo.play.metrics.Metrics
import org.scalatest.{Matchers, Suite}
import play.api.Application

import scala.collection.JavaConversions

trait MetricTestSupport {
  self: Suite with Matchers =>

  def app: Application

  private var metricsRegistry: MetricRegistry = _

  def givenCleanMetricRegistry(): Unit = {
    val registry = app.injector.instanceOf[Metrics].defaultRegistry
    for (metric <- JavaConversions.asScalaIterator[String](registry.getMetrics.keySet().iterator())) {
      registry.remove(metric)
    }
    metricsRegistry = registry
  }

  def timerShouldExistsAndBeenUpdated(metric: String): Unit = {
    metricsRegistry.getTimers.get(s"Timer-$metric").getCount should be >= 1L
  }

} 
开发者ID:hmrc,项目名称:agent-client-relationships,代码行数:30,代码来源:MetricTestSupport.scala

示例6: PseudoElectionService

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.election.impl

import akka.actor.ActorSystem
import akka.event.EventStream
import com.codahale.metrics.MetricRegistry
import mesosphere.marathon.core.base.ShutdownHooks
import mesosphere.marathon.metrics.Metrics
import org.slf4j.LoggerFactory

class PseudoElectionService(
  system: ActorSystem,
  eventStream: EventStream,
  metrics: Metrics = new Metrics(new MetricRegistry),
  hostPort: String,
  backoff: ExponentialBackoff,
  shutdownHooks: ShutdownHooks) extends ElectionServiceBase(
  system, eventStream, metrics, backoff, shutdownHooks
) {
  private val log = LoggerFactory.getLogger(getClass.getName)

  override def leaderHostPortImpl: Option[String] = if (isLeader) Some(hostPort) else None

  override def offerLeadershipImpl(): Unit = synchronized {
    log.info("Not using HA and therefore electing as leader by default")
    startLeadership(_ => stopLeadership())
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:28,代码来源:PseudoElectionService.scala

示例7: ElectionModule

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.election

import akka.actor.ActorSystem
import akka.event.EventStream
import com.codahale.metrics.MetricRegistry
import mesosphere.marathon.MarathonConf
import mesosphere.marathon.core.base.ShutdownHooks
import mesosphere.marathon.core.election.impl.{ CuratorElectionService, ExponentialBackoff, PseudoElectionService, TwitterCommonsElectionService }
import mesosphere.marathon.metrics.Metrics

class ElectionModule(
    config: MarathonConf,
    system: ActorSystem,
    eventStream: EventStream,
    metrics: Metrics = new Metrics(new MetricRegistry),
    hostPort: String,
    shutdownHooks: ShutdownHooks) {

  private lazy val backoff = new ExponentialBackoff(name = "offerLeadership")
  lazy val service: ElectionService = if (config.highlyAvailable()) {
    config.leaderElectionBackend.get match {
      case Some("twitter_commons") =>
        new TwitterCommonsElectionService(
          config,
          system,
          eventStream,
          metrics,
          hostPort,
          backoff,
          shutdownHooks
        )
      case Some("curator") =>
        new CuratorElectionService(
          config,
          system,
          eventStream,
          metrics,
          hostPort,
          backoff,
          shutdownHooks
        )
      case backend: Option[String] =>
        throw new IllegalArgumentException(s"Leader election backend $backend not known!")
    }
  } else {
    new PseudoElectionService(
      system,
      eventStream,
      metrics,
      hostPort,
      backoff,
      shutdownHooks
    )
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:56,代码来源:ElectionModule.scala

示例8: SystemResource

//设置package包名称以及导入依赖的类
package mesosphere.marathon.api

import java.io.StringWriter
import java.util.concurrent.TimeUnit
import javax.servlet.http.HttpServletRequest
import javax.ws.rs._
import javax.ws.rs.core.{ Context, MediaType, Response }

import com.codahale.metrics.{ MetricFilter, MetricRegistry }
import com.codahale.metrics.annotation.Timed
import com.codahale.metrics.json.MetricsModule
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.inject.Inject
import mesosphere.marathon.MarathonConf
import mesosphere.marathon.io.IO
import mesosphere.marathon.plugin.auth.AuthorizedResource.SystemConfig
import mesosphere.marathon.plugin.auth.{ Authenticator, Authorizer, ViewResource }


@Path("")
@Consumes(Array(MediaType.APPLICATION_JSON))
@Produces(Array(MarathonMediaType.PREFERRED_APPLICATION_JSON))
class SystemResource @Inject() (metrics: MetricRegistry, val config: MarathonConf)(implicit
  val authenticator: Authenticator,
    val authorizer: Authorizer) extends RestResource with AuthResource {

  private[this] lazy val mapper = new ObjectMapper().registerModule(
    new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false, MetricFilter.ALL)
  )

  @GET
  @Path("ping")
  @Timed
  def ping(@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
    withAuthorization(ViewResource, SystemConfig){
      ok("pong")
    }
  }

  @GET
  @Path("metrics")
  @Timed
  def metrics(@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
    withAuthorization(ViewResource, SystemConfig){
      IO.using(new StringWriter()) { writer =>
        mapper.writer().writeValue(writer, metrics)
        ok(writer.toString)
      }
    }
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:52,代码来源:SystemResource.scala

示例9: InMemTestClass1Resolver

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.storage.store.impl

import java.time.OffsetDateTime

import com.codahale.metrics.MetricRegistry
import mesosphere.AkkaUnitTest
import mesosphere.marathon.core.storage.store.impl.memory.{ InMemoryPersistenceStore, RamId }
import mesosphere.marathon.core.storage.store.{ IdResolver, PersistenceStoreTest, TestClass1 }
import mesosphere.marathon.metrics.Metrics
import mesosphere.marathon.storage.store.InMemoryStoreSerialization

trait InMemoryTestClass1Serialization {
  implicit object InMemTestClass1Resolver extends IdResolver[String, TestClass1, String, RamId] {
    override def toStorageId(id: String, version: Option[OffsetDateTime]): RamId =
      RamId(category, id, version)
    override val category: String = "test-class"
    override val hasVersions = true

    override def fromStorageId(key: RamId): String = key.id
    override def version(v: TestClass1): OffsetDateTime = v.version
  }
}

class InMemoryPersistenceStoreTest extends AkkaUnitTest with PersistenceStoreTest
    with InMemoryStoreSerialization with InMemoryTestClass1Serialization {

  implicit val metrics = new Metrics(new MetricRegistry)

  behave like basicPersistenceStore("InMemoryPersistenceStore", new InMemoryPersistenceStore())
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:31,代码来源:InMemoryPersistenceStoreTest.scala

示例10: LoadTimeCachingPersistenceStoreTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.storage.store.impl.cache

import java.util.UUID

import com.codahale.metrics.MetricRegistry
import mesosphere.AkkaUnitTest
import mesosphere.marathon.core.storage.store.PersistenceStoreTest
import mesosphere.marathon.core.storage.store.impl.InMemoryTestClass1Serialization
import mesosphere.marathon.core.storage.store.impl.memory.InMemoryPersistenceStore
import mesosphere.marathon.core.storage.store.impl.zk.{ ZkPersistenceStore, ZkTestClass1Serialization }
import mesosphere.marathon.integration.setup.ZookeeperServerTest
import mesosphere.marathon.metrics.Metrics
import mesosphere.marathon.storage.store.InMemoryStoreSerialization

import scala.concurrent.duration.Duration

class LoadTimeCachingPersistenceStoreTest extends AkkaUnitTest
    with PersistenceStoreTest with ZookeeperServerTest with ZkTestClass1Serialization
    with InMemoryStoreSerialization with InMemoryTestClass1Serialization {

  def zkStore: ZkPersistenceStore = {
    implicit val metrics = new Metrics(new MetricRegistry)

    val root = UUID.randomUUID().toString
    val rootZkClient = zkClient(namespace = Some(root))
    new ZkPersistenceStore(rootZkClient, Duration.Inf)
  }

  private def cachedInMemory = {
    implicit val metrics = new Metrics(new MetricRegistry)
    val store = new LoadTimeCachingPersistenceStore(new InMemoryPersistenceStore())
    store.preDriverStarts.futureValue
    store
  }

  private def cachedZk = {
    val store = new LoadTimeCachingPersistenceStore(zkStore)
    store.preDriverStarts.futureValue
    store
  }

  behave like basicPersistenceStore("LoadTime(InMemory)", cachedInMemory)
  behave like basicPersistenceStore("LoadTime(Zk)", cachedZk)
  // TODO: Mock out the backing store
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:46,代码来源:LoadTimeCachingPersistenceStoreTest.scala

示例11: TestGroupManagerFixture

//设置package包名称以及导入依赖的类
package mesosphere.marathon
package api

import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Provider

import akka.event.EventStream
import com.codahale.metrics.MetricRegistry
import mesosphere.marathon.core.group.GroupManagerModule
import mesosphere.marathon.core.leadership.AlwaysElectedLeadershipModule
import mesosphere.marathon.io.storage.StorageProvider
import mesosphere.marathon.metrics.Metrics
import mesosphere.marathon.storage.repository.{ AppRepository, GroupRepository, PodRepository }
import mesosphere.marathon.test.{ MarathonActorSupport, Mockito }
import mesosphere.marathon.util.WorkQueue

class TestGroupManagerFixture extends Mockito with MarathonActorSupport {
  val service = mock[MarathonSchedulerService]
  val groupRepository = mock[GroupRepository]
  val podRepository = mock[PodRepository]
  val appRepository = mock[AppRepository]
  val eventBus = mock[EventStream]
  val provider = mock[StorageProvider]

  val config = AllConf.withTestConfig("--zk_timeout", "1000")

  val metricRegistry = new MetricRegistry()
  val metrics = new Metrics(metricRegistry)

  val actorId = new AtomicInteger(0)

  val schedulerProvider = new Provider[DeploymentService] {
    override def get() = service
  }

  private[this] val groupManagerModule = new GroupManagerModule(
    config = config,
    AlwaysElectedLeadershipModule.forActorSystem(system),
    serializeUpdates = WorkQueue("serializeGroupUpdates", 1, 10),
    scheduler = schedulerProvider,
    groupRepo = groupRepository,
    appRepo = appRepository,
    podRepo = podRepository,
    storage = provider,
    eventBus = eventBus,
    metrics = metrics)

  val groupManager = groupManagerModule.groupManager
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:50,代码来源:TestGroupManagerFixture.scala

示例12: PodRepositoryTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.storage.repository

import java.util.UUID

import com.codahale.metrics.MetricRegistry
import mesosphere.AkkaUnitTest
import mesosphere.marathon.core.pod.PodDefinition
import mesosphere.marathon.core.storage.store.impl.zk.ZkPersistenceStore
import mesosphere.marathon.integration.setup.ZookeeperServerTest
import mesosphere.marathon.metrics.Metrics
import mesosphere.marathon.state.PathId

import scala.concurrent.duration.Duration

// small test to make sure pod serialization/deserialization in ZK is functioning.
class PodRepositoryTest extends AkkaUnitTest with ZookeeperServerTest {
  import PathId._

  "PodRepository" should {
    "store and retrieve pods" in {
      val pod = PodDefinition("a".toRootPath)
      val f = new Fixture()
      f.repo.store(pod).futureValue
      f.repo.get(pod.id).futureValue.value should equal(pod)
    }
    "store and retrieve pods with executor resources" in {
      val pod = PodDefinition("a".toRootPath, executorResources = PodDefinition.DefaultExecutorResources.copy(cpus = 10))
      val f = new Fixture()
      f.repo.store(pod).futureValue
      f.repo.get(pod.id).futureValue.value should equal(pod)
    }
  }

  class Fixture {
    implicit val metrics = new Metrics(new MetricRegistry)
    val root = UUID.randomUUID().toString
    val rootClient = zkClient(namespace = Some(root))
    val store = new ZkPersistenceStore(rootClient, Duration.Inf)
    val repo = PodRepository.zkRepository(store)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:42,代码来源:PodRepositoryTest.scala

示例13: GraphiteOptions

//设置package包名称以及导入依赖的类
package eu.inn.metrics.loaders

import java.net.InetAddress
import java.util.concurrent.TimeUnit

import com.codahale.metrics.MetricRegistry
import com.codahale.metrics.graphite.{Graphite, GraphiteReporter}
import com.typesafe.config.Config
import eu.inn.binders.tconfig._
import org.slf4j.LoggerFactory

import scala.concurrent.duration.Duration
import scala.util.Try

case class GraphiteOptions(enabled: Boolean,
                           host: String,
                           port: Int,
                           prefix: String,
                           hostSuffix: Option[String],
                           reportPeriod: Duration
                          )

class GraphiteReporterLoader(options: GraphiteOptions, registry: MetricRegistry) extends MetricsReporterLoader {
  val log = LoggerFactory.getLogger(getClass)
  def this(config: Config, registry: MetricRegistry) = this(config.getValue("graphite-reporter").read[GraphiteOptions], registry)

  def run() : Unit = {
    if (options.enabled) {
      val prefix = Seq(options.prefix, Try {
        InetAddress.getLocalHost.getHostName
      } getOrElse {
        "unknown-host"
      }.replaceAll("\\.", "-") + options.hostSuffix.fold("")("-" + _)).filter(_.trim.nonEmpty).mkString(".")

      log.info(s"Starting graphite reporter / $options")

      val graphite = new Graphite(options.host, options.port)
      val reporter = GraphiteReporter.forRegistry(registry).prefixedWith(prefix).build(graphite)
      reporter.start(options.reportPeriod.toMillis, TimeUnit.MILLISECONDS)
    } else {
      log.info("Graphite reporter is disabled")
    }
  }
} 
开发者ID:InnovaCo,项目名称:service-metrics-graphite,代码行数:45,代码来源:GraphiteReporterLoader.scala

示例14: CustomDirectivesServer

//设置package包名称以及导入依赖的类
package com.packt.chapter9

import java.util.concurrent.TimeUnit

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.HttpApp
import akka.http.scaladsl.settings.ServerSettings
import com.codahale.metrics.{ConsoleReporter, MetricRegistry}
import com.typesafe.config.ConfigFactory

object CustomDirectivesServer extends HttpApp with MetricDirectives {
  private val metricRegistry = new MetricRegistry()
  ConsoleReporter.forRegistry(metricRegistry).build().start(10, TimeUnit.SECONDS)

  val route =
    timer(metricRegistry) {
      get {
        complete { Thread.sleep(200); "Hello from GET!" }
      } ~
        post {
          complete { Thread.sleep(500); "Hello from POST!" }
        } ~
      put {
        meter(metricRegistry) {
          complete { "Hello from PUT!" }
        }
      }
    }
}

object CustomDirectivesApplication extends App {
  CustomDirectivesServer.startServer("0.0.0.0", 8088, ServerSettings(ConfigFactory.load))
} 
开发者ID:PacktPublishing,项目名称:Akka-Cookbook,代码行数:34,代码来源:CustomDirectivesApplication.scala

示例15: meter

//设置package包名称以及导入依赖的类
package com.packt.chapter9

import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.Directives._
import com.codahale.metrics.MetricRegistry

trait MetricDirectives {
  def meter(metricRegistry: MetricRegistry) : Directive0 = {
    extractMethod.flatMap[Unit] { httpMethod =>
      extractUri.flatMap { uri ?
        metricRegistry.meter(s"meter-Method[${httpMethod.value}]-Uri[${uri.path.toString}]").mark
        pass
      }
    }
  }

  def timer(metricRegistry: MetricRegistry) : Directive0 = {
    extractMethod.flatMap[Unit] { httpMethod =>
      extractUri.flatMap { uri ?
        val timer = metricRegistry.timer(s"timer-Method[${httpMethod.value}]-Uri[${uri.path.toString}]")
        val timerContext = timer.time()
        mapRouteResult { x ?
          timerContext.stop()
          x
        }
      }
    }
  }
} 
开发者ID:PacktPublishing,项目名称:Akka-Cookbook,代码行数:30,代码来源:MetricDirectives.scala


注:本文中的com.codahale.metrics.MetricRegistry类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。