在 scala 中为 logging/debuging 确定执行上下文的线程池输出

Nicifying execution contex's thread pool's output for logging/debuging in scala

是否有将池 in/for 重命名为 executon context 以在 logs/wile 调试中产生更好输出的好方法。不要看起来像 ForkJoinPool-2-worker-7(因为 ~2 没有说明池在应用程序中的用途)而是 WorkForkJoinPool-2-worker -7.. 没有为它创建新的 WorkForkJoinPool class?

示例:

object LogSample extends App {

  val ex1 = ExecutionContext.global
  val ex2 = ExecutionContext.fromExecutor(null:Executor) // another global ex context

  val system = ActorSystem("system")

  val log = Logging(system.eventStream, "my.nice.string")

  Future {
    log.info("1")
  }(ex1)

  Future {
    log.info("2")
  }(ex2)

  Thread.sleep(1000)

  // output, like this:

  /*
   [INFO] [09/14/2015 21:53:34.897] [ForkJoinPool-2-worker-7] [my.nice.string] 2
   [INFO] [09/14/2015 21:53:34.897] [ForkJoinPool-1-worker-7] [my.nice.string] 1
  */
}

好的。由于 current scala ExecutonContext implementation.

,这似乎是不可能的(特别是默认全局 iml

我能做的只是复制 并替换:

class DefaultThreadFactory(daemonic: Boolean) ... {
def wire[T <: Thread](thread: T): T = {
  thread.setName("My" + thread.getId) // ! add this one (make 'My' to be variable)
  thread.setDaemon(daemonic)
  thread.setUncaughtExceptionHandler(uncaughtExceptionHandler)
  thread
}...

因为threadFactory那里

val threadFactory = new DefaultThreadFactory(daemonic = true)

已硬编码...

(似乎 Vladimir Petrosyan 首先展示了更好的方式 :))

您需要实现自定义线程工厂,如下所示:

class CustomThreadFactory(prefix: String) extends ForkJoinPool.ForkJoinWorkerThreadFactory {
    def newThread(fjp: ForkJoinPool): ForkJoinWorkerThread = {
      val thread = new ForkJoinWorkerThread(fjp) {}
      thread.setName(prefix + "-" + thread.getName)
      thread
    }
  }

  val threadFactory = new CustomThreadFactory("custom prefix here")

  val uncaughtExceptionHandler = new UncaughtExceptionHandler {
    override def uncaughtException(t: Thread, e: Throwable) = e.printStackTrace()
  }

  val executor = new ForkJoinPool(10, threadFactory, uncaughtExceptionHandler, true)
  val ex2 = ExecutionContext.fromExecutor(executor) // another global ex context

  val system = ActorSystem("system")

  val log = Logging(system.eventStream, "my.nice.string")


  Future {
    log.info("2") //[INFO] [09/15/2015 18:22:43.728] [custom prefix here-ForkJoinPool-1-worker-29] [my.nice.string] 2
  }(ex2)

  Thread.sleep(1000)