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


Scala Logging类代码示例

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


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

示例1: Main

//设置package包名称以及导入依赖的类
import akka.actor.ActorSystem
import akka.event.Logging
import akka.event.Logging.InfoLevel
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import com.google.inject.Guice
import service.documents.{DocumentService, DocumentServiceModule}
import service.health._

object Main extends App with HealthRoutes {
  
  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()
  implicit val ec = system.dispatcher 

  val settings = Settings(system)

  val logger = Logging(system, getClass)

  private val injector = Guice.createInjector(DocumentServiceModule)
  private val docService = injector.getInstance(classOf[DocumentService])
  
  val routes = logRequestResult("", InfoLevel)(docService.docRoutes ~ healthRoutes)

  Http().bindAndHandle(routes, settings.Http.interface, settings.Http.port) map { binding =>
    logger.info(s"Server started on port {}", binding.localAddress.getPort)
  } recoverWith { case _ => system.terminate() }
} 
开发者ID:devknutst,项目名称:watermarkAkka,代码行数:30,代码来源:Main.scala

示例2: SeqUpdatesManagerRegion

//设置package包名称以及导入依赖的类
package im.actor.server.sequence

import akka.actor.{ ActorRef, ActorSystem, Props }
import akka.cluster.sharding.{ ClusterSharding, ClusterShardingSettings, ShardRegion }
import akka.event.Logging

import scala.util.{ Success, Try }

final case class SeqUpdatesManagerRegion(ref: ActorRef)

object SeqUpdatesManagerRegion {

  import UserSequenceCommands._

  private def extractEntityId(system: ActorSystem): ShardRegion.ExtractEntityId = {
    val log = Logging(system, getClass)

    {
      case e @ Envelope(userId, payload) ? (userId.toString, Try(e.getField(Envelope.descriptor.findFieldByNumber(payload.number))) match {
        case Success(any) ? any
        case _ ?
          val error = new RuntimeException(s"Payload not found for $e")
          log.error(error, error.getMessage)
          throw error
      })
    }
  }

  private val extractShardId: ShardRegion.ExtractShardId = {
    case Envelope(userId, _) ? (userId % 10).toString // TODO: configurable
  }

  private val typeName = "SeqUpdatesManager"

  private def start(props: Props)(implicit system: ActorSystem): SeqUpdatesManagerRegion =
    SeqUpdatesManagerRegion(ClusterSharding(system).start(
      typeName = typeName,
      entityProps = props,
      settings = ClusterShardingSettings(system),
      extractEntityId = extractEntityId(system),
      extractShardId = extractShardId
    ))

  def start()(
    implicit
    system: ActorSystem
  ): SeqUpdatesManagerRegion =
    start(UserSequence.props)

  def startProxy()(implicit system: ActorSystem): SeqUpdatesManagerRegion =
    SeqUpdatesManagerRegion(ClusterSharding(system).startProxy(
      typeName = typeName,
      role = None,
      extractEntityId = extractEntityId(system),
      extractShardId = extractShardId
    ))
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:58,代码来源:SeqUpdatesManagerRegion.scala

示例3: LogSourceSpec

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

import scala.concurrent.duration._
import akka.testkit.AkkaSpec
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.Props
import akka.event.Logging
import akka.testkit.ImplicitSender
import akka.testkit.TestProbe
import akka.actor.Deploy
import akka.event.Logging.Info
import akka.actor.ExtendedActorSystem

object LogSourceSpec {
  class Reporter extends Actor with ActorLogging {
    def receive = {
      case s: String ?
        log.info(s)
    }
  }
}

@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class LogSourceSpec extends AkkaSpec(
  """
    akka.loglevel = INFO
    akka.actor.provider = "akka.remote.RemoteActorRefProvider"
    akka.remote.netty.tcp.port = 0
  """) {

  import LogSourceSpec._

  val reporter = system.actorOf(Props[Reporter], "reporter")
  val logProbe = TestProbe()
  system.eventStream.subscribe(system.actorOf(Props(new Actor {
    def receive = {
      case i @ Info(_, _, msg: String) if msg contains "hello" ? logProbe.ref ! i
      case _ ?
    }
  }).withDeploy(Deploy.local), "logSniffer"), classOf[Logging.Info])

  "Log events" must {

    "should include host and port for local LogSource" in {
      reporter ! "hello"
      val info = logProbe.expectMsgType[Info]
      info.message should be("hello")
      val defaultAddress = system.asInstanceOf[ExtendedActorSystem].provider.getDefaultAddress
      info.logSource should include(defaultAddress.toString)
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:54,代码来源:LogSourceSpec.scala

示例4: CsvParsingStage

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.csv

import akka.event.Logging
import akka.stream.stage.{GraphStage, GraphStageLogic, InHandler, OutHandler}
import akka.stream.{Attributes, FlowShape, Inlet, Outlet}
import akka.util.ByteString

import scala.annotation.tailrec
import scala.util.control.NonFatal


private[csv] class CsvParsingStage(delimiter: Byte, quoteChar: Byte, escapeChar: Byte)
    extends GraphStage[FlowShape[ByteString, List[ByteString]]] {

  private val in = Inlet[ByteString](Logging.simpleName(this) + ".in")
  private val out = Outlet[List[ByteString]](Logging.simpleName(this) + ".out")
  override val shape = FlowShape(in, out)

  override protected def initialAttributes: Attributes = Attributes.name("CsvParsing")

  override def createLogic(inheritedAttributes: Attributes) =
    new GraphStageLogic(shape) with InHandler with OutHandler {
      private[this] val buffer = new CsvParser(delimiter, quoteChar, escapeChar)

      setHandlers(in, out, this)

      override def onPush(): Unit = {
        buffer.offer(grab(in))
        tryPollBuffer()
      }

      override def onPull(): Unit =
        tryPollBuffer()

      override def onUpstreamFinish(): Unit = {
        emitRemaining()
        completeStage()
      }

      private def tryPollBuffer() =
        try buffer.poll(requireLineEnd = true) match {
          case Some(csvLine) ? push(out, csvLine)
          case _ ?
            if (isClosed(in)) {
              emitRemaining()
              completeStage()
            } else pull(in)
        } catch {
          case NonFatal(ex) ? failStage(ex)
        }

      @tailrec private def emitRemaining(): Unit =
        buffer.poll(requireLineEnd = false) match {
          case Some(csvLine) ?
            emit(out, csvLine)
            emitRemaining()
          case _ ?
        }

    }
} 
开发者ID:akka,项目名称:alpakka,代码行数:62,代码来源:CsvParsingStage.scala

示例5: MagdaApp

//设置package包名称以及导入依赖的类
package au.csiro.data61.magda

import akka.actor.{ Actor, ActorLogging, ActorSystem, DeadLetter, Props }
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import au.csiro.data61.magda.api.SearchApi
import au.csiro.data61.magda.search.elasticsearch.{ DefaultClientProvider, ElasticSearchQueryer }

object MagdaApp extends App {
  implicit val config = AppConfig.conf()
  implicit val system = ActorSystem("search-api", config)
  implicit val executor = system.dispatcher
  implicit val materializer = ActorMaterializer()
  implicit val clientProvider = new DefaultClientProvider

  implicit val logger = Logging(system, getClass)

  logger.info("Starting API in env {} on port {}", AppConfig.getEnv, config.getString("http.port"))

  val listener = system.actorOf(Props(classOf[Listener]))
  system.eventStream.subscribe(listener, classOf[DeadLetter])

  logger.debug("Starting API")
  val searchQueryer = ElasticSearchQueryer.apply
  val api = new SearchApi(searchQueryer)

  val interface = Option(System.getenv("npm_package_config_interface")).orElse(Option(config.getString("http.interface"))).getOrElse("127.0.0.1")
  val port = Option(System.getenv("npm_package_config_port")).map(_.toInt).orElse(Option(config.getInt("http.port"))).getOrElse(6101)

  Http().bindAndHandle(api.routes, interface, port)
}

class Listener extends Actor with ActorLogging {
  def receive = {
    case d: DeadLetter => log.debug(d.message.toString())
  }
} 
开发者ID:TerriaJS,项目名称:magda,代码行数:39,代码来源:MagdaApp.scala

示例6: 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

示例7: MagdaApp

//设置package包名称以及导入依赖的类
package au.csiro.data61.magda

import akka.actor.{ Actor, ActorLogging, ActorSystem, DeadLetter, Props }
import akka.event.Logging
import akka.stream.ActorMaterializer
import au.csiro.data61.magda.api.Api
import au.csiro.data61.magda.crawler.Supervisor
import au.csiro.data61.magda.external.InterfaceConfig
import com.typesafe.config.{ ConfigObject, ConfigValue }

import scala.collection.JavaConversions._

object MagdaApp extends App {
  implicit val system = ActorSystem()
  implicit val executor = system.dispatcher
  implicit val materializer = ActorMaterializer()
  implicit val config = AppConfig.conf

  val logger = Logging(system, getClass)

  logger.info("Starting MAGDA CKAN Crawler with env {}", AppConfig.env)

  val listener = system.actorOf(Props(classOf[Listener]))
  system.eventStream.subscribe(listener, classOf[DeadLetter])

  val interfaceConfigs = config.getConfig("indexedServices").root().map {
    case (name: String, serviceConfig: ConfigValue) =>
      InterfaceConfig(serviceConfig.asInstanceOf[ConfigObject].toConfig)
  }.toSeq

  val supervisor = system.actorOf(Props(new Supervisor(system, config, interfaceConfigs)))

  // Index erryday 
  //  system.scheduler.schedule(0 millis, 1 days, supervisor, Start(List((ExternalInterfaceType.CKAN, new URL(config.getString("services.dga-api.baseUrl"))))))

  val api = new Api()
}

class Listener extends Actor with ActorLogging {
  def receive = {
    case d: DeadLetter => log.debug(d.message.toString())
  }
} 
开发者ID:TerriaJS,项目名称:magda-ckan,代码行数:44,代码来源:MagdaApp.scala

示例8: 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

示例9: DataProducer

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

import akka.actor._
import akka.event.Logging
import akka.stream.scaladsl.SourceQueueWithComplete
import com.omearac.producers.DataProducer.PublishMessages
import com.omearac.shared.EventMessages.{ActivatedProducerStream, MessagesPublished}
import com.omearac.shared.EventSourcing
import com.omearac.shared.KafkaMessages.KafkaMessage



object DataProducer {

  //Command Messages
  case class PublishMessages(numberOfMessages: Int)

  def props: Props = Props(new DataProducer)

}

class DataProducer extends Actor with EventSourcing {

  import context._

  implicit val system = context.system
  val log = Logging(system, this.getClass.getName)

  var producerStream: SourceQueueWithComplete[Any] = null

  def receive: Receive = {
    case ActivatedProducerStream(streamRef, kafkaTopic) =>
      producerStream = streamRef
      become(publishData)
    case msg: PublishMessages => if (producerStream == null) self ! msg
    case other => log.error("DataProducer got the unknown message while in idle: " + other)
  }

  def publishData: Receive = {
    case PublishMessages(numberOfMessages) =>
      for (i <- 1 to numberOfMessages) {
        val myPublishableMessage = KafkaMessage(timetag, " send me to kafka, yo!", i)
        producerStream.offer(myPublishableMessage)
      }

      //Tell the akka-http front end that messages were sent
      sender() ! MessagesPublished(numberOfMessages)
      publishLocalEvent(MessagesPublished(numberOfMessages))
    case other => log.error("DataProducer got the unknown message while producing: " + other)
  }
} 
开发者ID:omearac,项目名称:reactive-kafka-microservice-template,代码行数:52,代码来源:DataProducer.scala

示例10: WebServer

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

import akka.event.Logging
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import base.conf.ApiEnvConfig
import base.{ ApiSnapshots, Contexts }
import com.typesafe.config.Config
import module.RoutingModule
import provider.GraphSupport
import scalikejdbc.config._

import scala.concurrent.{ Await, Future }

object WebServer extends App with RoutingModule with ApiEnvConfig {
  override implicit val system = Contexts.system
  override implicit val executor = system.dispatcher
  override implicit val materializer = ActorMaterializer()

  new DBs with TypesafeConfigReader with StandardTypesafeConfig with NoEnvPrefix {
    override lazy val config: Config = configuration.envConfiguration.config
  }.setupAll()

  override val logger = Logging(system, getClass)

  private val interface: String = configuration.HTTP.interface
  private val port: Int = configuration.HTTP.port

  init()
    .flatMap(_ ? Http().bindAndHandle(wsRoutes, interface, port))
    .map(_ ? logger.info(s"Server online at http://$interface:$port/..."))
    .recover { case exc: Throwable ? logger.error(exc, s"WebServer failed to initialize.") }

  def init() = Future {
    logger.info("Application starting...")
    val graphFut = ApiSnapshots
      .initializeAsync()
      .map(_ ? GraphSupport.getGraphSet) // Load graph
    Await.result(graphFut, configuration.Graph.loadingTimeout)
    logger.info("Application started successfully...")
  }

} 
开发者ID:cspinetta,项目名称:footpath-routing,代码行数:44,代码来源:WebServer.scala

示例11: AkkademyDB

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

import com.akkademy.messages._
import akka.actor.{Props, ActorSystem, Status, Actor}
import akka.event.Logging
import scala.collection.mutable.HashMap

class AkkademyDB extends Actor
{
  val map = new HashMap[String,Object]
  val log = Logging(context.system, this)
  override def receive() = 
  {
    case SetRequest(key, value) =>
        log.info("Received SetRequest - key: {} value {}", key, value)
        map.put(key, value)
	sender() ! Status.Success
    case GetRequest(key) =>
	log.info("received GetRequest - key: {}", key)
	val response: Option[Object] = map.get(key)
	response match
		{
			case Some(x) => sender() ! x
			case None => sender() ! Status.Failure(new KeyNotFoundException(key))
		}
    case o => Status.Failure(new ClassNotFoundException)
  }
}

object Main extends App {
	val system = ActorSystem("akkademy")
	system.actorOf(Props[AkkademyDB], name = "akkademy-db")
} 
开发者ID:Edmond1983,项目名称:akkademydb-ch2,代码行数:34,代码来源:AkkademyDB.scala

示例12: PushFutureListener

//设置package包名称以及导入依赖的类
package im.actor.server.sequence

import akka.actor.ActorSystem
import akka.event.Logging
import com.relayrides.pushy.apns.PushNotificationResponse
import com.relayrides.pushy.apns.util.SimpleApnsPushNotification
import im.actor.server.model.push.ApplePushCredentials
import im.actor.util.log.AnyRefLogSource
import io.netty.util.concurrent.{ Future, GenericFutureListener }
import scodec.bits.BitVector

import scala.util.{ Failure, Success, Try }

final class PushFutureListener(userId: Int, creds: ApplePushCredentials, credsId: String)(implicit system: ActorSystem)
  extends GenericFutureListener[Future[PushNotificationResponse[SimpleApnsPushNotification]]] with AnyRefLogSource {

  private val log = Logging(system, this)
  private val seqUpdExt = SeqUpdatesExtension(system)
  private val tokenBytes = creds.token.toByteArray
  private val tokenString = BitVector(tokenBytes).toHex

  def operationComplete(future: Future[PushNotificationResponse[SimpleApnsPushNotification]]): Unit = {
    Try(future.get()) match {
      case Success(response) ?
        log.debug(
          "APNS send complete, user: {}, token: {}, cert id: {}",
          userId, tokenString, credsId
        )
        if (response.isAccepted) {
          log.debug(
            "Successfully delivered APNS notification to user: {}, token: {}, cert id: {}",
            userId, tokenString, credsId
          )
        } else {
          log.warning(
            s"APNS rejected notification for user: {}, token: {}, cert id: {}, with reason: {}",
            userId, tokenString, credsId, response.getRejectionReason
          )
          Option(response.getTokenInvalidationTimestamp) foreach { ts ?
            log.warning("APNS token: {} for user: {} invalidated at {}. Deleting token now", tokenString, userId, ts)
            seqUpdExt.unregisterApplePushCredentials(tokenBytes)
          }
        }
      case Failure(e) ?
        log.error(e, "Failed to send APNS notification for user: {}, token: {}, cert id: {}",
          userId, tokenString, credsId)
    }
  }

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:51,代码来源:PushFutureListener.scala

示例13: TcpFrontend

//设置package包名称以及导入依赖的类
package im.actor.server.frontend

import akka.actor._
import akka.event.Logging
import akka.stream.{ ActorMaterializer, Materializer }
import akka.stream.scaladsl._
import im.actor.server.session.SessionRegion

import scala.concurrent.duration._

object TcpFrontend extends Frontend("tcp") {
  val IdleTimeout = 30.minutes

  def start(host: String, port: Int, serverKeys: Seq[ServerKey])(
    implicit
    sessionRegion: SessionRegion,
    system:        ActorSystem
  ): Unit = {
    val log = Logging.getLogger(system, this)
    implicit val materializer: Materializer = ActorMaterializer()

    Tcp().bind(host, port, idleTimeout = IdleTimeout)
      .to(Sink.foreach {
        case (conn @ Tcp.IncomingConnection(localAddress, remoteAddress, flow)) ?
          log.debug("New TCP connection from {}", localAddress)

          val mtProto = mtProtoBlueprint(serverKeys, remoteAddress.getAddress())
          flow.joinMat(mtProto)(Keep.right).run()
      })
      .run()
  }
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:33,代码来源:TcpFrontend.scala

示例14: Session

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

import akka.actor.ActorRef
import akka.actor.Actor
import akka.event.Logging

class Session(user: String, fromClient: ActorRef, storage: ActorRef) extends Actor {
  private val loginTime = System.currentTimeMillis
  private var userLog: List[String] = Nil
  val log = Logging(context.system, this)
  log.info("New session for user [%s] has been created at [%s]".format(user, loginTime))

  def receive: Actor.Receive = {
    case msg @ ChatMessage(from, message) =>
      userLog ::= message
      storage forward msg //forward server to storage

    case msg @ GetChatLog(_) =>
      storage forward msg
    
    case msg @ AddFriend(user,friend) =>
      log.info("session keep client is %s".format(fromClient))
      log.info("session from %s".format(sender()))
      storage ! msg
    
    case msg @ ChatMessageTo(from,to,message)=>
      storage ! msg
    case msg @ GetChatMessageTo(from,to)=>
      storage ! msg  
      
    case msg : ChatLog =>
      log.info("session keep client is %s".format(fromClient))
      log.info("rev friends message");
      fromClient ! msg
  }
} 
开发者ID:Chehao,项目名称:Akkala,代码行数:37,代码来源:Session.scala

示例15: MemoryChatStorage

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

import akka.actor.Actor
import akka.event.Logging
import scala.collection.mutable.HashMap
import scala.collection.mutable.ListBuffer


trait ChatStorage extends Actor

class MemoryChatStorage extends ChatStorage {
  //self.lifeCycle = Permanent

  private var chatLog: ListBuffer[String] = ListBuffer("< Room >")
  val friends: HashMap[String, ListBuffer[String]] = HashMap[String, ListBuffer[String]]()
  private val chatMessageStorage: HashMap[String, HashMap[String, ListBuffer[String]]] = HashMap[String, HashMap[String, ListBuffer[String]]]()

  val log = Logging(context.system, this)
  log.info("Memory-based chat storage is starting up...")

  def receive = {
    case msg @ ChatMessage(from, message) =>
      log.info("New chat message [%s] from sender : %s".format(message, sender()))
      chatLog += message
      if (chatLog.size >= 10) {
        val messageList = chatLog.slice(chatLog.size - 10, chatLog.size)
        sender() ! ChatLog(messageList)
      } else {
        val messageList = chatLog
        sender() ! ChatLog(messageList)
      }

    case msg @ ChatMessageTo(from, to, message) =>
      log.info("New chat message (%s->%s) [%s] from sender : %s".format(from, to, message, sender()))
      val fromUserMap = chatMessageStorage.getOrElseUpdate(from, HashMap[String, ListBuffer[String]]())
      val msgs = fromUserMap.getOrElseUpdate(to, ListBuffer[String]("< " + to + " >")) += message
      //add message to target MessabBox map
      val toUserMap = chatMessageStorage.getOrElseUpdate(to, HashMap[String, ListBuffer[String]]())
      val msgTo = toUserMap.getOrElseUpdate(from, ListBuffer[String]("< " + from + " >")) += message

      sender() ! ChatLog(msgs)

    case msg @ GetChatMessageTo(from, to) =>
      val fromUserMap = chatMessageStorage.getOrElseUpdate(from, HashMap[String, ListBuffer[String]]())
      val msgs = fromUserMap.getOrElseUpdate(to, ListBuffer[String]("< " + to + " >"))
      sender() ! ChatLog(msgs)

    case GetChatLog(_) =>
      val messageList = chatLog
      sender() ! ChatLog(messageList)

    case msg @ AddFriend(user, friend) =>
      log.info("AddFriend message %s->%s from sender : %s".format(user, friend, sender()))
      val friendList = friends.getOrElseUpdate(user, ListBuffer[String]("<Friend List>")) += friend
      sender() ! ChatLog(friendList)

  }

  override def postRestart(reason: Throwable) = chatLog = ListBuffer()
} 
开发者ID:Chehao,项目名称:Akkala,代码行数:61,代码来源:MemoryChatStorage.scala


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