Instrumentation to add logging to Scala code -


in java can use aspectj add logging transparently java classes (or use other byte code instrumentation tools). wonder how add logging transparently scala functions.

i tool transform function foo

 def foo(x:int) = x + 1 

to that:

 def foo(x:int) = {     log.trace("enter foo x = " + x) // added automatically    val r = x + 1    log.trace("exit foo r = " + r) // added automatically      r } 

how add logging transparently scala functions?

aspectj work fine scala code. you'll need follow scala name mangling rules (i.e. def > becomes def $gt) , on.

suppose have

class foo {   def foo(x: int) {   }   def bar() { } } 

to add logging, can use java aspectj syntax, adding

"org.aspectj" % "aspectjweaver" % "1.7.2", "org.aspectj" % "aspectjrt" % "1.7.2" 

to build.sbt. moving on, can have following aspect:

@aspect public class monitoraspect {      @pointcut(value = "execution (* your.package.foo.*(..))")     public void methodsinfoo() {}      @before("methodsinfoo()")     public void enter(joinpoint jp) {         // log     }      @after("methodsinfoo()")     public void exit(joinpoint jp) {     } } 

the final piece meta-inf/aop.xml, defines work load-time weaver:

<aspectj>      <aspects>         <aspect name="your.package.monitoraspect"/>     </aspects>      <weaver options="-xnoinline">         <include within="your.package.*"/>     </weaver>  </aspectj> 

finally, start jvm -javaagent:$path_to_aspectjweaver.jar , you're set.


in case, may worth thinking using higher-order functions. if using logging example, , if you're doing before , after inner function, should consider using hofs.

def logged[u](f: => u): u = {     log.info("before")     val ret = f     log.info("after")     ret } 

here, have logged function takes function f, deals logs , whatever f does.


Comments