-
-
Save yuroyoro/1604839 to your computer and use it in GitHub Desktop.
こんな構文で階層型のログ出力をしたい
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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