jeudi, septembre 01, 2011

When programming in Java or Scala, I miss those C pre compiler macros __FILE__ , __LINE__ and __FUNC__ . I use them for logging where I am in my programs.

Well, I decided to have those in Scala, using Stack parsing after athrowing an interruption. I personally don't care if it's take time to execute.

There is one advantage compared to the C macros: you can get any upper level in the calling stack, which I sometimes find handy.


object util {
 val MatchFileLine = """.+\((.+)\..+:(\d+)\)""".r
 val MatchFunc = """(.+)\(.+""".r
 def main(args: Array[String]): Unit = { 
  println(util.tag(1))
  println(util.func(1))
 }
 def tag(i_level: Int): String = {
  val s_rien = ""
  try {
   throw new Exception()
  } catch {
   case unknown => unknown.getStackTrace.toList.apply(i_level).toString match {
    case MatchFileLine(file, line) => file+":"+line
    case _ => s_rien
   }
  }
 }

 def func(i_level: Int): String = {
  val s_rien = "functionNotFound"
  try {
   throw new Exception()
  } catch {
   case unknown => unknown.getStackTrace.toList.apply(i_level).toString match {
    case MatchFunc(funcs) => funcs.split('.').toList.last
    case _ => s_rien
   }
  } 
 }
}

class util() { }