How to get logging working in scala unit tests with testng, slf4s, and logback

后端 未结 4 920
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 23:51

I\'m new to Scala, and not that familiar with recent developments in Java, so I am having what I assume is a basic problem.

I\'m writing some Scala code, and testing

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-31 00:45

    The problem is that while the first thread is initializing the underlying logging implementation (blocking), for all other concurrent threads, SubstituteLoggerFactory is created. This substitute logger factory returns a SubstituteLogger instead the actual logger implementation. This issue isn't resolved in SLF4J-167.

    It is less likely to meet this issue in Java, because often logger objects are created as a static variable, so the LoggerFactory is being initialized during the class loading. In Scala there is no static modifier and companion objects are initialized lazily. Furthermore, most testing frameworks in Scala execute tests in parallel.

    To workaround this issue, you can change the test environment: as Bruno Bieth suggested you can initialize the LoggerFactory before the tests start. You can do that also in the test code rather than the build settings. You can also set the test to run sequentially, but then you lose speed.

    Alternatively you can eagerly initialize a Logger initialized in a companion object. Ugly, but in most cases ensures that Foo objects created concurrently won't be initialized with a SubstituteLogger.

    class Foo {
      val logger = Foo.singletonLogger
    }
    
    object Foo {
      val singletonLogger = LoggerFactory.getLogger(getClass)
    }
    

提交回复
热议问题