本文整理汇总了Scala中akka.event.LoggingAdapter类的典型用法代码示例。如果您正苦于以下问题:Scala LoggingAdapter类的具体用法?Scala LoggingAdapter怎么用?Scala LoggingAdapter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了LoggingAdapter类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: log
//设置package包名称以及导入依赖的类
package com.marwanad.util.log
import akka.actor.{Actor, ActorLogging}
import akka.event.Logging.LogLevel
import akka.event.{Logging, LoggingAdapter}
import LogUtils._
trait Timber extends ActorLogging {
this: Actor ?
private var _log: LoggingAdapter = _
override def log: LoggingAdapter = {
// only used in Actor, i.e. thread safe
if (_log eq null)
_log = akka.event.Logging(context.system, this)
_log
}
def log(s: String, level: LogLevel): Unit = {
level match {
case Logging.ErrorLevel => log.error(s.redBlink)
case Logging.DebugLevel => log.debug(s.white)
case Logging.InfoLevel => log.info(s.lightGreen)
case Logging.WarningLevel => log.warning(s.yellow)
}
}
def logDebug(s: String): Unit = {
log(s, Logging.DebugLevel)
}
def logInfo(s: String): Unit = {
log(s, Logging.InfoLevel)
}
def logError(s: String): Unit = {
log(s, Logging.ErrorLevel)
}
def logWarning(s: String): Unit = {
log(s, Logging.ErrorLevel)
}
def logActorPreStart(s: String): Unit = {
log(s" PreStart ? ".white.greenB.concat(" ").concat(s.green), Logging.InfoLevel)
}
def logActorMessageReceived(s: String): Unit = {
log(s" Received ? ".white.greenB.concat(" ").concat(s.white), Logging.InfoLevel)
}
}
开发者ID:marwanad,项目名称:UofR,代码行数:53,代码来源:Timber.scala
示例2: executor
//设置package包名称以及导入依赖的类
package com.ferhtaydn.server
import akka.actor.ActorSystem
import akka.event.LoggingAdapter
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._
import akka.stream.Materializer
import com.ferhtaydn.models.{ JsonFormats, PatientInfo, PatientResult }
import com.ferhtaydn.rater.RatePredictor
import akka.http.scaladsl.model.StatusCodes._
import scala.concurrent.ExecutionContextExecutor
trait Server extends JsonFormats {
implicit val system: ActorSystem
implicit def executor: ExecutionContextExecutor
implicit val materializer: Materializer
val logger: LoggingAdapter
def predictor: RatePredictor
protected val routes: Route =
pathPrefix("cancerater") {
get {
pathSingleSlash {
complete("Welcome to CanceRater")
}
} ~
get {
path("cm") {
complete {
predictor.confusionMatrixString.map[ToResponseMarshallable] {
case cm ? cm
}
}
}
} ~
post {
path("check") {
entity(as[PatientInfo]) { patientInfo ?
complete {
predictor.predict(patientInfo).map[ToResponseMarshallable] {
case Right(score) ? PatientResult(score)
case Left(error) ? BadRequest ? error
}
}
}
}
}
}
}
开发者ID:ferhtaydn,项目名称:canceRater,代码行数:57,代码来源:Server.scala
示例3: SearchApi
//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.api
import akka.event.LoggingAdapter
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.{ StatusCodes }
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import au.csiro.data61.magda.model.misc
import au.csiro.data61.magda.model.misc._
import au.csiro.data61.magda.api.{ model => apimodel }
import au.csiro.data61.magda.search.SearchQueryer
import com.typesafe.config.Config
class SearchApi(val searchQueryer: SearchQueryer)(implicit val config: Config, implicit val logger: LoggingAdapter) extends misc.Protocols with BaseMagdaApi with apimodel.Protocols {
override def getLogger = logger
val queryCompiler = new QueryCompiler()
val routes =
magdaRoute {
pathPrefix("v0") {
pathPrefix("facets") {
path(Segment / "options") { facetId ?
(get & parameters("facetQuery" ? "*", "start" ? 0, "limit" ? 10, "generalQuery" ? "*")) { (facetQuery, start, limit, generalQuery) ?
FacetType.fromId(facetId) match {
case Some(facetType) ? complete(searchQueryer.searchFacets(facetType, facetQuery, queryCompiler.apply(generalQuery), start, limit))
case None ? complete(NotFound)
}
}
}
} ~
pathPrefix("datasets") {
(get & parameters("query" ? "*", "start" ? 0, "limit" ? 10, "facetSize" ? 10)) { (rawQuery, start, limit, facetSize) ?
val query = if (rawQuery.equals("")) "*" else rawQuery
onSuccess(searchQueryer.search(queryCompiler.apply(query), start, limit, facetSize)) { result =>
val status = if (result.errorMessage.isDefined) StatusCodes.InternalServerError else StatusCodes.OK
pathPrefix("datasets") {
complete(status, result.copy(facets = None))
} ~ pathPrefix("facets") {
complete(status, result.facets)
} ~ pathEnd {
complete(status, result)
}
}
}
} ~
path("region-types") { get { getFromResource("regionMapping.json") } } ~
path("regions") {
(get & parameters("query" ? "*", "start" ? 0, "limit" ? 10)) { (query, start, limit) ?
complete(searchQueryer.searchRegions(query, start, limit))
}
}
}
}
}
开发者ID:TerriaJS,项目名称:magda,代码行数:57,代码来源:SearchApi.scala
示例4: getClient
//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.search.elasticsearch
import akka.actor.Scheduler
import akka.event.LoggingAdapter
import au.csiro.data61.magda.AppConfig
import au.csiro.data61.magda.util.ErrorHandling.retry
import com.sksamuel.elastic4s.{ TcpClient, ElasticsearchClientUri }
import org.elasticsearch.common.settings.Settings
import scala.concurrent.{ ExecutionContext, Future }
import scala.concurrent.duration._
trait ClientProvider {
def getClient(implicit scheduler: Scheduler, logger: LoggingAdapter, ec: ExecutionContext): Future[TcpClient]
}
class DefaultClientProvider extends ClientProvider {
private var clientFuture: Option[Future[TcpClient]] = None
override def getClient(implicit scheduler: Scheduler, logger: LoggingAdapter, ec: ExecutionContext): Future[TcpClient] = {
val outerFuture = clientFuture match {
case Some(future) => future
case None =>
val future = retry(() => Future {
val uri = ElasticsearchClientUri(AppConfig.conf().getString("elasticSearch.serverUrl"))
val settings = Settings.builder().put("cluster.name", "myesdb").build()
TcpClient.transport(settings, uri)
}, 10 seconds, 10, onRetry(logger))
.map { client =>
logger.info("Successfully connected to elasticsearch client")
client
}
clientFuture = Some(future)
future
}
outerFuture
}
private def onRetry(logger: LoggingAdapter)(retriesLeft: Int, error: Throwable) = logger.error("Failed to make initial contact with ES server, {} retries left", retriesLeft, error)
}
开发者ID:TerriaJS,项目名称:magda,代码行数:44,代码来源:ClientProvider.scala
示例5: resetIoTHub
//设置package包名称以及导入依赖的类
// Copyright (c) Microsoft.All rights reserved.
package com.microsoft.azure.iot.iothub2cassandra
import akka.actor.ActorSystem
import akka.event.{Logging, LoggingAdapter}
import akka.stream.ActorMaterializer
import com.microsoft.azure.iot.iothub2cassandra.storage.{IKeyspace, IConnection, Keyspace, Connection}
import com.microsoft.azure.iot.iothubreact.scaladsl.IoTHub
trait IDependencies {
val system : ActorSystem
val materializer : ActorMaterializer
val log : LoggingAdapter
val config : IConfig
val cassandraConnection: IConnection
val cassandraKeyspace : IKeyspace
val streamingService : IStreamingService
val webService : IWebService
def resetIoTHub(): Unit
def iotHub(): IoTHub
}
private[iothub2cassandra] object Dependencies extends IDependencies {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
private[this] var iotHubObj: Option[IoTHub] = None
def iotHub(): IoTHub = {
if (!iotHubObj.isDefined) iotHubObj = Some(IoTHub())
iotHubObj.get
}
override def resetIoTHub(): Unit = {
iotHubObj = None
}
lazy val log = Logging(system, "iothub2cassandra")
lazy val config = new Config
lazy val cassandraConnection = Connection()
lazy val cassandraKeyspace = Keyspace()
lazy val streamingService = StreamingService()
lazy val webService = Webservice()
implicit val dependencies: IDependencies = this
log.info("Cassandra cluster: " + config.cassandraCluster)
log.info("Web service: " + config.httpInterface + ":" + config.httpPort)
}
开发者ID:Azure,项目名称:toketi-iothub-to-cassandra,代码行数:54,代码来源:Dependencies.scala
示例6: Main
//设置package包名称以及导入依赖的类
package com.noedominguez.class_orchestration.restapi
import com.noedominguez.class_orchestration.restapi.services.{AuthService, TeamsService, UsersService, ExplorationsService, ExplorationEventsService, ExplorationObjectsService}
import akka.actor.ActorSystem
import akka.event.{Logging, LoggingAdapter}
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.noedominguez.class_orchestration.restapi.http.HttpService
import com.noedominguez.class_orchestration.restapi.utils.{DatabaseService, FlywayService}
import com.noedominguez.class_orchestration.restapi.utils.Config
import scala.concurrent.ExecutionContext
object Main extends App with Config {
implicit val actorSystem = ActorSystem()
implicit val executor: ExecutionContext = actorSystem.dispatcher
implicit val log: LoggingAdapter = Logging(actorSystem, getClass)
implicit val materializer: ActorMaterializer = ActorMaterializer()
val flywayService = new FlywayService(jdbcUrl, dbUser, dbPassword)
flywayService.migrateDatabaseSchema
val databaseService = new DatabaseService(jdbcUrl, dbUser, dbPassword)
val usersService = new UsersService(databaseService)
val authService = new AuthService(databaseService)(usersService)
val teamsService= new TeamsService(databaseService)
val explorationsService= new ExplorationsService(databaseService)
val explorationEventsService= new ExplorationEventsService(databaseService)
val explorationObjectsService= new ExplorationObjectsService(databaseService)
val httpService = new HttpService(usersService, authService, teamsService, explorationsService, explorationEventsService,explorationObjectsService)
Http().bindAndHandle(httpService.routes, httpHost, httpPort)
}
开发者ID:poguez,项目名称:class_orchestration_api,代码行数:36,代码来源:Main.scala
示例7: Main
//设置package包名称以及导入依赖的类
package de.innfactory.bootstrap
import akka.actor.ActorSystem
import akka.event.{Logging, LoggingAdapter}
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import de.innfactory.bootstrap.http.HttpService
import de.innfactory.bootstrap.services.{AuthService, DummyService}
import de.innfactory.bootstrap.utils.{AWSCognitoValidation, Configuration, FlywayService}
import scala.concurrent.ExecutionContext
object Main extends App with Configuration {
// $COVERAGE-OFF$Main Application Wrapper
implicit val actorSystem = ActorSystem()
implicit val executor: ExecutionContext = actorSystem.dispatcher
implicit val log: LoggingAdapter = Logging(actorSystem, getClass)
implicit val materializer: ActorMaterializer = ActorMaterializer()
val flywayService = new FlywayService(jdbcUrl, dbUser, dbPassword)
flywayService.migrateDatabaseSchema
val authService = new AuthService(new AWSCognitoValidation(authCognito, log))
val dummyService = new DummyService()
val httpService = new HttpService(authService, dummyService)
Http().bindAndHandle(httpService.routes, httpHost, httpPort)
// $COVERAGE-ON$
}
开发者ID:innFactory,项目名称:bootstrap-akka-http,代码行数:31,代码来源:Main.scala
示例8: config
//设置package包名称以及导入依赖的类
package com.example
import akka.actor.Actor
import akka.event.LoggingAdapter
import cakesolutions.kafka.akka.KafkaConsumerActor.Subscribe
import cakesolutions.kafka.akka.{ConsumerRecords, KafkaConsumerActor, KafkaProducerActor, ProducerRecords}
import cakesolutions.kafka.{KafkaProducer, KafkaProducerRecord}
import com.example.PingPongProtocol.PingPongMessage
import com.typesafe.config.Config
import org.apache.kafka.common.serialization.{StringDeserializer, StringSerializer}
import scala.util.Random
trait KafkaConfig{
def config:Config
def log: LoggingAdapter
def randomString(len: Int= 5): String = Random.alphanumeric.take(len).mkString("")
}
trait PingPongConsumer extends KafkaConfig{
this: Actor =>
//for pattern matching in our receive method
val msgExtractor = ConsumerRecords.extractor[java.lang.String, PingPongMessage]
val kafkaConsumerActor = context.actorOf(
KafkaConsumerActor.props(config,new StringDeserializer(), new JsonDeserializer[PingPongMessage], self),
"PingKafkaConsumerActor"
)
def subscribe(topics: List[String]) =
kafkaConsumerActor ! Subscribe.AutoPartition(topics)
}
trait PingPongProducer extends KafkaConfig{
this: Actor =>
val kafkaProducerConf = KafkaProducer.Conf(
bootstrapServers = config.getString("bootstrap.servers"),
keySerializer = new StringSerializer(),
valueSerializer = new JsonSerializer[PingPongMessage])
val kafkaProducerActor = context.actorOf(KafkaProducerActor.props( kafkaProducerConf))
def submitMsg(topics: List[String], msg: PingPongMessage) = {
log.info(s"Placing $msg on ${topics.mkString(",")}")
topics.foreach(topic => kafkaProducerActor ! ProducerRecords(List(KafkaProducerRecord(topic, randomString(3), msg))))
}
}
开发者ID:123avi,项目名称:kafka-akka-example,代码行数:51,代码来源:PingPongConsumer.scala
示例9: Main
//设置package包名称以及导入依赖的类
import akka.actor.ActorSystem
import akka.event.{ Logging, LoggingAdapter }
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import http.HttpService
import services._
import utils.{ Config, SampleDataSeed }
import scala.concurrent.ExecutionContext
object Main extends App with Config {
implicit val actorSystem = ActorSystem()
implicit val executor: ExecutionContext = actorSystem.dispatcher
implicit val log: LoggingAdapter = Logging(actorSystem, getClass)
implicit val materializer: ActorMaterializer = ActorMaterializer()
val flywayService = new FlywayServiceImpl(jdbcUrl, dbUser, dbPassword)
flywayService.migrateDatabaseSchema()
val databaseService = new DatabaseServiceImpl(jdbcUrl, dbUser, dbPassword)
val accountsService = new AccountsServiceImpl(databaseService)
val oAuthClientsService = new OAuthClientsServiceImpl(databaseService, accountsService)
val oAuthAccessTokensService = new OAuthAccessTokensServiceImpl(databaseService, oAuthClientsService)
val cacheService = new CachingServiceImpl(redisHost, redisPort)
val moviesService = new MoviesServiceImpl(databaseService, cacheService)
val reservationService = new ReservationServiceImpl(moviesService, cacheService)
val httpService = new HttpService(moviesService, oAuthClientsService,
oAuthAccessTokensService, accountsService, cacheService, reservationService)
if (dbCreateSampleData) new SampleDataSeed(accountsService, oAuthClientsService)
.run()
Http().bindAndHandle(httpService.routes, httpHost, httpPort)
}
开发者ID:ziyasal,项目名称:Reserveon,代码行数:37,代码来源:Main.scala
示例10: log
//设置package包名称以及导入依赖的类
package me.snov.akka.sqs.shape
import akka.event.{LoggingAdapter, NoLogging}
import akka.stream.ActorMaterializer
import akka.stream.stage.GraphStageLogic
private[sqs] trait StageLogging { self: GraphStageLogic =>
private var loggingAdapter: LoggingAdapter = _
def log: LoggingAdapter = {
if (loggingAdapter eq null) {
materializer match {
case actorMaterializer: ActorMaterializer =>
loggingAdapter = akka.event.Logging(actorMaterializer.system, self.getClass)
case _ =>
loggingAdapter = NoLogging
}
}
loggingAdapter
}
}
开发者ID:s12v,项目名称:akka-stream-sqs,代码行数:24,代码来源:StageLogging.scala
示例11: HttpService
//设置package包名称以及导入依赖的类
package gateway.restapi.http
import akka.event.LoggingAdapter
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import gateway.restapi.http.routes.{ClientsServiceRoute, GatewayRoute}
import gateway.restapi.services.{ClientsService, TransactionsService, WalletsService}
import scala.concurrent.ExecutionContext
class HttpService(
usersService: ClientsService,
transactionsService: TransactionsService,
walletsService: WalletsService
) (implicit executionContext: ExecutionContext, log: LoggingAdapter, materializer : ActorMaterializer) {
val clientsRouter = new ClientsServiceRoute(usersService)
val gatewayRouter = new GatewayRoute(transactionsService, walletsService)
val router = new Router(clientsRouter, gatewayRouter)
val routes: Route = router.BuildRoute
}
开发者ID:kartavtcev,项目名称:gateway-sketch,代码行数:23,代码来源:HttpService.scala
示例12: Router
//设置package包名称以及导入依赖的类
package gateway.restapi.http
import akka.event.LoggingAdapter
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route}
import akka.stream.ActorMaterializer
import scala.concurrent.ExecutionContext
import gateway.restapi.http.routes.{ClientsServiceRoute, GatewayRoute}
import gateway.restapi.utils.CorsSupport
class Router(clientsRouter: ClientsServiceRoute, gatewayRouter: GatewayRoute)
(implicit executionContext: ExecutionContext, log: LoggingAdapter, materializer : ActorMaterializer) extends CorsSupport {
def BuildRoute: Route = {
val exceptionHandler = ExceptionHandler { // todo: response with internal exception message in DEBUG only
case error: Throwable => { // not a bad practice to catch Throwable here because it's the Root
log.error(error, error.getMessage)
extractUri { uri =>
complete(HttpResponse(StatusCodes.BadRequest, entity = error.getMessage))
}
}
}
logRequestResult("gateway-sketch-rest-api") {
handleExceptions(exceptionHandler) {
pathPrefix("v1") {
corsHandler {
clientsRouter.route ~
gatewayRouter.route
}
}
} // Route.seal()
}
////A Route can be "sealed" using Route.seal, which relies on the in-scope RejectionHandler and
////ExceptionHandler instances to convert rejections and exceptions into appropriate HTTP responses for the client.
}
}
开发者ID:kartavtcev,项目名称:gateway-sketch,代码行数:39,代码来源:Router.scala
示例13: Main
//设置package包名称以及导入依赖的类
package gateway.restapi
import scala.concurrent.ExecutionContext
import akka.actor.ActorSystem
import akka.event.{Logging, LoggingAdapter}
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import gateway.restapi.domain.storagecontext.StorageContext
import gateway.restapi.http.HttpService
import gateway.restapi.services.{ClientsService, TransactionsService, WalletsService}
import gateway.restapi.utils.Config
object Main extends App with Config {
implicit val actorSystem = ActorSystem("gateway-sketch-rest-api")
implicit val executor: ExecutionContext = actorSystem.dispatcher
implicit val log: LoggingAdapter = Logging(actorSystem, getClass)
implicit val materializer: ActorMaterializer = ActorMaterializer()
val clientsService = new ClientsService(StorageContext.instanceProd)
val walletsService = new WalletsService(StorageContext.instanceProd)
val transactionService = new TransactionsService(StorageContext.instanceProd, walletsService)
val httpService = new HttpService(clientsService, transactionService, walletsService)
Http().bindAndHandle(httpService.routes, httpHost, httpPort)
}
开发者ID:kartavtcev,项目名称:gateway-sketch,代码行数:28,代码来源:Main.scala
示例14: cleanContext
//设置package包名称以及导入依赖的类
package gateway.restapi
import akka.actor.ActorSystem
import akka.event.{Logging, LoggingAdapter}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import de.heikoseeberger.akkahttpcirce.CirceSupport
import gateway.restapi.domain.ClientEnitity
import gateway.restapi.domain.storagecontext.StorageContext
import gateway.restapi.http.HttpService
import gateway.restapi.services.{ClientsService, TransactionsService, WalletsService}
import org.scalatest._
import scala.util.Random
trait BaseServiceTest extends WordSpec with Matchers with ScalatestRouteTest with CirceSupport {
implicit val actorSystem = ActorSystem("gateway-sketch-rest-api-test")
implicit val log: LoggingAdapter = Logging(actorSystem, getClass)
val clientsService = new ClientsService(StorageContext.instanceTest)
val walletsService = new WalletsService(StorageContext.instanceTest)
val transactionService = new TransactionsService(StorageContext.instanceTest, walletsService)
val httpService = new HttpService(clientsService, transactionService, walletsService)
def cleanContext : Unit = { StorageContext.instanceTest.clean() } // todo: replace this hack ro reset/clear Context with better language/scala test feature
def provisionClientsList(size: Int): Seq[ClientEnitity] = {
(1 to size).map { _ =>
clientsService.createClient(ClientEnitity(None, Random.nextString(10)))
}
StorageContext.instanceTest.getClients
}
def getTransactionService = transactionService
}
开发者ID:kartavtcev,项目名称:gateway-sketch,代码行数:34,代码来源:BaseServiceTest.scala
示例15: modifiedLar
//设置package包名称以及导入依赖的类
package hmda.api.http.public
import akka.actor.ActorSystem
import akka.event.LoggingAdapter
import akka.http.scaladsl.model.HttpEntity.ChunkStreamPart
import akka.http.scaladsl.model.{ ContentTypes, HttpEntity, HttpResponse }
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import hmda.api.EC
import hmda.api.http.HmdaCustomDirectives
import hmda.query.DbConfiguration._
import hmda.query.repository.filing.FilingComponent
trait PublicLarHttpApi extends HmdaCustomDirectives with FilingComponent {
implicit val system: ActorSystem
implicit val materializer: ActorMaterializer
val log: LoggingAdapter
val modifiedLarRepository = new ModifiedLarRepository(config)
def modifiedLar[_: EC](institutionId: String) =
path("filings" / Segment / "lar") { period =>
timedGet { _ =>
val data = modifiedLarRepository.findByInstitutionIdSource(institutionId, period)
.map(x => ChunkStreamPart(x.toCSV + "\n"))
val response = HttpResponse(entity = HttpEntity.Chunked(ContentTypes.`text/csv(UTF-8)`, data))
complete(response)
}
}
}
开发者ID:cfpb,项目名称:hmda-platform,代码行数:33,代码来源:PublicLarHttpApi.scala
示例16:
//设置package包名称以及导入依赖的类
package hmda.api.http.public
import akka.actor.ActorSystem
import akka.event.LoggingAdapter
import akka.stream.ActorMaterializer
import akka.util.Timeout
import hmda.api.http.HmdaCustomDirectives
import akka.http.scaladsl.server.Directives._
import scala.concurrent.ExecutionContext
trait PublicHttpApi extends PublicLarHttpApi with HmdaCustomDirectives {
implicit val system: ActorSystem
implicit val materializer: ActorMaterializer
implicit val timeout: Timeout
val log: LoggingAdapter
val publicHttpRoutes =
extractExecutionContext { executor =>
implicit val ec: ExecutionContext = executor
encodeResponse {
pathPrefix("institutions" / Segment) { instId =>
modifiedLar(instId)
}
}
}
}
开发者ID:cfpb,项目名称:hmda-platform,代码行数:29,代码来源:PublicHttpApi.scala
示例17: rootPath
//设置package包名称以及导入依赖的类
package hmda.api.http
import java.net.InetAddress
import java.time.Instant
import akka.actor.ActorSystem
import akka.event.LoggingAdapter
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import hmda.api.model.Status
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import hmda.api.protocol.HmdaApiProtocol
import spray.json._
trait BaseHttpApi extends HmdaApiProtocol with HmdaCustomDirectives {
implicit val system: ActorSystem
implicit val materializer: ActorMaterializer
val log: LoggingAdapter
def rootPath(name: String) =
pathSingleSlash {
timedGet { _ =>
complete {
val now = Instant.now.toString
val host = InetAddress.getLocalHost.getHostName
val status = Status("OK", name, now, host)
log.debug(status.toJson.toString)
ToResponseMarshallable(status)
}
}
}
def routes(apiName: String) = encodeResponse { rootPath(apiName) }
}
开发者ID:cfpb,项目名称:hmda-platform,代码行数:36,代码来源:BaseHttpApi.scala
示例18: BaseHttpApiSpec
//设置package包名称以及导入依赖的类
package hmda.api.http
import akka.event.{ NoLogging, LoggingAdapter }
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.headers.{ HttpEncodings, `Accept-Encoding` }
import akka.http.scaladsl.model.headers.HttpEncodings._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import hmda.api.model.Status
import org.scalatest.{ MustMatchers, WordSpec }
import scala.concurrent.ExecutionContext
class BaseHttpApiSpec extends WordSpec with MustMatchers with ScalatestRouteTest with BaseHttpApi {
override val log: LoggingAdapter = NoLogging
val ec: ExecutionContext = system.dispatcher
"Http API service" must {
"return OK for GET requests to the root path" in {
Get() ~> routes("hmda-filing-api") ~> check {
responseAs[Status].status mustBe "OK"
responseAs[Status].service mustBe "hmda-filing-api"
}
}
"use requested encoding for root path" in {
Get().addHeader(`Accept-Encoding`(gzip)) ~> routes("hmda-filing-api") ~> check {
response.encoding mustBe HttpEncodings.gzip
}
}
}
}
开发者ID:cfpb,项目名称:hmda-platform,代码行数:35,代码来源:BaseHttpApiSpec.scala
示例19: KnoldusRoutingServer
//设置package包名称以及导入依赖的类
package com.knoldus.logging
import akka.actor.ActorSystem
import akka.event.{LoggingAdapter, Logging}
import akka.event.Logging.LogLevel
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.RouteResult.Complete
import akka.stream.{Materializer, ActorMaterializer}
import com.knoldus.logging.routes.KnoldusRoutingService
import akka.http.scaladsl.server.directives.{LoggingMagnet, LogEntry, DebuggingDirectives}
import pl.project13.scala.rainbow.Rainbow
import scala.concurrent.ExecutionContext.Implicits.global
import Rainbow._
import scala.concurrent.ExecutionContext
class KnoldusRoutingServer(implicit val system: ActorSystem,
implicit val materializer: ActorMaterializer) extends KnoldusRoutingService {
def startServer(address: String, port: Int) = {
val loggedRoute = requestMethodAndResponseStatusAsInfo(Logging.InfoLevel, routes)
Http().bindAndHandle(loggedRoute, address, port)
}
def requestMethodAndResponseStatusAsInfo(level: LogLevel, route: Route)
(implicit m: Materializer, ex: ExecutionContext) = {
def akkaResponseTimeLoggingFunction(loggingAdapter: LoggingAdapter, requestTimestamp: Long)(req: HttpRequest)(res: Any): Unit = {
val entry = res match {
case Complete(resp) =>
val responseTimestamp: Long = System.currentTimeMillis()
val elapsedTime: Long = responseTimestamp - requestTimestamp
val loggingString = "Logged Request:" + req.method + ":" + req.uri + ":" + resp.status + ":" + elapsedTime
val coloredLoggingString = if (elapsedTime > StartApp.thresholdValue) {
loggingString.red
} else {
loggingString.green
}
LogEntry(coloredLoggingString, level)
case anythingElse =>
LogEntry(s"$anythingElse", level)
}
entry.logTo(loggingAdapter)
}
DebuggingDirectives.logRequestResult(LoggingMagnet(log => {
val requestTimestamp = System.currentTimeMillis()
akkaResponseTimeLoggingFunction(log, requestTimestamp)
}))(route)
}
}
开发者ID:shiv4nsh,项目名称:akka-http-logging-starter-kit,代码行数:55,代码来源:KnoldusRoutingServer.scala
示例20:
//设置package包名称以及导入依赖的类
package me.archdev
import me.archdev.restapi.http.HttpService
import me.archdev.restapi.models.{ TokenEntity, UserEntity }
import me.archdev.restapi.utils.Migration
import org.scalatest._
import akka.event.{ NoLogging, LoggingAdapter }
import akka.http.scaladsl.testkit.ScalatestRouteTest
import scala.concurrent.Await
import scala.concurrent.duration._
trait BaseServiceTest extends WordSpec with Matchers with ScalatestRouteTest with HttpService with Migration {
protected val log: LoggingAdapter = NoLogging
import driver.api._
val testUsers = Seq(
UserEntity(Some(1), "Arhelmus", "test"),
UserEntity(Some(2), "Arch", "test"),
UserEntity(Some(3), "Hierarh", "test")
)
val testTokens = Seq(
TokenEntity(userId = Some(1)),
TokenEntity(userId = Some(2)),
TokenEntity(userId = Some(3))
)
reloadSchema()
Await.result(db.run(users ++= testUsers), 10.seconds)
Await.result(db.run(tokens ++= testTokens), 10.seconds)
}
开发者ID:samuelmartingc,项目名称:Akka-REST-service,代码行数:35,代码来源:BaseServiceTest.scala
注:本文中的akka.event.LoggingAdapter类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论