2016-03-21 35 views
0

根據我的理解,只有在創建新任務或使用:=運算符進行設置時,才能訪問streams.value.log用於登錄Scala的設計模式SBT Autoplugin

我找對streams.value.log背景下的良好格局或許一些增強的知識,使我能避免以下幾點:

  1. 傳遞stream.value.log到每一個函數鏈,如。 GetBucket(...,logger:sbt.Logger)=> ParseBucketName(...,logger:sbt.Logger)=> GetBucketName(...,logger:sbt.Logger)=>等..

  2. 這樣做有一個全局可變像這樣

    trait AWSPluginUtils 
    { 
    
        //mutable logger: don't have to pass sbt.logger through every function 
    
        private var _logger: Any = None 
    
        def setLogger(sbtLogger: Logger): Unit = { 
         _logger = sbtLogger 
        } 
    
        def getLogger(): Logger = { 
         _getLogger 
        } 
    
        lazy val _getLogger: Logger = _logger match { 
         case l: sbt.Logger => l 
        } 
    
        def infoLog(message: String): Unit = { 
        getLogger().info(message) 
        } 
    
        def debugLog(message: String): Unit = { 
        getLogger().info(message) 
        } 
    
        def errLog(message: String): Nothing = { 
        getLogger().error(message) 
        throw new RuntimeException(message) 
        } 
    } 
    
+0

你爲什麼要避免1?這是IMO的正確答案。如果你想減少樣板,你可以使用'logger'和你的函數的隱含參數。 – sjrd

回答

0

我結束了使用隱式參數,使我不必通過明確通過功能層次傳遞streams.value.log,例如。

trait PluginUtils { 

def debugLog(message: String)(implicit logger: Logger): Unit = { 
    logger.info(message) 
    } 


//auto plugin definition (with my trait) 
object doStuffPlugin extends AutoPlugin with PluginUtils { 


//in override of set settings 

private lazyval settings: Seq[Setting[_]] = Seq(
    doStuff in Global := { 
      implicit val logger: Logger = streams.value.log 
      doStuff(
      region = region.value, 
      ......... 


//function that I'm calling 
private def doStuff(region: String)(implicit logger: Logger) 
debugLog("doStuff now") } 

現在我可以隱含參數(implicit logger: Logger)只是添加到調用鏈中的任何功能,我沒有通過記錄下來的參考4個級別。