Scala日志记录功能名称 [英] scala logging function name

查看:61
本文介绍了Scala日志记录功能名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的日志条目中,我想记录调用log方法的函数名称.

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?

换句话说,是否有可能提取运行上下文当前正在运行时执行的scala函数的名称?

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. The latter would be hard to read from logs.

推荐答案

这是您可以使用的 hack .它遍历当前堆栈跟踪以查找第一个非匿名函数.

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)
}

您可以像这样使用它:

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

明显的缺点是它的脆弱性.我完全不确定上面的单个正则表达式是否足以忽略所有匿名或其他无关紧要的功能.即使可以保证,命名架构在以后的Scala版本中也不会更改.

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日志记录功能名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆