How to add tracing within a 'for' comprehension?

后端 未结 5 1799
离开以前
离开以前 2021-01-30 17:49

For log tracing inside a for comprehension, I\'ve used dummy assignment like this:

val ll = List(List(1,2),List(1))            

for {
  outer <         


        
5条回答
  •  孤独总比滥情好
    2021-01-30 18:16

    Flaviu's answer inspired me to try playing with implicits. The idea is to see if the trace looks better with the 'trace' further to the right on the line:

    import Trace._
    
    object Main {  
      def main(args:Array[String])  {
        val listList = List(List(1,2,3), List(3,4))    
        for {
          list <- trace1(listList, "lList is: %s", listList)  // trace() 
          item <- list traced("list is: %s", list)            // implicit         
        } yield item
    

    I also wanted to try mixing in error logging in the same comprehension. Error logging seems to look best mixed with Daniel's approach:

        val optOpt:Option[Option[Int]] = Some(Some(1))
        for {
          opt <- optOpt;
          _ = trace2("opt found: %s", opt)   // trying Daniel's suggestion
          int <- opt orElse 
            err("num not found in: %s", opt)   // together with error logging
        } yield int
      }
    }
    

    Here's the supporting code for both experiments:

    object Trace {
      def trace1[T](any:T, message:String, params:AnyRef*):T = {
        Console println String.format("TRA: " + message, params:_*)
        any
      }
    
      def trace2[T](message:String, params:AnyRef*) {
        Console println String.format("TRA: " + message, params:_*)
      }
    
      def err[T](message:String, params:AnyRef*):Option[T] = {
        Console println String.format("ERR: " + message, params:_*)
        None
      }
    
      implicit def anyRefToTraceable[T](anyRef:T):Traceable[T] = {
        new Traceable(anyRef)
      }
    
      class Traceable[T](val self:T) {
        def traced(message:String, params:AnyRef*):T = {
          Console println String.format("TRA: " + message, params:_*)
          self
        }  
      }  
    }
    

提交回复
热议问题