我们如何在 Scala 中跟踪带有行号的表达式/打印语句?

How can we trace expressions / print statements with line numbers in Scala?

如果你想打印带有行号的语句,你该怎么做?

这取决于你想做什么。

使用 scala-trace-debug 库,您可以输入如下内容:

Debug.trace(1 + 2)

得到这个:

"3" in thread main:
    path.to.file(file.Scala: 22) // click-able stack trace

您可以自定义堆栈跟踪的行数,如下所示:

Debug.trace(1 + 2, 3) // 3 lines of stack trace

如果你这样做 info.collaboration_station.debug._,你甚至可以这样做:

val three = 3.trace

...

"3" in thread main:
    path.to.file(file.Scala: 22)

终于支持表达式了:

Debug.traceExpression{
    val myVal = 4
    1 + 2 + myVal
}

...

"{
  val myVal = 4;
  (3).+(myVal)
} -> 7" in thread main:
    at main.Main$.main(Main.scala:12)

与其他库不同,它更适合调试。如果我想提供正在发生的事情的历史记录并且我不想让用户看到堆栈跟踪,我就不会使用这个工具。

查看 Haoyi Li 的 sourcecode 图书馆,我认为它可以满足您的需求。

sourcecode is a small Scala library for that provides common "source code" context to your program at runtime, similar to Python's __name__, C++'s __LINE__ or Ruby's __FILE__. For example, you can ask for the file-name and line number of the current file, either through the () syntax or via an implicit.

参见示例https://github.com/lihaoyi/sourcecode#logging

You can use sourcecode.File and sourcecode.Line to define log functions that automatically capture their line number and file-name

def log(foo: String)(implicit line: sourcecode.Line, file: sourcecode.File) = {
  println(s"${file.value}:${line.value} $foo")
}

log("Foooooo") // sourcecode/shared/src/test/scala/sourcecode/Tests.scala:86 Fooooo