将日志源转换为字符串和类

将日志源转换为字符串和类
在运行时将源对象转换成要插入 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"
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值