gpt4 book ai didi

scala - 在 Scala 中定义日志记录特征时出现问题

转载 作者:行者123 更新时间:2023-12-02 00:36:47 24 4
gpt4 key购买 nike

似乎 scala 中常见的日志记录模式是使用与具体类混合的日志记录特征(参见 Liftweb、akka 等开源项目)。

类似的东西:

trait Logging {
val loggerName = this.getClass.getName
@transient lazy val log = new Logger(loggerName)
}

这正是我所知道的,但由于这种模式,我遇到了一个问题。实际上,如果 Logging 特征与派生类混合使用,则 Logger 将与最派生类的名称一起使用。

这里有一个例子来澄清我自己:

class Logger(logName : String){
def debug( msg : String ) { println("["+logName+"] : "+msg) }
}

trait Logging {
val loggerName = this.getClass.getName
@transient lazy val log = new Logger(loggerName)
}

package a {
class A extends Logging {
log.debug("log from A")
}
}

package b {
import a._
class B extends A with Logging {
log.debug("log from B")
}
}

object LogTest {
import b._
def main(args : Array[String]) = {
val instance = new B
}
}

当我运行这个程序时,我得到:

[b.B] : log from A
[b.B] : log from B

代替:

[a.A] : log from A
[b.B] : log from B

有没有人找到解决这个问题的方法?

最佳答案

我可以在伴随对象中使用记录器来实现这种效果:

object A extends Logging; 
class A { import A._
log.debug("log from A")
}

object B extends Logging;
class B extends A { import B._
log.debug("log from B")
}

关于scala - 在 Scala 中定义日志记录特征时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4286145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com