AOPを使わなくても処理の始まりと終わりにログを出力するtrait
This file contains 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
import scala.util.DynamicVariable | |
import scala.collection.immutable | |
import grizzled.slf4j.Logging | |
trait LoggingEx extends Logging { | |
private val msgs = new DynamicVariable[Seq[String]](immutable.Queue.empty) | |
private def withScope[T](msg: String, logger: (=> Any, => Throwable) => Unit, f: => T): T = { | |
val newMsgs = msgs.value :+ msg | |
val str = newMsgs.mkString(" : ") | |
logger("%s : start".format(str), null) | |
val r = msgs.withValue(newMsgs) { | |
f | |
} | |
logger("%s : end".format(str), null) | |
r | |
} | |
private def scoped[T](msg: String, logger: (=> Any, => Throwable) => Unit) { | |
val newMsgs = msgs.value :+ msg | |
val str = newMsgs.mkString(" : ") | |
logger(str, null) | |
} | |
def withInfoScope[T](msg: String)(f: => T): T = if (isInfoEnabled) withScope(msg, info _, f) else f | |
def withWarnScope[T](msg: String)(f: => T): T = if (isWarnEnabled) withScope(msg, warn _, f) else f | |
def withErrorScope[T](msg: String)(f: => T): T = if (isErrorEnabled) withScope(msg, error _, f) else f | |
def withDebugScope[T](msg: String)(f: => T): T = if (isDebugEnabled) withScope(msg, debug _, f) else f | |
def scopedInfo(msg: String) { | |
if (isInfoEnabled) scoped(msg, info _) | |
} | |
def scopedWarn(msg: String) { | |
if (isWarnEnabled) scoped(msg, warn _) | |
} | |
def scopedError(msg: String) { | |
if (isErrorEnabled) scoped(msg, error _) | |
} | |
def scopedDebug(msg: String) { | |
if (isDebugEnabled) scoped(msg, debug _) | |
} | |
} | |
// -- | |
def printWord(msg:String):String = withDebugScope("printWord"){ // printWord : start | |
scopedDebug("msg = " + msg) // printWord : msg = XXX | |
println(msg) | |
msg | |
} // printWord : end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment