scala logging function name

2019-03-31 01:15发布

In my log entries, I would like to log the function name in which the log method was called.

This is to automatically be able to filter log entries by function name. Is this possible? With any libraries? Any extensions with existing libraries?

In other words, is it possible to extract the name of the scala function the execution context is currently executing at runtime?

Secondary Question: I understand this may be far-fetched, but ideally, the closest enclosing named function which contained the logging call is preferred instead of the actual anonymous function that scala generates a cryptic name for. The latter would be hard to read from logs.

标签: scala logging
1条回答
相关推荐>>
2楼-- · 2019-03-31 01:59

Here is a hack that you could use. It traverses the current stack trace to find the first non-anonymous function.

def printStackFrame() {
  /* Get current stack trace. The first frame is this method call. */
  val st = new RuntimeException().getStackTrace.view.drop(1)

  // st take(5) foreach println /* Print a few frames of interest */

  val name =
    st.map(ste => ste.getClassName + "." + ste.getMethodName)
      .dropWhile(_.matches(""".*anonfun\$\d*\.apply\$mcV\$sp$"""))
      .apply(0)

  println(name)
}

You can use it like this:

class MyClass {
  def mydef() {
    printStackFrame()
  }

  def myhof(f: () => Unit) {
    f()
  }
}

val mc = new MyClass
mc.mydef() // Main$$anon$1$MyClass.mydef
mc.myhof(mc.mydef) // Main$$anon$1$MyClass.mydef
mc.myhof(() => {printStackFrame()}) // Main$$anon$1$MyClass.myhof

The obvious downside is its fragility. I am not at all sure if the single regex above suffices to ignore all anonymous or otherwise non-interesting functions. And even if, there are no guarantees that the naming schema doesn't change in future Scala versions.

查看更多
登录 后发表回答