org.slf4j.bridge.SLF4JBridgeHandler Scala Examples

The following examples show how to use org.slf4j.bridge.SLF4JBridgeHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: Server.scala    From opencensus-scala   with Apache License 2.0 5 votes vote down vote up
package io.opencensus.scala.examples.akka.http

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import com.typesafe.scalalogging.LazyLogging
import io.opencensus.scala.akka.http.TracingDirective._
import io.opencensus.trace.AttributeValue
import org.slf4j.bridge.SLF4JBridgeHandler

import scala.util.{Failure, Success}

object Server extends App with LazyLogging {
  // Forward java.util.Logging to slf4j
  SLF4JBridgeHandler.removeHandlersForRootLogger()
  SLF4JBridgeHandler.install()

  implicit val system: ActorSystem = ActorSystem()
  import system.dispatcher

  val routes: Route = traceRequest { span =>
    complete {
      val attrValue = AttributeValue.stringAttributeValue("test")
      span.putAttribute("my-attribute", attrValue)
      "Hello opencensus"
    }
  }

  logger.info("Binding...")
  Http().bindAndHandle(routes, "0.0.0.0", 8080).onComplete {
    case Success(bound) =>
      logger.info(s"Bound to ${bound.localAddress}")
    case Failure(e) =>
      logger.error("Failed to bind", e)
  }
} 
Example 2
Source File: Client.scala    From opencensus-scala   with Apache License 2.0 5 votes vote down vote up
package io.opencensus.scala.examples.akka.http

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.stream.scaladsl.{Sink, Source}
import io.opencensus.scala.akka.http.TracingClient
import org.slf4j.bridge.SLF4JBridgeHandler

import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.util.{Failure, Success}

object Client extends App {
  // Forward java.util.Logging to slf4j
  SLF4JBridgeHandler.removeHandlersForRootLogger()
  SLF4JBridgeHandler.install()

  implicit val system: ActorSystem = ActorSystem()
  import system.dispatcher

  def await[T](f: Future[T]) = Await.result(f, 3.seconds)

  // Request level client
  val pipeling = Http().singleRequest(_: HttpRequest)
  val r1 = await {
    TracingClient
      .traceRequest(pipeling)(HttpRequest(uri = "http://localhost:8080"))
      .flatMap(_.entity.toStrict(1.second))
      .map(_.data.utf8String)
  }
  println(r1)

  // Host level client
  val pool     = Http().cachedHostConnectionPool[Unit]("localhost", 8080)
  val hostFlow = TracingClient.traceRequestForPool(pool)

  val r2 = await {
    Source
      .single(HttpRequest(uri = "/"))
      .map((_, ()))
      .via(hostFlow)
      .map(_._1)
      .flatMapConcat {
        case Success(response) => response.entity.dataBytes
        case Failure(e)        => throw e
      }
      .map(_.utf8String)
      .runWith(Sink.head)
  }
  println(r2)

  // Connection level client
  val connection     = Http().outgoingConnection("localhost", 8080)
  val connectionFlow = TracingClient.traceRequestForConnection(connection)

  val r3 = await {
    Source
      .single(HttpRequest(uri = "/"))
      .via(connectionFlow)
      .flatMapConcat(_.entity.dataBytes)
      .map(_.utf8String)
      .runWith(Sink.head)
  }
  println(r3)
} 
Example 3
Source File: NoddySpec.scala    From pcplod   with Apache License 2.0 5 votes vote down vote up
// Copyright: 2010 - 2016 Rory Graves, Sam Halliday
// License: http://www.apache.org/licenses/LICENSE-2.0

// intentionally not in org.ensime.noddy for testing
package org.ensime.testing

import org.slf4j.LoggerFactory
import org.slf4j.bridge.SLF4JBridgeHandler
import scala.concurrent.Future
import org.scalatest._
import org.scalatest.Matchers._

trait Logging {
  SLF4JBridgeHandler.removeHandlersForRootLogger()
  SLF4JBridgeHandler.install()
  val log = LoggerFactory.getLogger(this.getClass)
}

class NoddySpec extends FlatSpec with Logging {

  "@noddy" should "generate companion's apply with no parameters" in {
    { Me(): Me } shouldBe null
  }

  it should "create a companion for Mallgan" in {
    Mallgan shouldBe a[Mallgan.type]
  }

  it should "generate companion apply with parameters" in {
    { Myself("foo", 23L): Myself } shouldBe null
  }

  it should "update Foo's companion" in {
    Foo.ignore("foo", 13L) shouldBe a[Foo]

    { Foo("foo", 13L): Foo } shouldBe null
  }

  it should "generate companion apply with named / default parameters" in {
    { Mine("foo"): Mine } shouldBe null

    { Mine(foo = "foo"): Mine } shouldBe null

    { Mine(bar = 10): Mine } shouldBe null
  }

  it should "not create anything not @noddy" in {
    "Irene" shouldNot compile
  }

  it should "handle typed classes" in {
    { Baz("hello"): Baz[String] } shouldBe null
  }

  it should "handle covariant types" in {
    { Covariant(""): Covariant[String] } shouldBe null
  }

  it should "handle contravariant types" in {
    { Contravariant(""): Contravariant[String] } shouldBe null
  }

  it should "generate a log method on the instance" in {
    { new LoggingFutures("hello", 0).exposed } shouldBe null
  }

  it should "generate a log method on the companion" in {
    { LoggingFutures.exposed } shouldBe null
  }

  it should "generate future methods on the companion" in {
    { LoggingFutures.a: Future[String] } shouldBe null

    { LoggingFutures.b: Future[Long] } shouldBe null
  }

} 
Example 4
Source File: PcPlodTest.scala    From pcplod   with Apache License 2.0 5 votes vote down vote up
// Copyright: 2010 - 2016 Rory Graves, Sam Halliday
// License: http://www.apache.org/licenses/LICENSE-2.0
package org.ensime.pcplod

import org.scalatest._
import Matchers._
import org.slf4j.LoggerFactory
import org.slf4j.bridge.SLF4JBridgeHandler

trait Logging {
  SLF4JBridgeHandler.removeHandlersForRootLogger()
  SLF4JBridgeHandler.install()
  val log = LoggerFactory.getLogger(this.getClass)
}

class PcPlodTest extends FlatSpec with Logging {

  "Mr Plod" should "give a sensible warning if you point at a missing file" in {
    val caught = intercept[IllegalArgumentException] {
      withMrPlod("com/acme/missing.scala") { mr =>
        mr.typeAtPoint(0)
      }
    }
    caught.getMessage shouldBe "requirement failed: Scala file com/acme/missing.scala not found as resource"
  }

  "Mr Plod" should "typecheck a compilable valid noddy file" in withMrPlod("com/acme/foo.scala") { mr =>
    mr.symbolAtPoint('foo) shouldBe Some("com.acme.Foo")
    mr.typeAtPoint('foo) shouldBe Some("com.acme.Foo.type")

    mr.symbolAtPoint('bar) shouldBe Some("com.acme.Foo.bar")
    mr.typeAtPoint('bar) shouldBe Some("Int")

    mr.symbolAtPoint('a) shouldBe Some("com.acme.Foo.a")
    mr.typeAtPoint('a) shouldBe Some("Int")

    mr.messages shouldBe empty
  }

  "Mr Plod" should "typecheck an uncompilable valid noddy file" in withMrPlod("com/acme/foo_bad.scala") { mr =>
    mr.typeAtPoint('foo) shouldBe Some("com.acme.Foo.type")

    mr.typeAtPoint('input_a) should matchPattern {
      case Some("<error>")  => // scala 2.11
      case Some("<notype>") => // scala 2.10
    }

    import org.ensime.pcplod.PcMessageSeverity._

    mr.messages should matchPattern {
      case List(
        PcMessage("com/acme/foo_bad.scala", Error, "';' expected but '=' found."),
        PcMessage("com/acme/foo_bad.scala", Error, "not found: value bar"),
        PcMessage("com/acme/foo_bad.scala", Error, "not found: value a")
        ) => // scala 2.11
      case List(
        PcMessage("com/acme/foo_bad.scala", Error, "';' expected but '=' found."),
        PcMessage("com/acme/foo_bad.scala", Error, "not found: value bar")
        ) => // scala 2.10
    }
  }

  "Noddy parser" should "support noddy syntax" in {
    val raw = "def ba@bar@r(a@a@: Int): Int = 2"
    val clean = "def bar(a: Int): Int = 2"

    PcPlod.parseNoddy(raw) shouldBe ((clean, Map("bar" -> 5, "a" -> 8)))
  }
} 
Example 5
Source File: TemperatureServer.scala    From the-finagle-docs   with MIT License 5 votes vote down vote up
package net.gutefrage.context

import java.util.concurrent.atomic.AtomicLong

import com.twitter.finagle._
import com.twitter.finagle.thrift.Protocols
import com.twitter.logging.{Logger, Logging}
import com.twitter.server.TwitterServer
import com.twitter.util.{Await, Future}
import net.gutefrage.Env
import net.gutefrage.temperature.thrift._
import org.slf4j.bridge.SLF4JBridgeHandler



object TemperatureServer extends TwitterServer with Logging{

  val port = flag[Int]("port", 8080, "port this server should use")
  val env = flag[Env]("env", Env.Local, "environment this server runs")

  override def failfastOnFlagsNotParsed: Boolean = true

  premain {
    SLF4JBridgeHandler.removeHandlersForRootLogger()
    SLF4JBridgeHandler.install()
  }

  onExit {
    info("Shutting down temperature server")
  }

  val appLog = Logger("application")

  def main() {
    appLog.info(s"Starting temperature server in environment ${env().name} on port ${port()}")

    // the actual server implementation
    val service = new TemperatureService.FutureIface {

      val numElements = new AtomicLong()
      val sumTemperature = new AtomicLong()

      override def add(datum: TemperatureDatum): Future[Unit] = {
        numElements.incrementAndGet()
        sumTemperature.addAndGet(datum.celsius)
        Future.Unit
      }

      override def mean(): Future[Double] = {
        // Accessing a given userContext if provided
        UserContext.current.foreach { userContext =>
          appLog.info(s"Call received with context: ${userContext}")
        }

        val n = numElements.get()
        val mean = if(n == 0L) 0.0 else sumTemperature.get() / n
        Future.value(mean)
      }
    }

    // Wrap the service implementation into a real finagle service
    val finagledService: Service[Array[Byte], Array[Byte]] = new TemperatureService.FinagledService(
      service, Protocols.binaryFactory()
    )

    // run and announce the service
    val server = ThriftMux.server
      .withLabel("temperature-service")
      .serveAndAnnounce(
        // schema ! host ! path ! shardId
        name = s"zk!127.0.0.1:2181!/service/${env.name}/temperature!0",
        // bind to local address
        addr = s":${port()}",
        service = finagledService
      )

    // Keep waiting for the server and prevent the java process to exit
    closeOnExit(server)
    Await.ready(server)
  }

} 
Example 6
Source File: WeatherApi.scala    From the-finagle-docs   with MIT License 5 votes vote down vote up
package net.gutefrage.context

import com.twitter.finagle._
import com.twitter.finagle.context.Contexts
import com.twitter.finagle.http.service.HttpResponseClassifier
import com.twitter.server.TwitterServer
import com.twitter.util.Await
import io.circe.generic.auto._
import io.finch._
import io.finch.circe._
import net.gutefrage.temperature.thrift._
import net.gutefrage.{Dtabs, Env}
import org.slf4j.LoggerFactory
import org.slf4j.bridge.SLF4JBridgeHandler


    case class Mean(mean: Double)
    case class MeanForUser(mean: Double, userId: Long)

    // mean temperature endpoint
    val mean: Endpoint[Mean] = get("weather" / "mean") {
      client.mean().map(mean => Ok(Mean(mean)))
    }

    // user endpoint which sets a UserContext
    val userMean: Endpoint[MeanForUser] =
      get("weather" / "mean" / "user" :: long) { userId: Long =>
        val userContext = UserContext(userId)
        Contexts.broadcast.let(UserContext, userContext) {
          client.mean().map(mean => Ok(MeanForUser(mean, userId)))
        }
      }

    // compose endpoints
    // https://github.com/finagle/finch/blob/master/docs/endpoint.md#composing-endpoints
    val api = mean :+: userMean

    // start and announce the server
    val server = Http.server
      .withLabel("weather-api")
      .withResponseClassifier(HttpResponseClassifier.ServerErrorsAsFailures)
      .serve(
        addr = s":${port()}",
        service = api.toService
      )

    closeOnExit(server)
    Await.ready(server)

  }

} 
Example 7
Source File: TemperatureSensorDtabs.scala    From the-finagle-docs   with MIT License 5 votes vote down vote up
package net.gutefrage.basic

import com.twitter.app.Flaggable
import com.twitter.conversions.time._
import com.twitter.finagle.{Dtab, ThriftMux}
import com.twitter.finagle.util.DefaultTimer
import com.twitter.logging.Logging
import com.twitter.server.TwitterServer
import com.twitter.util.{Await, Future}
import net.gutefrage.temperature.thrift._
import net.gutefrage.{Dtabs, Env}
import org.slf4j.bridge.SLF4JBridgeHandler


  override def failfastOnFlagsNotParsed: Boolean = true

  premain {
    SLF4JBridgeHandler.removeHandlersForRootLogger()
    SLF4JBridgeHandler.install()

    // initialise custom dtabs
    Dtabs.init(baseDtab())
    info(
      s"""|Use base dtab:
          |${Dtab.base.show}
       """.stripMargin)
  }

  onExit {
    info("Shutting down sensor")
  }

  def main(): Unit = {
    // create a thrift client and resolve address via dtabs
    val client = ThriftMux.client.newIface[TemperatureService.FutureIface](
      dest = "/s/temperature",
      label = "temperature-sensor"
    )

    implicit val timer = DefaultTimer.twitter
    val randomTemp = new java.util.Random()

    def sendLoop: Future[Unit] = {
      val datum = TemperatureDatum(randomTemp.nextInt(40) - 10,
                                   System.currentTimeMillis / 1000)
      info(s"Sending data: $datum")
      for {
        _ <- Future.sleep(1.second)
        _ <- client.add(datum)
        _ <- sendLoop
      } yield ()
    }

    Await.ready(sendLoop)
  }

} 
Example 8
Source File: TemperatureServer.scala    From the-finagle-docs   with MIT License 5 votes vote down vote up
package net.gutefrage.basic

import java.util.concurrent.atomic.AtomicLong

import com.twitter.finagle._
import com.twitter.finagle.thrift.Protocols
import com.twitter.logging.Logger
import com.twitter.server.TwitterServer
import com.twitter.util.logging.Logging
import com.twitter.util.{Await, Future}
import net.gutefrage.Env
import net.gutefrage.temperature.thrift._
import org.slf4j.bridge.SLF4JBridgeHandler



object TemperatureServer extends TwitterServer with Logging{

  val port = flag[Int]("port", 8080, "port this server should use")
  val env = flag[Env]("env", Env.Local, "environment this server runs")

  override def failfastOnFlagsNotParsed: Boolean = true

  premain {
    SLF4JBridgeHandler.removeHandlersForRootLogger()
    SLF4JBridgeHandler.install()
  }

  onExit {
    info("Shutting down temperature server")
  }

  val appLog = Logger("application")

  def main() {
    appLog.info(s"Starting temperature server in environment ${env().name} on port ${port()}")

    // the actual server implementation
    val service = new TemperatureService.FutureIface {

      val numElements = new AtomicLong()
      val sumTemperature = new AtomicLong()

      override def add(datum: TemperatureDatum): Future[Unit] = {
        numElements.incrementAndGet()
        sumTemperature.addAndGet(datum.celsius)
        Future.Unit
      }

      override def mean(): Future[Double] = {
        val n = numElements.get()
        val mean = if(n == 0L) 0.0 else sumTemperature.get() / n
        Future.value(mean)
      }
    }

    // Wrap the service implementation into a real finagle service
    val finagledService: Service[Array[Byte], Array[Byte]] = new TemperatureService.FinagledService(
      service, Protocols.binaryFactory()
    )

    // run and announce the service
    val server = ThriftMux.server
      .withLabel("temperature-service")
      .serveAndAnnounce(
        // schema ! host ! path ! shardId
        name = s"zk!127.0.0.1:2181!/service/${env().name}/temperature!0",
        // bind to local address
        addr = s":${port()}",
        service = finagledService
      )

    // Keep waiting for the server and prevent the java process to exit
    closeOnExit(server)
    Await.ready(server)
  }

} 
Example 9
Source File: TemperatureSensorStatic.scala    From the-finagle-docs   with MIT License 5 votes vote down vote up
package net.gutefrage.basic

import com.twitter.conversions.time._
import com.twitter.finagle.ThriftMux
import com.twitter.finagle.util.DefaultTimer
import com.twitter.server.TwitterServer
import com.twitter.util.logging.Logging
import com.twitter.util.{Await, Future}
import net.gutefrage.temperature.thrift._
import net.gutefrage.{Dtabs, Env}
import org.slf4j.bridge.SLF4JBridgeHandler


object TemperatureSensorStatic extends TwitterServer with Logging{
  val env = flag[Env]("env", Env.Local, "environment this server runs")

  premain {
    SLF4JBridgeHandler.removeHandlersForRootLogger()
    SLF4JBridgeHandler.install()

    // initialise custom dtabs
    Dtabs.init()
  }

  onExit {
    info("Shutting down sensor")
  }

  def main(): Unit = {
    // create a thrift client and resolve address via dtabs
    val client = ThriftMux.client.newIface[TemperatureService.FutureIface](
      // schema ! args
      dest = s"zk2!127.0.0.1:2181!/service/${env().name}/temperature",
      label = "temperature-sensor"
    )

    implicit val timer = DefaultTimer.twitter
    val randomTemp = new java.util.Random()

    def sendLoop: Future[Unit] = {
      val datum = TemperatureDatum(randomTemp.nextInt(40) - 10,
                                   System.currentTimeMillis / 1000)
      info(s"Sending data: $datum")
      for {
        _ <- Future.sleep(1.second)
        _ <- client.add(datum)
        _ <- sendLoop
      } yield ()
    }

    Await.ready(sendLoop)
  }

} 
Example 10
Source File: WeatherApi.scala    From the-finagle-docs   with MIT License 5 votes vote down vote up
package net.gutefrage.basic

import com.twitter.finagle._
import com.twitter.finagle.http.service.HttpResponseClassifier
import com.twitter.server.TwitterServer
import com.twitter.util.Await
import io.circe.generic.auto._
import io.finch._
import io.finch.circe._
import net.gutefrage.temperature.thrift._
import net.gutefrage.{Dtabs, Env}
import org.slf4j.LoggerFactory
import org.slf4j.bridge.SLF4JBridgeHandler


    case class Mean(mean: Double)

    // mean temperature endpoint
    val api: Endpoint[Mean] = get("weather" / "mean") {
      client.mean().map(mean => Ok(Mean(mean)))
    }

    // start and announce the server
    val server = Http.server
      .withLabel("weather-api")
      .withResponseClassifier(HttpResponseClassifier.ServerErrorsAsFailures)
      .serve(
        addr = s":${port()}",
        service = api.toService
      )

    closeOnExit(server)
    Await.ready(server)

  }

} 
Example 11
Source File: Logging.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.app

import com.twitter.app.App
import com.twitter.finagle.http.filter.LoggingFilter
import java.util.logging.Level
import java.util.logging.LogManager
import org.slf4j.bridge.SLF4JBridgeHandler

trait Logging { self: App =>
  init {
    // Turn off Java util logging so that slf4j can configure it
    LogManager.getLogManager.getLogger("").getHandlers.toList.foreach { l =>
      l.setLevel(Level.OFF)
    }
    org.slf4j.LoggerFactory.getLogger("slf4j-logging").debug("Installing SLF4JLogging")
    SLF4JBridgeHandler.install()

    // Override Logger config to use the parent handler
    LoggingFilter.log.setUseParentHandlers(true)
  }

  onExit {
    org.slf4j.LoggerFactory.getLogger("slf4j-logging").debug("Uninstalling SLF4JLogging")
    SLF4JBridgeHandler.uninstall()
  }
} 
Example 12
Source File: LoggingBootstrap.scala    From vamp   with Apache License 2.0 5 votes vote down vote up
package io.vamp.bootstrap

import com.typesafe.scalalogging.Logger
import io.vamp.common.akka.Bootstrap
import io.vamp.model.Model
import org.slf4j.LoggerFactory
import org.slf4j.bridge.SLF4JBridgeHandler

import scala.concurrent.Future

abstract class LoggingBootstrap extends Bootstrap {

  def logo: String

  def clazz: Class[_] = classOf[Vamp]

  lazy val version: String = if (Model.version.nonEmpty) s"version ${Model.version}" else ""

  override def start(): Future[Unit] = Future.successful {
    val logger = Logger(LoggerFactory.getLogger(clazz))
    if (!SLF4JBridgeHandler.isInstalled) {
      SLF4JBridgeHandler.removeHandlersForRootLogger()
      SLF4JBridgeHandler.install()
    }
    logger.info(logo)
  }

  override def stop(): Future[Unit] = Future.successful {
    if (SLF4JBridgeHandler.isInstalled) SLF4JBridgeHandler.uninstall()
  }
} 
Example 13
Source File: Logger.scala    From shapenet-viewer   with MIT License 5 votes vote down vote up
package edu.stanford.graphics.shapenet.util

import org.slf4j.LoggerFactory
import java.io.File

import org.slf4j.bridge.SLF4JBridgeHandler
import uk.org.lidalia.sysoutslf4j.context.SysOutOverSLF4J


                   additive: Boolean = false) = {
    import ch.qos.logback.classic.spi.ILoggingEvent
    import ch.qos.logback.classic.Level
    import ch.qos.logback.classic.LoggerContext
    import ch.qos.logback.classic.encoder.PatternLayoutEncoder
    import ch.qos.logback.core.FileAppender

    // Make sure log directory is created
    val file: File = new File(filename)
    val parent: File = file.getParentFile
    if (parent != null) parent.mkdirs

    val loggerContext = LoggerFactory.getILoggerFactory().asInstanceOf[LoggerContext]
    val logger = loggerContext.getLogger(loggerName)

    // Setup pattern
    val patternLayoutEncoder = new PatternLayoutEncoder()
    patternLayoutEncoder.setPattern(pattern)
    patternLayoutEncoder.setContext(loggerContext)
    patternLayoutEncoder.start()

    // Setup appender
    val fileAppender = new FileAppender[ILoggingEvent]()
    fileAppender.setFile(filename)
    fileAppender.setEncoder(patternLayoutEncoder)
    fileAppender.setContext(loggerContext)
    fileAppender.start()

    // Attach appender to logger
    logger.addAppender(fileAppender)
    //logger.setLevel(Level.DEBUG)
    logger.setAdditive(additive)

    fileAppender.getName
  }

  def detachAppender(appenderName: String, loggerName: String = org.slf4j.Logger.ROOT_LOGGER_NAME): Unit = {
    import ch.qos.logback.classic.LoggerContext

    val loggerContext = LoggerFactory.getILoggerFactory().asInstanceOf[LoggerContext]
    val logger = loggerContext.getLogger(loggerName)
    logger.detachAppender(appenderName)
  }

  def getLogger(clazz: Class[_]): org.slf4j.Logger = {
    LoggerFactory.getLogger(clazz)
  }

  def getLogger(name: String): org.slf4j.Logger = {
    LoggerFactory.getLogger(name)
  }
}

trait Loggable {
  lazy val logger = Logger.getLogger(this.getClass)

  def startTrack(name: String): Unit = {
    logger.debug("Starting " + name)
  }

  def endTrack(name: String): Unit = {
    logger.debug("Finished " + name)
  }
}