Skip to content

Instantly share code, notes, and snippets.

@notyy
Created March 12, 2012 15:13
Show Gist options
  • Save notyy/2022552 to your computer and use it in GitHub Desktop.
Save notyy/2022552 to your computer and use it in GitHub Desktop.
logger with value
def myFunc() = {
val rs = calcSomeResult()
logger.info("result is:" + rs)
rs
}
避免上面的麻烦写法:
object LogUtil {
def kestrel[A](x: A)(f: A => Unit): A = { f(x); x }
def logV[A](f: String => Unit)(s: String, x: A) = kestrel(x) { y => f(s + ": " + y) }
}
----------------------------
class LogUtilSpec extends FlatSpec with ShouldMatchers {
val logger = LoggerFactory.getLogger(this.getClass())
import LogUtil._
"LogUtil" should "print log info and keep the value, and the calc for value should only be called once" in {
def calcValue = { println("calcValue"); 100 } // to confirm it's called only once
val v = logV(logger.info)("result is", calcValue)
v should be === 100
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment