将日志源转换为字符串和类
在运行时将源对象转换成要插入 LogEvent 的源字符串和类的规则是使用隐式参数的方式实现的, 因此是可配置的: 只需要创建你自己的 LogSource[T] 实例并将它放在创建logger的作用域中即可。
这个例子创建了一个日志源来模拟Java logger的传统用法,该日志源使用原对象的类名作为日志类别。 在这里加入对 getClazz 的重写只是为了作说明,因为它精确地包含了缺省行为。
Note
你也可以先创建字符串然后将它作为日志源传入,但要知道这时 LogEvent 中的 Class[_] 将是 akka.event.DummyClassForStringSources.
在运行时将源对象转换成要插入 LogEvent 的源字符串和类的规则是使用隐式参数的方式实现的, 因此是可配置的: 只需要创建你自己的 LogSource[T] 实例并将它放在创建logger的作用域中即可。
import akka.event.LogSource
import akka.actor.ActorSystem
object MyType {
implicit val logSource: LogSource[AnyRef] = new LogSource[AnyRef] {
def genString(o: AnyRef): String = o.getClass.getName
override def getClazz(o: AnyRef): Class[_] = o.getClass
}
}
class MyType(system: ActorSystem) {
import MyType._
import akka.event.Logging
val log = Logging(system, this)
}
这个例子创建了一个日志源来模拟Java logger的传统用法,该日志源使用原对象的类名作为日志类别。 在这里加入对 getClazz 的重写只是为了作说明,因为它精确地包含了缺省行为。
Note
你也可以先创建字符串然后将它作为日志源传入,但要知道这时 LogEvent 中的 Class[_] 将是 akka.event.DummyClassForStringSources.
SLF4J 事件监听器对这种情况会特殊处理 (使用实际的字符串来查找logger实例而不是类名), 你在实现自己的日志适配器时可能也会这么做。
完整的例子:
import akka.actor._
import akka.actor.Props
import akka.event.Logging
import akka.actor.ActorSystem
import akka.util.Timeout
import akka.pattern.ask
import scala.concurrent.duration._
import akka.actor.ReceiveTimeout
import akka.pattern.gracefulStop
import scala.concurrent.{Await,Future}
import akka.event.LogSource
import akka.actor.ActorSystem
object MyType {
implicit val logSource: LogSource[AnyRef] = new LogSource[AnyRef] {
def genString(o: AnyRef): String = o.getClass.getName
override def getClazz(o: AnyRef): Class[_] = o.getClass
}
}
class MyType(system: ActorSystem) {
import MyType._
import akka.event.Logging
val log = Logging(system, this)
}
class MyActor extends Actor{
//设置接受数据的时间
context.setReceiveTimeout(30 milliseconds)
val log = new MyType(context.system)
import context._
def receive = {
case "test" =>
log.log.info("receiveed test")
//通过seder发送消息
sender() ! "OK I receive your msg"
case ReceiveTimeout =>
context.setReceiveTimeout(Duration.Undefined)
}
}
object MyTest1{
val prop1 = Props[MyActor]
val sytem = ActorSystem("mtSystem")
implicit val timeout = Timeout(5 seconds)
//创建Actor
val myActor = sytem.actorOf(prop1,"MyActor")
def main(args: Array[String]): Unit = {
val date = myActor ? "test"
}
}