• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala MetricRegistry类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: KafkaSink

//设置package包名称以及导入依赖的类
package org.apache.spark.metrics.sink

import java.util.{ Properties, Locale }
import java.util.concurrent.TimeUnit

import org.slf4j.Logger
import org.slf4j.LoggerFactory

import com.codahale.metrics.MetricRegistry
import org.apache.spark.SecurityManager

import com.manyangled.kafkasink.KafkaReporter

class KafkaSink(val properties: Properties, val registry: MetricRegistry,
    securityMgr: SecurityManager) extends org.apache.spark.metrics.sink.Sink {

  val logger: Logger = LoggerFactory.getLogger(this.getClass)

  private def popt(prop: String): Option[String] =
    Option(properties.getProperty(prop))

  // These are non-negotiable
  val broker = popt("broker").get
  val topic = popt("topic").get

  lazy val reporter = new KafkaReporter(registry, broker, topic, properties)

  def start(): Unit = {
    logger.info(s"Starting Kafka metric reporter at $broker, topic $topic")
    val period = popt("period").getOrElse("10").toLong
    val tstr = popt("unit").getOrElse("seconds").toUpperCase(Locale.ROOT)
    val tunit = TimeUnit.valueOf(tstr)
    reporter.start(period, tunit)
  }

  def stop(): Unit = {
    logger.info(s"Stopping Kafka metric reporter at $broker, topic $topic")
    reporter.stop()
  }

  def report(): Unit = {
    logger.info(s"Reporting metrics to Kafka reporter at $broker, topic $topic")
    reporter.report()
  }
} 
开发者ID:erikerlandson,项目名称:spark-kafka-sink,代码行数:46,代码来源:KafkaSink.scala


示例17: MetricRegistryProvider

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

import javax.inject.{Provider, Singleton}

import com.codahale.metrics.MetricRegistry
import com.codahale.metrics.jvm.{
  GarbageCollectorMetricSet,
  MemoryUsageGaugeSet,
  ThreadStatesGaugeSet
}

@Singleton
class MetricRegistryProvider extends Provider[MetricRegistry] {
  private val registry = new MetricRegistry

  registry.register("jvm.gc", new GarbageCollectorMetricSet)
  registry.register("jvm.memory", new MemoryUsageGaugeSet)
  registry.register("jvm.threads", new ThreadStatesGaugeSet)

  override def get(): MetricRegistry = registry
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:22,代码来源:MetricRegistryProvider.scala


示例18: InstrumentLogging

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

import javax.inject.{Inject, Singleton}

import ch.qos.logback.classic.LoggerContext
import com.codahale.metrics.MetricRegistry
import com.codahale.metrics.logback.InstrumentedAppender
import org.slf4j.{Logger, LoggerFactory}

@Singleton
class InstrumentLogging @Inject()(metricRegistry: MetricRegistry) {
  InstrumentLogging.instrument(metricRegistry)
}

object InstrumentLogging {
  def instrument(metricRegistry: MetricRegistry): Unit = {
    val factory = LoggerFactory.getILoggerFactory.asInstanceOf[LoggerContext]
    val root    = factory.getLogger(Logger.ROOT_LOGGER_NAME)

    val instrumentedAppended = new InstrumentedAppender(metricRegistry)
    instrumentedAppended.setContext(root.getLoggerContext)
    instrumentedAppended.start()
    root.addAppender(instrumentedAppended)
  }
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:26,代码来源:InstrumentLogging.scala


示例19: MetricsFilter

//设置package包名称以及导入依赖的类
package microtools.filters

import javax.inject.Inject

import akka.stream.Materializer
import com.codahale.metrics.MetricRegistry
import play.api.mvc.{Filter, RequestHeader, Result}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.Success

class MetricsFilter @Inject()(metricRegistry: MetricRegistry)(
    implicit ec: ExecutionContext,
    override implicit val mat: Materializer
) extends Filter {
  private val successTimer = metricRegistry.timer("play.requests.success")
  private val clientErrorMeter =
    metricRegistry.meter("play.requests.clientError")
  private val serverErrorMeter =
    metricRegistry.meter("play.requests.serverError")

  override def apply(f: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = {
    val timeCtx      = successTimer.time()
    val futureResult = f(rh)

    futureResult.onComplete {
      case Success(result) if result.header.status < 400 =>
        timeCtx.stop()
      case Success(result) if result.header.status < 500 =>
        clientErrorMeter.mark()
      case _ =>
        serverErrorMeter.mark()
    }
    futureResult
  }
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:37,代码来源:MetricsFilter.scala


示例20: ExceptionMeteredListener

//设置package包名称以及导入依赖的类
package de.khamrakulov.play.metrics.annotation.guice.listener

import java.lang.reflect.Method

import com.codahale.metrics.MetricRegistry
import com.codahale.metrics.annotation.ExceptionMetered
import de.khamrakulov.play.metrics.annotation.MetricNamer
import de.khamrakulov.play.metrics.annotation.guice.interceptor.ExceptionMeteredInterceptor
import de.khamrakulov.play.metrics.annotation.matcher.AnnotationProvider


private[annotation] object ExceptionMeteredListener {
  def apply(metricRegistry: MetricRegistry, metricNamer: MetricNamer, provider: AnnotationProvider) =
    new ExceptionMeteredListener(metricRegistry, metricNamer, provider)
}

private[annotation] class ExceptionMeteredListener(metricRegistry: MetricRegistry,
                                              metricNamer: MetricNamer,
                                              provider: AnnotationProvider) extends DeclaredMethodsTypeListener {

  protected def getInterceptor(method: Method) = provider.get[ExceptionMetered].from(method).map { annotation =>
    val meter = metricRegistry.meter(metricNamer.metered(method, annotation))
    ExceptionMeteredInterceptor(meter, annotation.cause)
  }

} 
开发者ID:htimur,项目名称:metrics-annotation-play,代码行数:27,代码来源:ExceptionMeteredListener.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Pipeline类代码示例发布时间:2022-05-23
下一篇:
Scala BufferedInputStream类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap