Scala registration function name

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

This is automatic to filter log entries by function name. Is it possible? With any libraries? Any extensions with existing libraries?

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

Secondary question: I understand that this may be far-fetched, but ideally, the closest private named function containing the registration call is preferred over the actual anonymous function that scala generates the critical name. The latter would be difficult to read from magazines.

+4
source share
1 answer

Here is a hack you can 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 as follows:

 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 

An obvious disadvantage is its fragility. I'm not at all sure that one regular expression is enough to ignore all anonymous or otherwise not interesting functions. And even if there is no guarantee that the name scheme will not change in future versions of Scala.

+2
source

All Articles