Skip to content

Instantly share code, notes, and snippets.

@yuroyoro
Forked from j5ik2o/gist:1518723
Created January 13, 2012 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuroyoro/1604839 to your computer and use it in GitHub Desktop.
Save yuroyoro/1604839 to your computer and use it in GitHub Desktop.
こんな構文で階層型のログ出力をしたい
def connect = {
import LogOps._
log("connect") { implicit ctx => // connect start
// ... 何かの処理 ...
println("in connect")
log("login") { implicit ctx => // connect : login start
// ... 何かの処理 ...
println("in login")
} // connect : login end
// ... 何かの処理 ...
println("out login")
} // connect end
}
// implicit parameterで実現しればいいのかな... でも、名前が2種類になるのはダサいなー、、、logという名前で統一的に実現できればいいけど無理かなー
object LogOps {
sealed trait LogContext {
val ctxs:Seq[String]
def child(childCtx:String) = ActualLogContext(ctxs :+ childCtx)
override def toString = ctxs.mkString(":")
def debug(msg:String) = println("%s :%s" format(toString, msg))
}
case class ActualLogContext(ctxs:Seq[String]) extends LogContext
case object EmptyLogContext extends LogContext { val ctxs = Seq.empty[String] }
implicit val defaultLogContext:LogContext = EmptyLogContext
def log[T](msg:String)(f: LogContext => T)(implicit ctx:LogContext) = {
val currentContext = ctx.child(msg)
currentContext.debug("start")
val r = f(currentContext)
currentContext.debug("end")
r
}
}
connect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment