简体   繁体   English

Scala日志记录功能名称

[英]scala logging function name

In my log entries, I would like to log the function name in which the log method was called. 在我的日志条目中,我想记录调用log方法的函数名称。

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? 换句话说,是否可以提取运行上下文当前正在运行时的scala函数的名称?

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. 次要问题:我知道这可能牵强,但理想情况下,首选包含记录调用的最接近的封闭命名函数,而不是scala为之生成隐名的实际匿名函数。 The latter would be hard to read from logs. 后者将很难从日志中读取。

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. 即使可以保证,命名架构在以后的Scala版本中也不会更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM