2016-03-21 36 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个级别。