Skip to content

Instantly share code, notes, and snippets.

@j5ik2o
Created January 14, 2012 15:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j5ik2o/1611868 to your computer and use it in GitHub Desktop.
Save j5ik2o/1611868 to your computer and use it in GitHub Desktop.
AOPを使わなくても処理の始まりと終わりにログを出力するtrait
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